</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK" />
+ <component name="ProjectType">
+ <option name="id" value="jpab" />
+ </component>
</project>
\ No newline at end of file
<artifactId>lis-services</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
package hu.user.lis;
-import hu.user.lis.ui.config.WebSecurityConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.FilterType;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.SpringVersion;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
-//@SpringBootApplication(scanBasePackages = {"hu.user.lis"})
-@SpringBootApplication(exclude = {
- org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
- org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration.class}
-)
-@ComponentScan(basePackages = {"hu.user.lis"}, excludeFilters = {
- @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = WebSecurityConfig.class)})
+@SpringBootApplication(scanBasePackages = {"hu.user.lis"})
+//@SpringBootApplication(exclude = {
+// org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
+// org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration.class}
+//)
+//@ComponentScan(basePackages = {"hu.user.lis"}, excludeFilters = {
+// @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = WebSecurityConfig.class)})
@EnableWebMvc
//@EnableMongoRepositories(basePackages = "hu.user.lis.db.repository")
-@EnableJpaRepositories(basePackages = "hu.user.lis.db.repository")
+@EnableJpaRepositories("hu.user.lis.db.repository")
public class Main extends SpringBootServletInitializer implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger logger = LogManager.getLogger();
homepage: index
zul-view-resolver-enabled: true
spring:
+ jpa:
+ hibernate:
+ use-new-id-generator-mappings: false
+ show-sql: true
+ properties:
+ hibernate:
+ format_sql: true
output:
ansi:
enabled: always
--- /dev/null
+### HTTP server
+server:
+ port: 8080
+ servlet:
+ context-path: /
+
+### ZKoss
+zk:
+ homepage: index
+ zul-view-resolver-enabled: true
+### Spring
+spring:
+ #active: dev
+ # profiles:
+ #main:
+ # banner-mode: off
+ output:
+ ansi:
+ enabled: always
+ mail:
+ host: smtp.gmail.com
+ port: 465
+ username: mediacubeserver@gmail.com
+ password: salabakter
+ protocol: smtps
+ properties:
+ mail:
+ smtp:
+ auth: true
+ starttls:
+ enable: true
+ #datasources:
+ # maszkaweb:
+ # driver-class-name: com.mysql.jdbc.Driver
+ # type: com.zaxxer.hikari.HikariDataSource
+ # jdbcUrl: jdbc:mysql://localhost:3306/maszkaweb?useUnicode=true&characterEncoding=UTF-8
+ # username: root
+ # password: password
+ # pool-name: pool-maszkaweb
+ # maximum-pool-size: 50
+ # minimum-idle: 10
+ # data:
+ # mongodb:
+ # # host: dvdev.in.useribm.hu
+ # host: localvm
+ # port: 27017
+ # database: lis
+
+ # username: db2admin
+ # password: password
+# datasource:
+# # driver-class-name: com.mysql.jdbc.Driver
+# type: com.zaxxer.hikari.HikariDataSource
+# url: jdbc:db2://localvm:50000/testmc
+# username: db2admin
+# password: password
+# hikari:
+# pool-name: testmc
+# maximum-pool-size: 50
+# minimum-idle: 10
+service:
+ message: Hello, World
-### HTTP server
server:
port: 8080
servlet:
context-path: /
-
-### ZKoss
zk:
homepage: index
zul-view-resolver-enabled: true
-### Spring
spring:
- #active: dev
- # profiles:
- #main:
- # banner-mode: off
+ jpa:
+ hibernate:
+ use-new-id-generator-mappings: false
+ show-sql: false
+ properties:
+ hibernate:
+ format_sql: true
output:
ansi:
enabled: always
- mail:
- host: smtp.gmail.com
- port: 465
- username: mediacubeserver@gmail.com
- password: salabakter
- protocol: smtps
- properties:
- mail:
- smtp:
- auth: true
- starttls:
- enable: true
- #datasources:
- # maszkaweb:
- # driver-class-name: com.mysql.jdbc.Driver
- # type: com.zaxxer.hikari.HikariDataSource
- # jdbcUrl: jdbc:mysql://localhost:3306/maszkaweb?useUnicode=true&characterEncoding=UTF-8
- # username: root
- # password: password
- # pool-name: pool-maszkaweb
- # maximum-pool-size: 50
- # minimum-idle: 10
- # data:
- # mongodb:
- # # host: dvdev.in.useribm.hu
- # host: localvm
- # port: 27017
- # database: lis
-
- # username: db2admin
- # password: password
-# datasource:
-# # driver-class-name: com.mysql.jdbc.Driver
-# type: com.zaxxer.hikari.HikariDataSource
-# url: jdbc:db2://localvm:50000/testmc
-# username: db2admin
-# password: password
-# hikari:
-# pool-name: testmc
-# maximum-pool-size: 50
-# minimum-idle: 10
-service:
- message: Hello, World
+ datasource:
+ type: com.zaxxer.hikari.HikariDataSource
+ url: jdbc:db2://dvdev.in.useribm.hu:50000/lis
+ username: db2admin
+ password: password
+logging:
+ level:
+ org.hibernate.engine.jdbc.spi.SqlExceptionHelper: ERROR
+ org.springframework.security.web: DEBUG
+# pattern:
+# console: "%d %-5level %logger : %msg%n"
+# file: "%d %-5level [%thread] %logger : %msg%n"
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) $today.year-$today.month-24.
+ * By elGekko
+ */
+
+package hu.user.lis;
+
+import hu.user.lis.db.ServiceRecord;
+import hu.user.lis.db.repository.ServiceRecordRepository;
+import lombok.extern.log4j.Log4j2;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import java.util.List;
+
+
+@Log4j2
+@RunWith(SpringRunner.class)
+@ComponentScan("hu.user.lis")
+@SpringBootTest
+//@TestPropertySource("classpath:application.yaml")
+//@AutoConfigureMockMvc
+public class ITRepository {
+ @Autowired
+ private ServiceRecordRepository serviceRecordRepository;
+
+ @Test
+ public void testRepositoryCapabilities() {
+ List<ServiceRecord> allItems = serviceRecordRepository.findAll();
+ ServiceRecord serviceRecord = allItems.get(0);
+
+ List<ServiceRecord> filteredItems1 = serviceRecordRepository.findByProjectIdAndAssociateId(serviceRecord.getProject().getId(), serviceRecord.getAssociate().getId());
+ log.info("Found {} items", filteredItems1.size());
+
+ List<ServiceRecord> filteredItems2 = serviceRecordRepository.findByProjectIdAndAssociateId(serviceRecord.getProject().getId(), null);
+ log.info("Found {} items", filteredItems2.size());
+ }
+
+}
Migration script with the --help option.
Enjoy.
+
+
+
+DOCKER
+docker run -itd --name lis --privileged=true -p 50000:50000 -p 27017:27017 -e LICENSE=accept -e DB2INSTANCE=db2admin -e DB2INST1_PASSWORD=password -e DBNAME=lis -e PERSISTENT_HOME=true -v /Docker:/database ibmcom/db2
+docker logs -f lis
+docker exec -it lis bash
+docker stop lis
+docker remove lis
--- /dev/null
+## Base time zone to ensure times are consistent across machines
+time_zone=GMT+0:00
+
+## The character set that scripts are encoded with
+script_char_set=UTF-8
+
+## JDBC connection properties.
+driver=com.ibm.db2.jcc.DB2Driver
+url=jdbc:db2://dvdev.in.useribm.hu:50000/lis
+username=db2admin
+password=password
+
+#
+# A NOTE ON STORED PROCEDURES AND DELIMITERS
+#
+# Stored procedures and functions commonly have nested delimiters
+# that conflict with the schema migration parsing. If you tend
+# to use procs, functions, triggers or anything that could create
+# this situation, then you may want to experiment with
+# send_full_script=true (preferred), or if you can't use
+# send_full_script, then you may have to resort to a full
+# line delimiter such as "GO" or "/" or "!RUN!".
+#
+# Also play with the autocommit settings, as some drivers
+# or databases don't support creating procs, functions or
+# even tables in a transaction, and others require it.
+#
+
+# This ignores the line delimiters and
+# simply sends the entire script at once.
+# Use with JDBC drivers that can accept large
+# blocks of delimited text at once.
+send_full_script=false
+
+# This controls how statements are delimited.
+# By default statements are delimited by an
+# end of line semicolon. Some databases may
+# (e.g. MS SQL Server) may require a full line
+# delimiter such as GO.
+# These are ignored if send_full_script is true.
+delimiter=;
+full_line_delimiter=false
+
+# If set to true, each statement is isolated
+# in its own transaction. Otherwise the entire
+# script is executed in one transaction.
+# Few databases should need this set to true,
+# but some do.
+auto_commit=false
+
+# If set to false, warnings from the database will interrupt migrations.
+ignore_warnings=false
+
+# Custom driver path to allow you to centralize your driver files
+# Default requires the drivers to be in the drivers directory of your
+# initialized migration directory (created with "migrate init")
+# driver_path=
+
+# Name of the table that tracks changes to the database
+changelog=CHANGELOG
+
+# Migrations support variable substitutions in the form of ${variable}
+# in the migration scripts. All of the above properties will be ignored though,
+# with the exception of changelog.
+# Example: The following would be referenced in a migration file as ${ip_address}
+# ip_address=192.168.0.1
+
-- // create_initial_schema
-- Migration SQL that makes the change goes here.
CREATE TABLE associate (
- id BIGINT NOT NULL,
- name VARCHAR(255),
- login VARCHAR(255),
- password VARCHAR(255),
- monthly_cost DOUBLE NOT NULL,
- active SMALLINT NOT NULL,
- CONSTRAINT pk_associate PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ name VARCHAR(255),
+ login VARCHAR(255),
+ password VARCHAR(255),
+ monthly_cost DOUBLE NOT NULL,
+ active SMALLINT NOT NULL,
+ CONSTRAINT pk_associate PRIMARY KEY (id)
);
CREATE TABLE edocument (
- id BIGINT NOT NULL,
- created TIMESTAMP,
- name VARCHAR(255),
- description VARCHAR(255),
- size INTEGER NOT NULL,
- file BLOB,
- CONSTRAINT pk_edocument PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ created TIMESTAMP,
+ name VARCHAR(255),
+ description VARCHAR(255),
+ size INTEGER NOT NULL,
+ file BLOB,
+ CONSTRAINT pk_edocument PRIMARY KEY (id)
);
CREATE TABLE project_status (
- id BIGINT NOT NULL,
- name VARCHAR(255),
- active SMALLINT NOT NULL,
- order INTEGER NOT NULL,
- CONSTRAINT pk_projectstatus PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ name VARCHAR(255),
+ active SMALLINT NOT NULL,
+ order INTEGER NOT NULL,
+ CONSTRAINT pk_projectstatus PRIMARY KEY (id)
);
CREATE TABLE partner (
- id BIGINT NOT NULL,
- name VARCHAR(255),
- vat_nr VARCHAR(255),
- address VARCHAR(255),
- active SMALLINT NOT NULL,
- CONSTRAINT pk_partner PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ name VARCHAR(255),
+ vat_nr VARCHAR(255),
+ address VARCHAR(255),
+ active SMALLINT NOT NULL,
+ CONSTRAINT pk_partner PRIMARY KEY (id)
);
CREATE TABLE project (
- id BIGINT NOT NULL,
- project_status_id BIGINT,
- name VARCHAR(255),
- human_id VARCHAR(255),
- contact_name VARCHAR(255),
- partner_id BIGINT,
- active SMALLINT NOT NULL,
- CONSTRAINT pk_project PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ project_status_id BIGINT,
+ name VARCHAR(255),
+ human_id VARCHAR(255),
+ contact_name VARCHAR(255),
+ partner_id BIGINT,
+ active SMALLINT NOT NULL,
+ CONSTRAINT pk_project PRIMARY KEY (id)
);
ALTER TABLE project ADD CONSTRAINT FK_PROJECT_ON_PARTNER FOREIGN KEY (partner_id) REFERENCES partner (id);
ALTER TABLE project ADD CONSTRAINT FK_PROJECT_ON_PROJECT_STATUS FOREIGN KEY (project_status_id) REFERENCES project_status (id);
CREATE TABLE invoice (
- id BIGINT NOT NULL,
- human_id VARCHAR(255),
- title VARCHAR(255),
- partner_id BIGINT,
- project_id BIGINT,
- income SMALLINT NOT NULL,
- currency INTEGER,
- net_amount DOUBLE NOT NULL,
- gross_amount DOUBLE NOT NULL,
- vat_amount DOUBLE NOT NULL,
- completion_date TIMESTAMP,
- create_date TIMESTAMP,
- payment_deadline TIMESTAMP,
- planned SMALLINT NOT NULL,
- file BLOB,
- CONSTRAINT pk_invoice PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ human_id VARCHAR(255),
+ title VARCHAR(255),
+ partner_id BIGINT,
+ project_id BIGINT,
+ income SMALLINT NOT NULL,
+ currency INTEGER,
+ net_amount DOUBLE NOT NULL,
+ gross_amount DOUBLE NOT NULL,
+ vat_amount DOUBLE NOT NULL,
+ completion_date TIMESTAMP,
+ create_date TIMESTAMP,
+ payment_deadline TIMESTAMP,
+ planned SMALLINT NOT NULL,
+ file BLOB,
+ CONSTRAINT pk_invoice PRIMARY KEY (id)
);
ALTER TABLE invoice ADD CONSTRAINT FK_INVOICE_ON_PARTNER FOREIGN KEY (partner_id) REFERENCES partner (id);
ALTER TABLE invoice ADD CONSTRAINT FK_INVOICE_ON_PROJECT FOREIGN KEY (project_id) REFERENCES project (id);
CREATE TABLE treasury (
- id BIGINT NOT NULL,
- project_id BIGINT,
- human_id VARCHAR(255),
- buy_amount DOUBLE NOT NULL,
- buy_currency INTEGER,
- sell_amount DOUBLE NOT NULL,
- sell_currency INTEGER,
- transaction_date TIMESTAMP,
- value_date TIMESTAMP,
- file BLOB,
- CONSTRAINT pk_treasury PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ project_id BIGINT,
+ human_id VARCHAR(255),
+ buy_amount DOUBLE NOT NULL,
+ buy_currency INTEGER,
+ sell_amount DOUBLE NOT NULL,
+ sell_currency INTEGER,
+ transaction_date TIMESTAMP,
+ value_date TIMESTAMP,
+ file BLOB,
+ CONSTRAINT pk_treasury PRIMARY KEY (id)
);
ALTER TABLE treasury ADD CONSTRAINT FK_TREASURY_ON_PROJECT FOREIGN KEY (project_id) REFERENCES project (id);
CREATE TABLE project_associate (
- id BIGINT NOT NULL,
- project_id BIGINT,
- associate_id BIGINT,
- CONSTRAINT pk_projectassociate PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ project_id BIGINT,
+ associate_id BIGINT,
+ CONSTRAINT pk_projectassociate PRIMARY KEY (id)
);
ALTER TABLE project_associate ADD CONSTRAINT FK_PROJECTASSOCIATE_ON_ASSOCIATE FOREIGN KEY (associate_id) REFERENCES associate (id);
ALTER TABLE project_associate ADD CONSTRAINT FK_PROJECTASSOCIATE_ON_PROJECT FOREIGN KEY (project_id) REFERENCES project (id);
CREATE TABLE service_record (
- id BIGINT NOT NULL,
- project_id BIGINT,
- associate_id BIGINT,
- work_day TIMESTAMP,
- description VARCHAR(255),
- details VARCHAR(255),
- work_hours INTEGER NOT NULL,
- cost DOUBLE NOT NULL,
- file BLOB,
- CONSTRAINT pk_servicerecord PRIMARY KEY (id)
+ id BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
+ project_id BIGINT,
+ associate_id BIGINT,
+ work_day TIMESTAMP,
+ description VARCHAR(255),
+ details VARCHAR(255),
+ work_hours INTEGER NOT NULL,
+ cost DOUBLE NOT NULL,
+ file BLOB,
+ CONSTRAINT pk_servicerecord PRIMARY KEY (id)
);
ALTER TABLE service_record ADD CONSTRAINT FK_SERVICERECORD_ON_ASSOCIATE FOREIGN KEY (associate_id) REFERENCES associate (id);
ALTER TABLE service_record ADD CONSTRAINT FK_SERVICERECORD_ON_PROJECT FOREIGN KEY (project_id) REFERENCES project (id);
<artifactId>lis</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.mybatis.maven</groupId>
+ <artifactId>migrations-maven-plugin</artifactId>
+ <version>1.1.4</version>
+ <configuration>
+ <repository>${project.basedir}/migrations</repository>
+ </configuration>
+ <dependencies>
+ <dependency>
+ <groupId>com.ibm.db2</groupId>
+ <artifactId>jcc</artifactId>
+ <version>11.5.8.0</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+ </plugins>
+ </build>
<dependencies>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-mongodb</artifactId>
- <version>3.4.6</version>
- </dependency>
- <dependency>
- <groupId>org.mongodb</groupId>
- <artifactId>mongodb-driver-sync</artifactId>
- <version>4.9.1</version>
- </dependency>
-
-
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<artifactId>jcc</artifactId>
<version>11.5.8.0</version>
</dependency>
-
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
package hu.user.lis.db;
import lombok.*;
-import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@Setter
@Entity
@Builder
-@Document
@AllArgsConstructor
@NoArgsConstructor
public class Associate {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
String login;
package hu.user.lis.db;
import lombok.*;
-import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@Setter
@Entity
@Builder
-@Document
@AllArgsConstructor
@NoArgsConstructor
public class EDocument {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
Date created;
String name;
package hu.user.lis.db;
import lombok.*;
-import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.*;
import java.util.Date;
@Setter
@Entity
@Builder
-@Document
@AllArgsConstructor
@NoArgsConstructor
public class Invoice {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String humanId;
String title;
package hu.user.lis.db;
import lombok.*;
-import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@Setter
@Entity
@Builder
-@Document
@AllArgsConstructor
@NoArgsConstructor
public class Partner {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
String vatNr;
package hu.user.lis.db;
import lombok.*;
-import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.*;
import java.util.List;
@Setter
@Entity
@Builder
-@Document
@AllArgsConstructor
@NoArgsConstructor
public class Project {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
@JoinColumn(name = "project_status_id")
package hu.user.lis.db;
import lombok.*;
-import org.springframework.data.mongodb.core.mapping.Document;
-import org.springframework.data.mongodb.core.mapping.DocumentReference;
import javax.persistence.*;
@Setter
@Entity
@Builder
-@Document
@AllArgsConstructor
@NoArgsConstructor
public class ProjectAssociate {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
@JoinColumn(name = "project_id")
- @DocumentReference
Project project;
@ManyToOne
@JoinColumn(name = "associate_id")
- @DocumentReference
Associate associate;
}
@Table(name = "project_status")
public class ProjectStatus {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
boolean active;
package hu.user.lis.db;
+import com.fasterxml.jackson.annotation.JsonIncludeProperties;
import lombok.*;
-import org.springframework.data.mongodb.core.mapping.Document;
-import org.springframework.data.mongodb.core.mapping.DocumentReference;
import javax.persistence.*;
import java.util.Date;
@Setter
@Entity
@Builder
-@Document
@AllArgsConstructor
@NoArgsConstructor
public class ServiceRecord {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
@JoinColumn(name = "project_id")
- @DocumentReference(lazy = true)
+ @JsonIncludeProperties({"id"})
Project project;
@ManyToOne
@JoinColumn(name = "associate_id")
- @DocumentReference(lazy = true)
+ @JsonIncludeProperties({"id"})
Associate associate;
Date workDay;
String description;
package hu.user.lis.db;
import lombok.*;
-import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.*;
import java.util.Date;
@Setter
@Builder
@Entity
-@Document
@AllArgsConstructor
@NoArgsConstructor
public class Treasury {
@Id
- @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
@JoinColumn(name = "project_id")
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Associate;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface AssociateRepository extends JpaRepository<Associate, Long>, AssociateRepositorySearch {
+
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Associate;
+import org.springframework.data.domain.Pageable;
+
+import java.util.List;
+
+public interface AssociateRepositorySearch {
+ List<Associate> search(String partialName, boolean filterShowActive, boolean filterShowInActive, Pageable pageable);
+
+ long count(String partialName, boolean filterShowActive, boolean filterShowInActive);
+
+// List<Associate> search(String partialName, boolean filterShowActive, Pageable pageable);
+//
+// long count(String partialName, boolean filterShowActive);
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Associate;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.data.domain.Pageable;
+import org.springframework.stereotype.Repository;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+import java.util.ArrayList;
+import java.util.List;
+
+@Repository
+public class AssociateRepositorySearchImpl implements AssociateRepositorySearch {
+ @PersistenceContext
+ EntityManager entityManager;
+
+ Predicate[] getPredicates(CriteriaBuilder cb, Root<Associate> root, String partialName, boolean filterShowActive, boolean filterShowInActive) {
+ List<Predicate> predicates = new ArrayList<>();
+ if (StringUtils.isNotBlank(partialName)) {
+ predicates.add(cb.like(cb.lower(root.get("name")), "%" + partialName.toLowerCase() + "%"));
+ }
+ if (filterShowActive && !filterShowInActive) {
+ predicates.add(cb.isTrue(root.get("active")));
+ }
+ if (filterShowInActive && !filterShowActive) {
+ predicates.add(cb.isFalse(root.get("active")));
+ }
+ return predicates.toArray(new Predicate[]{});
+ }
+
+// Predicate[] getPredicates(CriteriaBuilder cb, Root<Associate> root, String partialName, boolean filterShowActive) {
+// List<Predicate> predicates = new ArrayList<>();
+// if (StringUtils.isNotBlank(partialName)) {
+// predicates.add(cb.like(root.get("name"), "%" + partialName + "%"));
+// }
+// if (filterShowActive) {
+// predicates.add(cb.isTrue(root.get("active")));
+// } else {
+// predicates.add(cb.isFalse(root.get("active")));
+// }
+// return predicates.toArray(new Predicate[]{});
+// }
+
+ @Override
+ public List<Associate> search(String partialName, boolean filterShowActive, boolean filterShowInActive, Pageable pageable) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery<Associate> cq = cb.createQuery(Associate.class);
+ Root<Associate> root = cq.from(Associate.class);
+ TypedQuery<Associate> query = entityManager.createQuery(cq);
+ cq.where(getPredicates(cb, root, partialName, filterShowActive, filterShowInActive));
+ query.setMaxResults(pageable.getPageSize());
+ query.setFirstResult(pageable.getPageSize() * pageable.getPageNumber());
+ return query.getResultList();
+ }
+
+ @Override
+ public long count(String partialName, boolean filterShowActive, boolean filterShowInActive) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery<Long> cq = cb.createQuery(Long.class);
+ Root<Associate> root = cq.from(Associate.class);
+ cq.select(cb.count(root));
+ cq.where(getPredicates(cb, root, partialName, filterShowActive, filterShowInActive));
+ return entityManager.createQuery(cq).getSingleResult();
+ }
+
+// @Override
+// public List<Associate> search(String partialName, boolean filterShowActive, Pageable pageable) {
+// CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+// CriteriaQuery<Associate> cq = cb.createQuery(Associate.class);
+// Root<Associate> root = cq.from(Associate.class);
+// TypedQuery<Associate> query = entityManager.createQuery(cq);
+// cq.where(getPredicates(cb, root, partialName, filterShowActive));
+// query.setMaxResults(pageable.getPageSize());
+// query.setFirstResult(pageable.getPageSize() * pageable.getPageNumber());
+// return query.getResultList();
+// }
+//
+// @Override
+// public long count(String partialName, boolean filterShowActive) {
+// CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+// CriteriaQuery<Long> cq = cb.createQuery(Long.class);
+// Root<Associate> root = cq.from(Associate.class);
+// cq.select(cb.count(root));
+// cq.where(getPredicates(cb, root, partialName, filterShowActive));
+// return entityManager.createQuery(cq).getSingleResult();
+// }
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Invoice;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
+
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Partner;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface PartnerRepository extends JpaRepository<Partner, Long>, PartnerRepositorySearch {
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Partner;
+import org.springframework.data.domain.Pageable;
+
+import java.util.List;
+
+public interface PartnerRepositorySearch {
+ List<Partner> search(String partialName, String partialVatNr, String partialAddress, boolean filterShowActive, boolean filterShowInActive, Pageable pageable);
+
+ long count(String partialName, String partialVatNr, String partialAddress, boolean filterShowActive, boolean filterShowInActive);
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Partner;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.data.domain.Pageable;
+import org.springframework.stereotype.Repository;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+import java.util.ArrayList;
+import java.util.List;
+
+@Repository
+public class PartnerRepositorySearchImpl implements PartnerRepositorySearch {
+ @PersistenceContext
+ EntityManager entityManager;
+
+ Predicate[] getPredicates(CriteriaBuilder cb, Root<Partner> root, String partialName,
+ String partialVatNr, String partialAddress, boolean filterShowActive, boolean filterShowInActive) {
+ List<Predicate> predicates = new ArrayList<>();
+ List<Predicate> orPredicates = new ArrayList<>();
+ if (StringUtils.isNotBlank(partialName)) {
+ orPredicates.add(cb.like(root.get("name"), "%" + partialName + "%"));
+ }
+ if (StringUtils.isNotBlank(partialVatNr)) {
+ orPredicates.add(cb.like(root.get("vat_nr"), "%" + partialVatNr + "%"));
+ }
+ if (StringUtils.isNotBlank(partialAddress)) {
+ orPredicates.add(cb.like(root.get("address"), "%" + partialAddress + "%"));
+ }
+ if (orPredicates.size() > 0) {
+ predicates.add(cb.or(orPredicates.toArray(new Predicate[]{})));
+ }
+ if (filterShowActive && !filterShowInActive) {
+ predicates.add(cb.isTrue(root.get("active")));
+ }
+ if (filterShowInActive && !filterShowActive) {
+ predicates.add(cb.isFalse(root.get("active")));
+ }
+ return predicates.toArray(new Predicate[]{});
+ }
+
+ Predicate[] getPredicates(CriteriaBuilder cb, Root<Partner> root, String partialName, boolean filterShowActive) {
+ List<Predicate> predicates = new ArrayList<>();
+ if (StringUtils.isNotBlank(partialName)) {
+ predicates.add(cb.like(root.get("name"), "%" + partialName + "%"));
+ }
+ if (filterShowActive) {
+ predicates.add(cb.isTrue(root.get("active")));
+ } else {
+ predicates.add(cb.isFalse(root.get("active")));
+ }
+ return predicates.toArray(new Predicate[]{});
+ }
+
+ @Override
+ public List<Partner> search(String partialName, String partialVatNr, String partialAddress, boolean filterShowActive, boolean filterShowInActive, Pageable pageable) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery<Partner> cq = cb.createQuery(Partner.class);
+ Root<Partner> root = cq.from(Partner.class);
+ cq.where(getPredicates(cb, root, partialName, partialVatNr, partialAddress, filterShowActive, filterShowInActive));
+ TypedQuery<Partner> query = entityManager.createQuery(cq);
+ query.setMaxResults(pageable.getPageSize());
+ query.setFirstResult(pageable.getPageSize() * pageable.getPageNumber());
+ return query.getResultList();
+ }
+
+ @Override
+ public long count(String partialName, String partialVatNr, String partialAddress, boolean filterShowActive, boolean filterShowInActive) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery<Long> cq = cb.createQuery(Long.class);
+ Root<Partner> root = cq.from(Partner.class);
+ cq.select(cb.count(root));
+ cq.where(getPredicates(cb, root, partialName, partialVatNr, partialAddress, filterShowActive, filterShowInActive));
+ return entityManager.createQuery(cq).getSingleResult();
+ }
+
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.ProjectAssociate;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface ProjectAssociateRepository extends JpaRepository<ProjectAssociate, Long> {
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Project;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface ProjectRepository extends JpaRepository<Project, Long>, ProjectRepositorySearch {
+
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Project;
+import org.springframework.data.domain.Pageable;
+
+import java.util.List;
+
+public interface ProjectRepositorySearch {
+ List<Project> search(String partialName, boolean filterShowActive, boolean filterShowInActive, Pageable pageable);
+
+ long count(String partialName, boolean filterShowActive, boolean filterShowInActive);
+
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Project;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.data.domain.Pageable;
+import org.springframework.stereotype.Repository;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+import java.util.ArrayList;
+import java.util.List;
+
+@Repository
+public class ProjectRepositorySearchImpl implements ProjectRepositorySearch {
+ @PersistenceContext
+ EntityManager entityManager;
+
+ Predicate[] getPredicates(CriteriaBuilder cb, Root<Project> root, String partialName, boolean filterShowActive, boolean filterShowInActive) {
+ List<Predicate> predicates = new ArrayList<>();
+ if (StringUtils.isNotBlank(partialName)) {
+ List<Predicate> orPredicates = new ArrayList<>();
+ orPredicates.add(cb.like(cb.lower(root.get("name")), "%" + partialName.toLowerCase() + "%"));
+ orPredicates.add(cb.like(cb.lower(root.get("humanId")), "%" + partialName.toLowerCase() + "%"));
+ orPredicates.add(cb.like(cb.lower(root.join("partner").get("name")), "%" + partialName.toLowerCase() + "%"));
+ predicates.add(cb.or(orPredicates.toArray(new Predicate[]{})));
+ }
+
+ if (filterShowActive && !filterShowInActive) {
+ predicates.add(cb.isTrue(root.get("active")));
+ }
+ if (filterShowInActive && !filterShowActive) {
+ predicates.add(cb.isFalse(root.get("active")));
+ }
+ return predicates.toArray(new Predicate[]{});
+ }
+
+ @Override
+ public List<Project> search(String partialName, boolean filterShowActive, boolean filterShowInActive, Pageable pageable) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery<Project> cq = cb.createQuery(Project.class);
+ Root<Project> root = cq.from(Project.class);
+ TypedQuery<Project> query = entityManager.createQuery(cq);
+ cq.where(getPredicates(cb, root, partialName, filterShowActive, filterShowInActive));
+ query.setMaxResults(pageable.getPageSize());
+ query.setFirstResult(pageable.getPageSize() * pageable.getPageNumber());
+ return query.getResultList();
+ }
+
+ @Override
+ public long count(String partialName, boolean filterShowActive, boolean filterShowInActive) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery<Long> cq = cb.createQuery(Long.class);
+ Root<Project> root = cq.from(Project.class);
+ cq.select(cb.count(root));
+ cq.where(getPredicates(cb, root, partialName, filterShowActive, filterShowInActive));
+ return entityManager.createQuery(cq).getSingleResult();
+ }
+}
package hu.user.lis.db.repository;
import hu.user.lis.db.ProjectStatus;
+import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
-import org.springframework.data.jpa.repository.Modifying;
-import org.springframework.data.jpa.repository.Query;
-import org.springframework.transaction.annotation.Transactional;
+
+import java.util.List;
public interface ProjectStatusRepository extends JpaRepository<ProjectStatus, Long> {
- @Modifying
- @Transactional
- @Query(value = "TRUNCATE TABLE project_status IMMEDIATE", nativeQuery = true)
- void truncate();
+ List<ProjectStatus> findByActiveIsTrue(Sort sort);
+
+ long countByActiveIsTrue();
}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.ServiceRecord;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+import java.util.List;
+
+public interface ServiceRecordRepository extends JpaRepository<ServiceRecord, Long>, ServiceRecordRepositorySearch {
+ List<ServiceRecord> findByProjectId(Long projectId);
+
+ List<ServiceRecord> findByProjectIdAndAssociateId(Long projectId, Long associateId);
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.ServiceRecord;
+import org.springframework.data.domain.Pageable;
+
+import java.util.List;
+
+public interface ServiceRecordRepositorySearch {
+ List<ServiceRecord> search(Long filterProjectId, Long filterAssociateId, Pageable pageable);
+
+ long count(Long filterProjectId, Long filterAssociateId);
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.ServiceRecord;
+import org.springframework.data.domain.Pageable;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+public class ServiceRecordRepositorySearchImpl implements ServiceRecordRepositorySearch {
+ @PersistenceContext
+ EntityManager entityManager;
+
+ Predicate[] getPredicates(CriteriaBuilder cb, Root<ServiceRecord> root, Long filterProjectId, Long filterAssociateId) {
+ List<Predicate> predicates = new ArrayList<>();
+ if (Objects.nonNull(filterProjectId)) {
+ predicates.add(cb.equal(root.join("project").get("id"), filterProjectId));
+ }
+ if (Objects.nonNull(filterAssociateId)) {
+ predicates.add(cb.equal(root.join("associate").get("id"), filterAssociateId));
+ }
+ return predicates.toArray(new Predicate[]{});
+ }
+
+ @Override
+ public List<ServiceRecord> search(Long filterProjectId, Long filterAssociateId, Pageable pageable) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery<ServiceRecord> cq = cb.createQuery(ServiceRecord.class);
+ Root<ServiceRecord> root = cq.from(ServiceRecord.class);
+ cq.where(getPredicates(cb, root, filterProjectId, filterAssociateId));
+ TypedQuery<ServiceRecord> query = entityManager.createQuery(cq);
+ query.setMaxResults(pageable.getPageSize());
+ query.setFirstResult(pageable.getPageSize() * pageable.getPageNumber());
+ return query.getResultList();
+ }
+
+ @Override
+ public long count(Long filterProjectId, Long filterAssociateId) {
+ CriteriaBuilder cb = entityManager.getCriteriaBuilder();
+ CriteriaQuery<Long> cq = cb.createQuery(Long.class);
+ Root<ServiceRecord> root = cq.from(ServiceRecord.class);
+ cq.select(cb.count(root));
+ cq.where(getPredicates(cb, root, filterProjectId, filterAssociateId));
+ return entityManager.createQuery(cq).getSingleResult();
+ }
+}
--- /dev/null
+package hu.user.lis.db.repository;
+
+import hu.user.lis.db.Treasury;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface TreasuryRepository extends JpaRepository<Treasury, Long> {
+
+}
<artifactId>spring-web</artifactId>
<version>5.3.24</version>
</dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.12.0</version>
- </dependency>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
+++ /dev/null
-package hu.user.lis.services;
-
-import org.springframework.http.MediaType;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import java.util.Arrays;
-import java.util.List;
-
-@RestController
-@RequestMapping(path = "/onetwo", produces = MediaType.APPLICATION_JSON_VALUE)
-public class OneTwoService {
- @GetMapping
- public List<String> findAll() {
- return Arrays.asList("One2", "Two1");
- }
-
-}
package hu.user.lis.services.api;
import hu.user.lis.db.Associate;
-import hu.user.lis.services.nosql.AssociateDbService;
-import hu.user.lis.services.nosql.DbService;
+import hu.user.lis.db.repository.AssociateRepository;
+import hu.user.lis.services.data.AssociateService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
@Log4j2
@RestController
@RequestMapping("/api/associate")
-public class AssociateApi extends DbApi<Associate> {
+public class AssociateApi extends DbApi<Associate, AssociateRepository, AssociateService> {
@Autowired
- AssociateDbService associateDbService;
+ AssociateRepository associateRepository;
+ @Autowired
+ AssociateService associateService;
+
+ @Override
+ protected AssociateService getService() {
+ return associateService;
+ }
@Override
- protected DbService<Associate> getDbService() {
- return associateDbService;
+ protected AssociateRepository getRepository() {
+ return associateRepository;
}
}
package hu.user.lis.services.api;
-import hu.user.lis.services.nosql.DbService;
-import org.springframework.web.bind.annotation.*;
+import hu.user.lis.services.data.DataService;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
-public abstract class DbApi<T> {
+public abstract class DbApi<T, R extends JpaRepository<T, Long>, S extends DataService<T>> {
- protected abstract DbService<T> getDbService();
+ protected abstract S getService();
+
+ protected abstract R getRepository();
@GetMapping("/list")
public List<T> list() {
- return getDbService().list();
+ return getRepository().findAll();
}
@GetMapping("/get/{id}")
- public T get(@PathVariable String id) {
- return getDbService().get(id);
- }
-
- @PostMapping("/create")
- public T create(@RequestBody T entity) {
- return getDbService().insert(entity);
+ public T get(@PathVariable long id) {
+ return getRepository().findById(id).orElse(null);
}
- @PutMapping("/update")
- public void update(@RequestBody T entity) {
- getDbService().save(entity);
+ @PostMapping("/save")
+ public T save(@RequestBody T entity) {
+ return getRepository().save(entity);
}
- @GetMapping("/reset")
- public void reset() {
- getDbService().reset();
+ @GetMapping("/delete")
+ public void deleteAll() {
+ getRepository().deleteAll();
}
@GetMapping("/generate")
public List<T> generate() {
- return getDbService().generate();
+ deleteAll();
+ return getRepository().saveAll(getService().getAll());
}
}
package hu.user.lis.services.api;
-import hu.user.lis.services.nosql.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
@RequestMapping("/api/generate")
public class GenerateApi {
@Autowired
- ProjectStatusDbService projectStatusDbService;
+ ProjectStatusApi projectStatusApi;
@Autowired
- PartnerDbService partnerDbService;
+ ProjectApi projectApi;
@Autowired
- AssociateDbService associateDbService;
+ PartnerApi partnerApi;
@Autowired
- InvoiceDbService invoiceDbService;
+ AssociateApi associateApi;
@Autowired
- TreasuryDbService treasuryDbService;
+ InvoiceApi invoiceApi;
@Autowired
- ProjectDbService projectDbService;
+ TreasuryApi treasuryApi;
@Autowired
- ProjectAssociateDbService projectAssociateDbService;
+ ProjectAssociateApi projectAssociateApi;
@Autowired
- ServiceRecordDbService serviceRecordDbService;
+ ServiceRecordApi serviceRecordApi;
@GetMapping("/all")
public String list() {
- log.info("projectStatusDbService");
- projectStatusDbService.generate();
- log.info("partnerDbService");
- partnerDbService.generate();
- log.info("associateDbService");
- associateDbService.generate();
- log.info("invoiceDbService");
- invoiceDbService.generate();
- log.info("treasuryDbService");
- treasuryDbService.generate();
- log.info("projectDbService");
- projectDbService.generate();
- log.info("projectAssociateDbService");
- projectAssociateDbService.generate();
- log.info("serviceRecordDbService");
- serviceRecordDbService.generate();
+ log.info("projectStatus");
+ projectStatusApi.generate();
+ log.info("partner");
+ partnerApi.generate();
+ log.info("associate");
+ associateApi.generate();
+ log.info("invoice");
+ invoiceApi.generate();
+ log.info("treasury");
+ treasuryApi.generate();
+ log.info("project");
+ projectApi.generate();
+ log.info("serviceRecord");
+ serviceRecordApi.generate();
+ log.info("projectAssociate");
+ projectAssociateApi.generate();
+
return "DONE";
}
package hu.user.lis.services.api;
import hu.user.lis.db.Invoice;
-import hu.user.lis.services.nosql.DbService;
-import hu.user.lis.services.nosql.InvoiceDbService;
+import hu.user.lis.db.repository.InvoiceRepository;
+import hu.user.lis.services.data.InvoiceService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
@Log4j2
@RestController
@RequestMapping("/api/invoice")
-public class InvoiceApi extends DbApi<Invoice> {
+public class InvoiceApi extends DbApi<Invoice, InvoiceRepository, InvoiceService> {
@Autowired
- InvoiceDbService invoiceDbService;
+ InvoiceRepository invoiceRepository;
+
+ @Autowired
+ InvoiceService invoiceService;
+
+ @Override
+ protected InvoiceService getService() {
+ return invoiceService;
+ }
@Override
- protected DbService<Invoice> getDbService() {
- return invoiceDbService;
+ protected InvoiceRepository getRepository() {
+ return invoiceRepository;
}
}
package hu.user.lis.services.api;
import hu.user.lis.db.Partner;
-import hu.user.lis.services.nosql.DbService;
-import hu.user.lis.services.nosql.PartnerDbService;
+import hu.user.lis.db.repository.PartnerRepository;
+import hu.user.lis.services.data.PartnerService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
@Log4j2
@RestController
@RequestMapping("/api/partner")
-public class PartnerApi extends DbApi<Partner> {
+public class PartnerApi extends DbApi<Partner, PartnerRepository, PartnerService> {
@Autowired
- PartnerDbService partnerDbService;
+ PartnerRepository partnerRepository;
+
+ @Autowired
+ PartnerService partnerService;
+
+ @Override
+ protected PartnerService getService() {
+ return partnerService;
+ }
@Override
- protected DbService<Partner> getDbService() {
- return partnerDbService;
+ protected PartnerRepository getRepository() {
+ return partnerRepository;
}
}
package hu.user.lis.services.api;
import hu.user.lis.db.Project;
-import hu.user.lis.services.nosql.DbService;
-import hu.user.lis.services.nosql.ProjectDbService;
+import hu.user.lis.db.repository.ProjectRepository;
+import hu.user.lis.services.data.ProjectService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
@Log4j2
@RestController
@RequestMapping("/api/project")
-public class ProjectApi extends DbApi<Project> {
+public class ProjectApi extends DbApi<Project, ProjectRepository, ProjectService> {
@Autowired
- ProjectDbService projectDbService;
+ ProjectRepository projectRepository;
+ @Autowired
+ ProjectService projectService;
+
+ @Override
+ protected ProjectService getService() {
+ return projectService;
+ }
@Override
- protected DbService<Project> getDbService() {
- return projectDbService;
+ protected ProjectRepository getRepository() {
+ return projectRepository;
}
}
package hu.user.lis.services.api;
import hu.user.lis.db.ProjectAssociate;
-import hu.user.lis.services.nosql.DbService;
-import hu.user.lis.services.nosql.ProjectAssociateDbService;
+import hu.user.lis.db.repository.ProjectAssociateRepository;
+import hu.user.lis.services.data.ProjectAssociateService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
@Log4j2
@RestController
@RequestMapping("/api/project-associate")
-public class ProjectAssociateApi extends DbApi<ProjectAssociate> {
+public class ProjectAssociateApi extends DbApi<ProjectAssociate, ProjectAssociateRepository, ProjectAssociateService> {
@Autowired
- ProjectAssociateDbService projectAssociateDbService;
+ ProjectAssociateRepository projectAssociateRepository;
+ @Autowired
+ ProjectAssociateService projectAssociateService;
+
+ @Override
+ protected ProjectAssociateService getService() {
+ return projectAssociateService;
+ }
@Override
- protected DbService<ProjectAssociate> getDbService() {
- return projectAssociateDbService;
+ protected ProjectAssociateRepository getRepository() {
+ return projectAssociateRepository;
}
}
import hu.user.lis.services.data.ProjectStatusService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.List;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
@Log4j2
@RestController
@RequestMapping("/api/project-status")
-public class ProjectStatusApi {
+public class ProjectStatusApi extends DbApi<ProjectStatus, ProjectStatusRepository, ProjectStatusService> {
@Autowired
ProjectStatusRepository projectStatusRepository;
@Autowired
ProjectStatusService projectStatusService;
- @GetMapping("/list")
- public List<ProjectStatus> list() {
- return projectStatusRepository.findAll();
- }
-
- @GetMapping("/get/{id}")
- public ProjectStatus get(@PathVariable Long id) {
- return projectStatusRepository.findById(id).orElse(null);
- }
-
- @PostMapping("/create")
- public ProjectStatus create(@RequestBody ProjectStatus entity) {
- return projectStatusRepository.save(entity);
- }
-
- @PutMapping("/update")
- public void update(@RequestBody ProjectStatus entity) {
- projectStatusRepository.truncate();
- }
-
- @GetMapping("/reset")
- public void reset() {
- projectStatusRepository.truncate();
+ @Override
+ protected ProjectStatusService getService() {
+ return projectStatusService;
}
- @GetMapping("/generate")
- public List<ProjectStatus> generate() {
- reset();
- List<ProjectStatus> result = projectStatusService.getAll();
- projectStatusRepository.saveAll(result);
- return result;
+ @Override
+ protected ProjectStatusRepository getRepository() {
+ return projectStatusRepository;
}
}
package hu.user.lis.services.api;
import hu.user.lis.db.ServiceRecord;
-import hu.user.lis.services.nosql.DbService;
-import hu.user.lis.services.nosql.ServiceRecordDbService;
+import hu.user.lis.db.repository.ServiceRecordRepository;
+import hu.user.lis.services.data.ServiceRecordService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
@Log4j2
@RestController
@RequestMapping("/api/service-record")
-public class ServiceRecordApi extends DbApi<ServiceRecord> {
+public class ServiceRecordApi extends DbApi<ServiceRecord, ServiceRecordRepository, ServiceRecordService> {
@Autowired
- ServiceRecordDbService serviceRecordDbService;
+ ServiceRecordRepository serviceRecordRepository;
+ @Autowired
+ ServiceRecordService serviceRecordService;
+
+ @Override
+ protected ServiceRecordService getService() {
+ return serviceRecordService;
+ }
@Override
- protected DbService<ServiceRecord> getDbService() {
- return serviceRecordDbService;
+ protected ServiceRecordRepository getRepository() {
+ return serviceRecordRepository;
}
}
package hu.user.lis.services.api;
import hu.user.lis.db.Treasury;
-import hu.user.lis.services.nosql.DbService;
-import hu.user.lis.services.nosql.TreasuryDbService;
+import hu.user.lis.db.repository.TreasuryRepository;
+import hu.user.lis.services.data.TreasuryService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
@Log4j2
@RestController
@RequestMapping("/api/treasury")
-public class TreasuryApi extends DbApi<Treasury> {
+public class TreasuryApi extends DbApi<Treasury, TreasuryRepository, TreasuryService> {
@Autowired
- TreasuryDbService treasuryDbService;
+ TreasuryRepository treasuryRepository;
+ @Autowired
+ TreasuryService treasuryService;
+
+ @Override
+ protected TreasuryService getService() {
+ return treasuryService;
+ }
@Override
- protected DbService<Treasury> getDbService() {
- return treasuryDbService;
+ protected TreasuryRepository getRepository() {
+ return treasuryRepository;
}
}
import java.util.List;
public interface AssociateService extends DataService<Associate> {
- List<Associate> getAll();
-
void setAll(List<Associate> entities);
Associate createNew();
package hu.user.lis.services.data;
+import java.util.List;
+
public interface DataService<T> {
+ List<T> getAll();
+
T copy(T sourceEntity);
T copy(T sourceEntity, String property, Object value);
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.reflect.Field;
+import java.util.List;
@Log4j2
-public class DataServiceImpl<T> implements DataService<T> {
+public abstract class DataServiceImpl<T> implements DataService<T> {
@Autowired
ObjectMapper mapper;
+ @Override
+ public abstract List<T> getAll();
+
@Override
public T copy(T sourceEntity) {
T result = null;
import hu.user.lis.db.EDocument;
-import java.util.List;
-
public interface EDocumentService extends DataService<EDocument> {
- List<EDocument> getAll();
-
EDocument createNew();
void add(EDocument entity);
import java.util.List;
public interface InvoiceService extends DataService<Invoice> {
- List<Invoice> getAll();
-
void setAll(List<Invoice> entities);
Invoice createNew();
package hu.user.lis.services.data;
-import com.fasterxml.jackson.core.JsonProcessingException;
import hu.user.lis.db.Partner;
import java.util.List;
-public interface PartnerService {
- List<Partner> getAll();
-
+public interface PartnerService extends DataService<Partner> {
void setAll(List<Partner> entities);
Partner createNew();
Partner getById(String id);
- Partner copy(Partner sourceEntity);
-
void replace(Partner targetEntity, Partner replacementEntity);
Partner getRandom();
- String toString(Partner sourceEntity) throws JsonProcessingException;
-
- Partner copy(Partner sourceEntity, String property, Object value) throws JsonProcessingException, NoSuchFieldException, IllegalAccessException;
-
Partner getByName(String name);
}
package hu.user.lis.services.data;
-import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.javafaker.Address;
import hu.user.lis.db.Partner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
-import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
return result;
}
- @Override
- public Partner copy(Partner sourceEntity) {
- Partner result = null;
- try {
- String json = toString(sourceEntity);
- result = mapper.readValue(json, Partner.class);
- } catch (JsonProcessingException e) {
- log.catching(e);
- }
- return result;
- }
-
- @Override
- public String toString(Partner sourceEntity) {
- String result = null;
- try {
- result = mapper.writeValueAsString(sourceEntity);
- } catch (JsonProcessingException e) {
- log.catching(e);
- }
- return result;
- }
-
- @Override
- public Partner copy(Partner sourceEntity, String property, Object value) {
- Partner result = copy(sourceEntity);
- Field field = null;
- try {
- field = result.getClass().getDeclaredField(property);
- field.setAccessible(true);
- field.set(result, value);
- } catch (Exception e) {
- log.catching(e);
- }
- return result;
- }
-
@Override
public Partner getByName(String name) {
return getAll().stream().filter(p -> p.getName().equals(name)).findFirst().get();
import hu.user.lis.db.Project;
import hu.user.lis.db.ProjectAssociate;
-import java.util.List;
import java.util.Map;
-public interface ProjectAssociateService {
+public interface ProjectAssociateService extends DataService<ProjectAssociate> {
ProjectAssociate createNew(Project project, Associate associate);
void add(ProjectAssociate entity);
void update(Project project, Map<Associate, Boolean> associates);
- String toString(ProjectAssociate sourceEntity);
-
- List<ProjectAssociate> getAll();
}
import java.util.List;
-public interface ProjectService {
- List<Project> getAll();
+public interface ProjectService extends DataService<Project> {
void setAll(List<Project> entities);
void add(Project entity);
- Project copy(Project sourceEntity);
-
void replace(Project targetEntity, Project replacementEntity);
-
- String toString(Project sourceEntity);
-
- Project copy(Project sourceEntity, String property, Object value);
}
import hu.user.lis.db.ProjectStatus;
-import java.util.List;
-
public interface ProjectStatusService extends DataService<ProjectStatus> {
- List<ProjectStatus> getAll();
ProjectStatus getById(Object id);
@Override
public ProjectStatus createNew() {
- ProjectStatus result = ProjectStatus.builder().active(true).order(entities.size() + 1).build();
- entities.add(result);
- return result;
+ return ProjectStatus.builder().active(true).build();
}
@Override
import java.util.List;
public interface ServiceRecordService extends DataService<ServiceRecord> {
- List<ServiceRecord> getAll();
ServiceRecord getById(String id);
package hu.user.lis.services.data;
import hu.user.lis.db.Project;
+import hu.user.lis.db.ProjectAssociate;
import hu.user.lis.db.ServiceRecord;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.RandomUtils;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
@Service
@Log4j2
private List<ServiceRecord> generate() {
List<ServiceRecord> result = new ArrayList<>();
- Date workDay = dataGeneratorService.faker().date().past(10 + 1, TimeUnit.DAYS);
- String description = dataGeneratorService.faker().lorem().sentence(10);
- int workHours = RandomUtils.nextInt(1, 9);
- ServiceRecord entity = ServiceRecord.builder()
- .associate(associateService.getRandom())
- .project(projectService.getRandom())
- .workDay(workDay)
- .workHours(workHours)
- .description(description)
- .build();
- calculateCost(entity);
- result.add(entity);
-
-// projectService.getAll().forEach(p -> {
-// int serviceRecordCount = RandomUtils.nextInt(3, 10);
-//
-// List<ProjectAssociate> projectAssociates = projectAssociateService.getAll().stream().filter(e -> e.getProject().getId().equals(p.getId())).collect(Collectors.toList());
-// projectAssociates.forEach(pa -> {
-// for (int i = 0; i < serviceRecordCount; i++) {
-// Date workDay = dataGeneratorService.faker().date().past(i * 10 + 1, TimeUnit.DAYS);
-// String description = dataGeneratorService.faker().lorem().sentence(10);
-// int workHours = RandomUtils.nextInt(1, 9);
-// ServiceRecord entity = ServiceRecord.builder()
-// .associate(pa.getAssociate())
-// .project(pa.getProject())
-// .workDay(workDay)
-// .workHours(workHours)
-// .description(description)
-// .build();
-// calculateCost(entity);
-// result.add(entity);
-//
-// entity = ServiceRecord.builder()
-// .associate(pa.getAssociate())
-// .project(pa.getProject())
-// .workDay(workDay)
-// .workHours(workHours)
-// .description(description)
-// .build();
-// calculateCost(entity);
-// result.add(entity);
-// }
-// });
-// });
+ projectService.getAll().forEach(p -> {
+ int serviceRecordCount = RandomUtils.nextInt(3, 10);
+
+ List<ProjectAssociate> projectAssociates = projectAssociateService.getAll().stream().filter(e -> e.getProject().getId().equals(p.getId())).collect(Collectors.toList());
+ projectAssociates.forEach(pa -> {
+ for (int i = 0; i < serviceRecordCount; i++) {
+ Date workDay = dataGeneratorService.faker().date().past(i * 10 + 1, TimeUnit.DAYS);
+ String description = dataGeneratorService.faker().lorem().sentence(10);
+ int workHours = RandomUtils.nextInt(1, 9);
+ ServiceRecord entity = ServiceRecord.builder()
+ .associate(pa.getAssociate())
+ .project(pa.getProject())
+ .workDay(workDay)
+ .workHours(workHours)
+ .description(description)
+ .build();
+ calculateCost(entity);
+ result.add(entity);
+
+ entity = ServiceRecord.builder()
+ .associate(pa.getAssociate())
+ .project(pa.getProject())
+ .workDay(workDay)
+ .workHours(workHours)
+ .description(description)
+ .build();
+ calculateCost(entity);
+ result.add(entity);
+ }
+ });
+ });
return result;
}
import hu.user.lis.db.Supplier;
-import java.util.List;
-
-public interface SupplierService {
- List<Supplier> getAll();
+public interface SupplierService extends DataService<Supplier> {
}
import java.util.List;
-public interface TreasuryService {
- List<Treasury> getAll();
-
+public interface TreasuryService extends DataService<Treasury> {
Treasury createNew();
- Treasury copy(Treasury sourceEntity);
-
- String toString(Treasury sourceEntity);
-
- Treasury copy(Treasury sourceEntity, String property, Object value);
-
List<Treasury> getRandom();
+
Treasury getByHumanId(String id);
List<Treasury> getByHumanIds(String[] ids);
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import hu.user.lis.db.Associate;
-import hu.user.lis.services.data.AssociateService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class AssociateDbService extends DbService<Associate> {
- public static final String ID = "id";
- public static final String NAME = "name";
- public static final String ACTIVE = "active";
- public static final String LOGIN = "login";
- public static final String PASSWORD = "password";
- public static final String MONTHLY_COST = "monthlyCost";
- @Autowired
- AssociateService associateService;
-
- @Override
- protected Class<Associate> getEntityClass() {
- return Associate.class;
- }
-
- @Override
- protected List<Associate> generateEntities() {
- return associateService.getAll();
- }
-
- @Override
- protected void afterGenerateEntities(List<Associate> entities) {
- associateService.setAll(entities);
- }
-
-}
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import com.mongodb.client.MongoCollection;
-import org.bson.Document;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.mongodb.core.MongoTemplate;
-import org.springframework.data.mongodb.core.query.Query;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public abstract class DbService<T> {
- @Autowired
- MongoTemplate mongoTemplate;
-
- protected abstract Class<T> getEntityClass();
-
- public List<T> list() {
- return mongoTemplate.findAll(getEntityClass());
- }
-
- public List<T> list(Query query) {
- return mongoTemplate.find(query, getEntityClass());
- }
-
- public long count(Query query) {
- return mongoTemplate.count(query, getEntityClass());
- }
-
- public T get(String id) {
- return mongoTemplate.findById(id, getEntityClass());
- }
-
- public T insert(T entity) {
- mongoTemplate.insert(entity);
- return entity;
- }
-
- public T save(T entity) {
- return mongoTemplate.save(entity);
- }
-
- public void reset() {
- String collectionName = mongoTemplate.getCollectionName(getEntityClass());
- MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
- if (collection != null) {
- collection.drop();
- }
- }
-
- public List<T> generate() {
- reset();
- List<T> result = generateEntities();
- mongoTemplate.insertAll(result);
- afterGenerateEntities(result);
- return result;
- }
-
- protected abstract List<T> generateEntities();
-
- protected void afterGenerateEntities(List<T> entities) {
- }
-
-}
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import hu.user.lis.db.Invoice;
-import hu.user.lis.services.data.InvoiceService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class InvoiceDbService extends DbService<Invoice> {
- @Autowired
- InvoiceService invoiceService;
-
- @Override
- protected Class<Invoice> getEntityClass() {
- return Invoice.class;
- }
-
- @Override
- protected List<Invoice> generateEntities() {
- return invoiceService.getAll();
- }
-
- @Override
- protected void afterGenerateEntities(List<Invoice> entities) {
- invoiceService.setAll(entities);
- }
-}
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import hu.user.lis.db.Partner;
-import hu.user.lis.services.data.PartnerService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class PartnerDbService extends DbService<Partner> {
- public static final String ID = "id";
- public static final String NAME = "name";
- public static final String VAT_NR = "vatNr";
- public static final String ADDRESS = "address";
- @Autowired
- PartnerService partnerService;
-
- @Override
- protected Class<Partner> getEntityClass() {
- return Partner.class;
- }
-
- @Override
- protected List<Partner> generateEntities() {
- return partnerService.getAll();
- }
-
- @Override
- protected void afterGenerateEntities(List<Partner> entities) {
- partnerService.setAll(entities);
- }
-}
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import hu.user.lis.db.ProjectAssociate;
-import hu.user.lis.services.data.ProjectAssociateService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class ProjectAssociateDbService extends DbService<ProjectAssociate> {
- @Autowired
- ProjectAssociateService projectAssociateService;
-
- @Override
- protected Class<ProjectAssociate> getEntityClass() {
- return ProjectAssociate.class;
- }
-
- @Override
- protected List<ProjectAssociate> generateEntities() {
- return projectAssociateService.getAll();
- }
-
-}
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import hu.user.lis.db.Project;
-import hu.user.lis.services.data.ProjectService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class ProjectDbService extends DbService<Project> {
- @Autowired
- ProjectService projectService;
-
- @Override
- protected Class<Project> getEntityClass() {
- return Project.class;
- }
-
- @Override
- protected List<Project> generateEntities() {
- return projectService.getAll();
- }
-
- @Override
- protected void afterGenerateEntities(List<Project> entities) {
- projectService.setAll(entities);
- }
-}
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import hu.user.lis.db.ProjectStatus;
-import hu.user.lis.services.data.ProjectStatusService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class ProjectStatusDbService extends DbService<ProjectStatus> {
- public final String ID = "id";
- public final String NAME = "name";
- public final String ACTIVE = "active";
- public final String ORDER = "order";
- @Autowired
- ProjectStatusService projectStatusService;
-
- @Override
- protected Class<ProjectStatus> getEntityClass() {
- return ProjectStatus.class;
- }
-
- @Override
- protected List<ProjectStatus> generateEntities() {
- return projectStatusService.getAll();
- }
-
-}
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import hu.user.lis.db.ServiceRecord;
-import hu.user.lis.services.data.ServiceRecordService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class ServiceRecordDbService extends DbService<ServiceRecord> {
- public static final String ID = "id";
- public static final String PROJECT_ID = "projectId";
- public static final String ASSOCIATE_ID = "associateId";
- @Autowired
- ServiceRecordService serviceRecordService;
-
- @Override
- protected Class<ServiceRecord> getEntityClass() {
- return ServiceRecord.class;
- }
-
- @Override
- protected List<ServiceRecord> generateEntities() {
- return serviceRecordService.getAll();
- }
-
-}
+++ /dev/null
-package hu.user.lis.services.nosql;
-
-import hu.user.lis.db.Treasury;
-import hu.user.lis.services.data.TreasuryService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-@Service
-public class TreasuryDbService extends DbService<Treasury> {
- @Autowired
- TreasuryService treasuryService;
-
- @Override
- protected Class<Treasury> getEntityClass() {
- return Treasury.class;
- }
-
- @Override
- protected List<Treasury> generateEntities() {
- return treasuryService.getAll();
- }
-}
import org.zkoss.zk.ui.WebApps;
import javax.annotation.PostConstruct;
+import java.util.Objects;
@Configuration
//@Profile("dev")
logger.info("**** ZK-Springboot-Demo: development configuration active ****");
logger.info("**************************************************************");
+ if (Objects.nonNull(WebApps.getCurrent())) {
+ // enable non minified js
+ WebApps.getCurrent().getConfiguration().setDebugJS(true);
+ }
+
//disable various caches to avoid server restarts
Library.setProperty("org.zkoss.zk.ZUML.cache", "false");
Library.setProperty("org.zkoss.zk.WPD.cache", "false");
Library.setProperty("org.zkoss.zk.WCS.cache", "false");
Library.setProperty("org.zkoss.web.classWebResource.cache", "false");
Library.setProperty("org.zkoss.util.label.cache", "false");
-
- // enable non minified js
- WebApps.getCurrent().getConfiguration().setDebugJS(true);
-
// enable for debugging MVVM commands and binding (very verbose)
Library.setProperty("org.zkoss.bind.DebuggerFactory.enable", "false");
}
return "timeout";
}
- @GetMapping({"/projects", "/associates", "/project-associates", "/service-records", "/settings", "/project/**"})
+ @GetMapping("/login")
+ public String login() {
+ return "login";
+ }
+
+ @GetMapping({"/partners", "/projects", "/associates", "/project-associates", "/service-records", "/settings", "/project/**"})
public String index() {
return "index";
}
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
+import static hu.user.lis.ui.view.IndexViewModel.NAVIGATION;
+
/**
* This is an example of minimal configuration for ZK + Spring Security, we open as less access as possible to run a ZK-based application.
* Please understand the configuration and modify it upon your requirement.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
- private static final String ZUL_FILES = "/zkau/web/**/*.zul";
- private static final String ZK_RESOURCES = "/zkres/**";
+ public static final String ZUL_FILES = "/zkau/web/**/*.zul";
+ public static final String[] ZK_RESOURCES = {"/zkau/web/**/js/**", "/zkau/web/**/zul/css/**", "/zkau/web/**/img/**"};
// allow desktop cleanup after logout or when reloading login page
- private static final String REMOVE_DESKTOP_REGEX = "/zkau\\?dtid=.*&cmd_0=rmDesktop&.*";
+ public static final String REMOVE_DESKTOP_REGEX = "/zkau\\?dtid=.*&cmd_0=rmDesktop&.*";
@Override
protected void configure(HttpSecurity http) throws Exception {
- // you need to disable spring CSRF to make ZK AU pass security filter
- // ZK already sends a AJAX request with a built-in CSRF token,
- // please refer to https://www.zkoss.org/wiki/ZK%20Developer's%20Reference/Security%20Tips/Cross-site%20Request%20Forgery
http.csrf().disable();
+ String[] navigation = NAVIGATION.keySet().toArray(new String[]{});
http.authorizeRequests()
- .antMatchers(ZUL_FILES).denyAll() // block direct access to zul under class path web resource folder
+ .antMatchers(ZUL_FILES).denyAll() // block direct access to zul files
.antMatchers(HttpMethod.GET, ZK_RESOURCES).permitAll() // allow zk resources
.regexMatchers(HttpMethod.GET, REMOVE_DESKTOP_REGEX).permitAll() // allow desktop cleanup
.requestMatchers(req -> "rmDesktop".equals(req.getParameter("cmd_0"))).permitAll() // allow desktop cleanup from ZATS
- .mvcMatchers("/", "/login", "/logout").permitAll() //permit the URL for login and logout
- .mvcMatchers("/secure").hasRole("USER")
- .anyRequest().authenticated() //enforce all requests to be authenticated
+ .mvcMatchers("/", "/login", "/logout").permitAll()
+ .mvcMatchers(navigation).hasRole("USER")
+ .anyRequest().authenticated()
.and()
.formLogin()
- .loginPage("/login").defaultSuccessUrl("/secure/main")
+ .loginPage("/login").defaultSuccessUrl("/partners")
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/");
}
- /**
- * Creates an {@link InMemoryUserDetailsManager} for demo/testing purposes only. DON'T use this in production, see: {@link User#withUserDetails}!
- *
- * @return userDetailsService
- */
@Bean
@Override
public UserDetailsService userDetailsService() {
package hu.user.lis.ui.data;
import hu.user.lis.db.Associate;
-import hu.user.lis.services.nosql.AssociateDbService;
+import hu.user.lis.db.repository.AssociateRepository;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
-import org.springframework.data.domain.PageRequest;
-import org.springframework.data.domain.Sort;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
+import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
-import org.zkoss.bind.BindUtils;
import org.zkoss.zul.FieldComparator;
import java.util.List;
@Component
@Log4j2
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-public class AssociateSelectorDataModel extends CachedDataModel<Associate> {
+public class AssociateSelectorDataModel extends CachedSpringDataModel<Associate> {
static private final int SEARCH_LIMIT = 10;
@Autowired
- AssociateDbService associateDbService;
+ AssociateRepository associateRepository;
private String partialName;
- private Query filter() {
- Query result = new Query();
- if (StringUtils.isNotBlank(partialName)) {
- result.addCriteria(Criteria.where(AssociateDbService.NAME).regex("/^" + partialName + "/i"));
- }
- result.addCriteria(Criteria.where(AssociateDbService.ACTIVE).is(true));
- return result;
- }
-
@Override
protected List<Associate> getResultSet(int page, int pageSize, FieldComparator sortComparator) {
- Query query = filter();
- query.with(Sort.by(Sort.Direction.ASC, AssociateDbService.NAME));
- query.with(PageRequest.of(page, pageSize));
- List<Associate> result = associateDbService.list(query);
+ Pageable pageable = createPageable(0, SEARCH_LIMIT, null);
+ List<Associate> result = StringUtils.isBlank(partialName) ? associateRepository.findAll(pageable).toList() :
+ associateRepository.search(partialName, true, false, pageable);
+
+ log.info("Associate filter: {}", partialName);
+ result.forEach(a -> {
+ log.info("Associate: {}", a.getName());
+ });
return result;
}
@Override
public int getResultSetCount() {
- Query query = filter();
- int result = (int) associateDbService.count(query);
+ int result = StringUtils.isBlank(partialName) ?
+ (int) associateRepository.count() :
+ (int) associateRepository.count(partialName, true, false);
+ log.info("Associate filter: {}", partialName);
+ log.info("Associate count: {}", result);
return result > SEARCH_LIMIT ? SEARCH_LIMIT : result;
}
log.info("Searching associate using filter {}", partialName);
this.partialName = partialName;
super.reset();
- BindUtils.postNotifyChange(null, null, this, "*");
}
}
package hu.user.lis.ui.data;
import hu.user.lis.db.Associate;
+import hu.user.lis.db.repository.AssociateRepository;
import hu.user.lis.services.data.AssociateService;
-import hu.user.lis.services.nosql.AssociateDbService;
import lombok.extern.log4j.Log4j2;
-import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
-import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
-import org.springframework.data.domain.Sort;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.zkoss.zul.FieldComparator;
@Component
@Log4j2
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-public class AssociatesDataModel extends CachedDataModel<Associate> {
+public class AssociatesDataModel extends CachedSpringDataModel<Associate> {
@Autowired
- AssociateDbService associateDbService;
+ AssociateRepository associateRepository;
@Autowired
AssociateService associateService;
private String partialName;
private boolean filterShowInActive;
private boolean filterShowActive;
- private Query filter() {
- Query result = new Query();
- if (listAll) {
- result.addCriteria(Criteria.where(AssociateDbService.ID).gt(0));
- return result;
- }
- if (StringUtils.isNotBlank(partialName)) {
- result.addCriteria(Criteria.where(AssociateDbService.NAME).regex("/^" + partialName + "/i"));
- }
- if (filterShowActive && !filterShowInActive) {
- result.addCriteria(Criteria.where(AssociateDbService.ACTIVE).is(true));
- }
- if (filterShowInActive && !filterShowActive) {
- result.addCriteria(Criteria.where(AssociateDbService.ACTIVE).is(false));
- }
- return result;
- }
-
@Override
protected List<Associate> getResultSet(int page, int pageSize, FieldComparator sortComparator) {
- Query query = filter();
- if (sortComparator != null) {
- String orderBy = sortComparator.getRawOrderBy();
- Sort.Direction direction = sortComparator.isAscending() ? Sort.Direction.ASC : Sort.Direction.DESC;
- query.with(Sort.by(direction, orderBy));
- }
-
- Pageable pageable = PageRequest.of(page, pageSize);
- query.with(pageable);
-
- List<Associate> result = associateDbService.list(query);
+ Pageable pageable = createPageable(page, pageSize, sortComparator);
+ List<Associate> result = listAll ? associateRepository.findAll(pageable).toList() :
+ associateRepository.search(partialName, filterShowActive, filterShowInActive, pageable);
return result;
}
@Override
public int getResultSetCount() {
- Query query = filter();
- return (int) associateDbService.count(query);
+ long result = listAll ? associateRepository.count() :
+ associateRepository.count(partialName, filterShowActive, filterShowInActive);
+ return (int) result;
}
public void search(String partialName) {
}
public void addNew(Associate entity) {
- associateDbService.insert(entity);
+ associateRepository.save(entity);
}
public Associate copy(Associate selectedEntity) {
return associateService.copy(selectedEntity);
}
- public Associate save(Associate selectedEntity) {
- return associateDbService.save(selectedEntity);
+ public Associate save(Associate entity) {
+ return associateRepository.save(entity);
}
}
return this.resultSetSize;
}
+// private void loadCache(int forIndex) {
+// try {
+// int halfSize = this.cacheSize / 2;
+// int rowLimit = this.cacheSize; // 200
+// int startPos = 0;
+// if ((forIndex - halfSize) > 0) { // forIndex=60 startPos=0
+// // cache=0-200, forIndex=150
+// // startPos=50 cache=50-250
+// startPos = (forIndex - halfSize);
+// }
+//
+// int endPos = (startPos + rowLimit);
+// endPos = ((this.resultSetSize < 0) || (endPos <= this.resultSetSize)) ? endPos : this.resultSetSize;
+//
+//
+// if (this.resultSetSize < 0) {
+// this.resultSetSize = getResultSetCount();
+// log.info("Result item count is {}", resultSetSize);
+// }
+//
+// log.info("Query result from {} to {}", startPos, endPos);
+//
+// int limit = endPos - startPos;
+// int page = (int) Math.ceil(this.resultSetSize / limit);
+// List<T> resList = getResultSet(page, limit, sortComparator);
+//
+// if (resList != null) {
+// log.info("Got {} records", resList.size());
+// for (int c = 0; c < resList.size(); c++) {
+// cache.put(startPos + c, resList.get(c));
+// // logger.debug("CachedListMode.cached idx: " +
+// // (startPos + c));
+// }
+// }
+// // logger.debug("CachedListMode.cacheSize: " + cache.size());
+//
+// cacheStart = startPos + 1;
+// cacheEnd = cacheStart + (cache.size() == 0 ? 0 : (cache.size() - 1));
+// } catch (Exception e) {
+// log.error("", e);
+// }
+// }
+
private void loadCache(int forIndex) {
try {
int halfSize = this.cacheSize / 2;
log.info("Result item count is {}", resultSetSize);
}
- log.info("Query result from {} to {}", startPos, endPos);
-
int limit = endPos - startPos;
- int page = (int) Math.ceil(this.resultSetSize / limit);
+
+ // (int) Math.ceil(this.resultSetSize / limit);
+ int page = forIndex == 0 ? 0 : (int) Math.ceil(limit / forIndex);
+ log.info("Query result from {} to {} | page {} pageSize {}", startPos, endPos, page, limit);
List<T> resList = getResultSet(page, limit, sortComparator);
if (resList != null) {
--- /dev/null
+package hu.user.lis.ui.data;
+
+import lombok.extern.log4j.Log4j2;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.domain.Sort;
+import org.springframework.stereotype.Component;
+import org.zkoss.zul.FieldComparator;
+
+import java.util.Objects;
+
+@Component
+@Log4j2
+public abstract class CachedSpringDataModel<T> extends CachedDataModel<T> {
+ protected Pageable createPageable(int page, int pageSize, FieldComparator sortComparator) {
+ Pageable pageable;
+ if (Objects.isNull(sortComparator)) {
+ pageable = PageRequest.of(page, pageSize);
+ } else {
+ String orderBy = sortComparator.getRawOrderBy();
+ Sort.Direction direction = sortComparator.isAscending() ? Sort.Direction.ASC : Sort.Direction.DESC;
+ pageable = PageRequest.of(page, pageSize, Sort.by(direction, orderBy));
+ }
+ return pageable;
+ }
+}
+
package hu.user.lis.ui.data;
import hu.user.lis.db.Partner;
+import hu.user.lis.db.repository.PartnerRepository;
import hu.user.lis.services.data.PartnerService;
-import hu.user.lis.services.nosql.AssociateDbService;
-import hu.user.lis.services.nosql.PartnerDbService;
import lombok.extern.log4j.Log4j2;
-import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
-import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
-import org.springframework.data.domain.Sort;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.zkoss.zul.FieldComparator;
@Component
@Log4j2
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-public class PartnersDataModel extends CachedDataModel<Partner> {
+public class PartnersDataModel extends CachedSpringDataModel<Partner> {
@Autowired
- PartnerDbService partnerDbService;
+ PartnerRepository partnerRepository;
@Autowired
PartnerService partnerService;
private String partialName;
private boolean filterShowActive;
- private Query filter() {
- Query result = new Query();
- if (listAll) {
- result.addCriteria(Criteria.where(PartnerDbService.ID).gt(0));
- return result;
- }
- if (StringUtils.isNotBlank(partialName)) {
- result.addCriteria(Criteria.where(PartnerDbService.NAME).regex("/^" + partialName + "/i"));
- }
- if (StringUtils.isNotBlank(partialVatNr)) {
- result.addCriteria(Criteria.where(PartnerDbService.VAT_NR).regex("/^" + partialVatNr + "/i"));
- }
- if (StringUtils.isNotBlank(partialAddress)) {
- result.addCriteria(Criteria.where(PartnerDbService.ADDRESS).regex("/^" + partialAddress + "/i"));
- }
- if (filterShowActive && !filterShowInActive) {
- result.addCriteria(Criteria.where(AssociateDbService.ACTIVE).is(true));
- }
- if (filterShowInActive && !filterShowActive) {
- result.addCriteria(Criteria.where(AssociateDbService.ACTIVE).is(false));
- }
- return result;
- }
-
@Override
protected List<Partner> getResultSet(int page, int pageSize, FieldComparator sortComparator) {
- Query query = filter();
- if (sortComparator != null) {
- String orderBy = sortComparator.getRawOrderBy();
- Sort.Direction direction = sortComparator.isAscending() ? Sort.Direction.ASC : Sort.Direction.DESC;
- query.with(Sort.by(direction, orderBy));
- }
-
- Pageable pageable = PageRequest.of(page, pageSize);
- query.with(pageable);
- List<Partner> result = partnerDbService.list(query);
+ Pageable pageable = createPageable(page, pageSize, sortComparator);
+ List<Partner> result = listAll ? partnerRepository.findAll() :
+ partnerRepository.search(partialName, partialVatNr, partialAddress, filterShowActive, filterShowInActive, pageable);
return result;
}
@Override
public int getResultSetCount() {
- Query query = filter();
- return (int) partnerDbService.count(query);
+ long result = listAll ? partnerRepository.count() :
+ partnerRepository.count(partialName, partialVatNr, partialAddress, filterShowActive, filterShowInActive);
+ return (int) result;
}
public void search(String partialName, String partialVatNr, String partialAddress) {
}
public void addNew(Partner entity) {
- partnerDbService.insert(entity);
+ partnerRepository.save(entity);
}
public Partner copy(Partner selectedEntity) {
}
public Partner save(Partner selectedEntity) {
- return partnerDbService.save(selectedEntity);
+ return partnerRepository.save(selectedEntity);
}
}
package hu.user.lis.ui.data;
import hu.user.lis.db.Project;
-import hu.user.lis.services.data.ProjectService;
+import hu.user.lis.db.repository.ProjectRepository;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
+import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
-import org.zkoss.bind.BindUtils;
import org.zkoss.zul.FieldComparator;
-import java.util.Comparator;
import java.util.List;
-import java.util.stream.Collectors;
@Component
@Log4j2
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-public class ProjectSelectorDataModel extends CachedDataModel<Project> {
+public class ProjectSelectorDataModel extends CachedSpringDataModel<Project> {
static private final int SEARCH_LIMIT = 10;
@Autowired
- ProjectService projectService;
+ ProjectRepository projectRepository;
private String partialSearch;
- private boolean filter(Project project) {
- if (StringUtils.isBlank(partialSearch)) {
- return true;
- }
- if (StringUtils.isNotBlank(partialSearch)) {
- if (project.getHumanId().toLowerCase().contains(partialSearch.toLowerCase())) {
- return true;
- }
- if (project.getName().toLowerCase().contains(partialSearch.toLowerCase())) {
- return true;
- }
- if (project.getPartner().getName().toLowerCase().contains(partialSearch.toLowerCase())) {
- return true;
- }
- }
- return false;
- }
-
@Override
protected List<Project> getResultSet(int page, int pageSize, FieldComparator sortComparator) {
- List<Project> result = projectService.getAll().stream()
- .sorted(Comparator.comparing(Project::getName))
- .filter(s -> filter(s))
- .limit(SEARCH_LIMIT)
- .collect(Collectors.toList());
+ Pageable pageable = createPageable(0, SEARCH_LIMIT, null);
+ List<Project> result = StringUtils.isBlank(partialSearch) ? projectRepository.findAll(pageable).toList() :
+ projectRepository.search(partialSearch, true, false, pageable);
return result;
}
@Override
public int getResultSetCount() {
- int result = (int) projectService.getAll().stream()
- .filter(s -> filter(s))
- .limit(SEARCH_LIMIT)
- .count();
- return result;
+ int result = StringUtils.isBlank(partialSearch) ?
+ (int) projectRepository.count() :
+ (int) projectRepository.count(partialSearch, true, false);
+ return result > SEARCH_LIMIT ? SEARCH_LIMIT : result;
}
public void search(String partialSearch) {
log.info("Searching projects using filter {}", partialSearch);
this.partialSearch = partialSearch;
super.reset();
- BindUtils.postNotifyChange(null, null, this, "*");
}
public void getLimited() {
log.info("Searching projects using limit {}", SEARCH_LIMIT);
this.partialSearch = null;
super.reset();
- BindUtils.postNotifyChange(null, null, this, "*");
}
}
package hu.user.lis.ui.data;
import hu.user.lis.db.ProjectStatus;
+import hu.user.lis.db.repository.ProjectStatusRepository;
import hu.user.lis.services.data.ProjectStatusService;
-import hu.user.lis.services.nosql.ProjectStatusDbService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
+import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
-import org.zkoss.bind.BindUtils;
import org.zkoss.zul.FieldComparator;
import java.util.List;
-import java.util.stream.Collectors;
@Component
@Log4j2
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-public class ProjectStatusDataModel extends CachedDataModel<ProjectStatus> {
+public class ProjectStatusDataModel extends CachedSpringDataModel<ProjectStatus> {
@Autowired
ProjectStatusService projectStatusService;
@Autowired
- ProjectStatusDbService projectStatusDbService;
+ ProjectStatusRepository projectStatusRepository;
private boolean activeOnly;
@Override
protected List<ProjectStatus> getResultSet(int page, int pageSize, FieldComparator sortComparator) {
List<ProjectStatus> result;
if (activeOnly) {
- result = projectStatusService.getAll().stream().filter(e -> e.isActive()).collect(Collectors.toList());
+ result = projectStatusRepository.findByActiveIsTrue(Sort.by(Sort.Direction.ASC, "order"));
} else {
- result = projectStatusService.getAll();
+ result = projectStatusRepository.findAll(Sort.by(Sort.Direction.ASC, "order"));
}
return result;
}
@Override
public int getResultSetCount() {
- return projectStatusService.getAll().size();
+ long result = activeOnly ? projectStatusRepository.countByActiveIsTrue() : projectStatusRepository.count();
+ return (int) result;
}
public void listAll() {
- super.reset();
this.activeOnly = false;
- BindUtils.postNotifyChange(null, null, this, "*");
+ super.reset();
}
public void listActive() {
- super.reset();
this.activeOnly = true;
- BindUtils.postNotifyChange(null, null, this, "*");
+ super.reset();
}
public void moveUp(ProjectStatus entity) {
}
public void append() {
- projectStatusService.createNew();
+ ProjectStatus entity = projectStatusService.createNew();
+ long currentCount = projectStatusRepository.count();
+ entity.setOrder((int) currentCount + 1);
+ projectStatusRepository.save(entity);
}
}
import hu.user.lis.db.Associate;
import hu.user.lis.db.Project;
import hu.user.lis.db.ServiceRecord;
+import hu.user.lis.db.repository.ServiceRecordRepository;
import hu.user.lis.services.data.ServiceRecordService;
-import hu.user.lis.services.nosql.ServiceRecordDbService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
-import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
-import org.springframework.data.domain.Sort;
-import org.springframework.data.mongodb.core.query.Criteria;
-import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.FieldComparator;
+import javax.persistence.EntityNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
@Component
@Log4j2
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-public class ServiceRecordsDataModel extends CachedDataModel<ServiceRecord> {
+public class ServiceRecordsDataModel extends CachedSpringDataModel<ServiceRecord> {
@Autowired
ServiceRecordService serviceRecordService;
@Autowired
- ServiceRecordDbService serviceRecordDbService;
+ ServiceRecordRepository serviceRecordRepository;
private boolean listAll;
private Long filterProjectId;
private Long filterAssociateId;
private boolean groupByAssociate;
- private Query filter() {
- Query result = new Query();
- if (listAll) {
- result.addCriteria(Criteria.where(ServiceRecordDbService.ID).gt(0));
- return result;
- }
- if (Objects.nonNull(filterProjectId)) {
- result.addCriteria(Criteria.where(ServiceRecordDbService.PROJECT_ID).is(filterProjectId));
- }
- if (Objects.nonNull(filterAssociateId)) {
- result.addCriteria(Criteria.where(ServiceRecordDbService.ASSOCIATE_ID).is(filterAssociateId));
- }
- return result;
- }
-
@Init
public void init() {
Clients.evalJavaScript("pushNav('/service-records')");
@Override
protected List<ServiceRecord> getResultSet(int page, int pageSize, FieldComparator sortComparator) {
- Query query = filter();
- if (sortComparator != null) {
- String orderBy = sortComparator.getRawOrderBy();
- Sort.Direction direction = sortComparator.isAscending() ? Sort.Direction.ASC : Sort.Direction.DESC;
- query.with(Sort.by(direction, orderBy));
- }
- Pageable pageable = PageRequest.of(page, pageSize);
- query.with(pageable);
- List<ServiceRecord> result = serviceRecordDbService.list(query);
+ Pageable pageable = createPageable(page, pageSize, sortComparator);
+ List<ServiceRecord> result = listAll ? serviceRecordRepository.findAll(pageable).toList() :
+ serviceRecordRepository.search(filterProjectId, filterAssociateId, pageable);
return result;
}
Map<Long, ServiceRecord> getGroupedServiceRecords() {
Map<Long, ServiceRecord> grouped = new HashMap<>();
- Query query = filter();
- List<ServiceRecord> allEntities = serviceRecordDbService.list(query);
-
+ List<ServiceRecord> allEntities = serviceRecordRepository.findByProjectId(filterProjectId);
allEntities.stream().forEach(s -> {
if (grouped.containsKey(s.getAssociate().getId())) {
ServiceRecord serviceRecord = grouped.get(s.getAssociate().getId());
@Override
public int getResultSetCount() {
- Query query = filter();
- return (int) serviceRecordDbService.count(query);
+ long result = listAll ? serviceRecordRepository.count() :
+ serviceRecordRepository.count(filterProjectId, filterAssociateId);
+ return (int) result;
}
public void listAll() {
}
public void addNew(ServiceRecord entity) {
- serviceRecordDbService.insert(entity);
+ serviceRecordRepository.save(entity);
}
- public ServiceRecord copy(ServiceRecord selectedEntity) {
- return serviceRecordService.copy(selectedEntity);
+ public ServiceRecord copy(ServiceRecord entity) {
+ return serviceRecordRepository.findById(entity.getId()).orElseThrow(EntityNotFoundException::new);
}
+//
+// public ServiceRecord copy(ServiceRecord entity, String property, Object value) {
+// ServiceRecord result = copy(entity);
+// try {
+// Field field = result.getClass().getDeclaredField(property);
+// field.setAccessible(true);
+// field.set(result, value);
+// } catch (Exception e) {
+// log.catching(e);
+// }
+// return result;
+// }
public ServiceRecord save(ServiceRecord selectedEntity) {
- return serviceRecordDbService.save(selectedEntity);
+ return serviceRecordRepository.save(selectedEntity);
}
+
+
}
private static final String PROJECT_ASSOCIATES_LIST = "~./project-associates.zul";
private static final String SERVICE_RECORDS_LIST = "~./service-records.zul";
private static final String SETTINGS_LIST = "~./settings.zul";
+ public static Map<String, String> NAVIGATION = ImmutableMap.of(
+ "/partners", PARTNERS_LIST,
+ "/projects", PROJECTS_LIST,
+ "/project", PROJECT_EDITOR,
+ "/associates", ASSOCIATES_LIST,
+ "/project-associates", PROJECT_ASSOCIATES_LIST,
+ "/service-records", SERVICE_RECORDS_LIST,
+ "/settings", SETTINGS_LIST
+ );
@WireVariable
BuildProperties buildProperties;
@WireVariable
SessionSettings sessionSettings;
-
@WireVariable
EventBus eventBus;
String searchPhrase;
String page;
- private Map<String, String> navigation = ImmutableMap.of(
- "/projects", PROJECTS_LIST,
- "/project", PROJECT_EDITOR,
- "/associates", ASSOCIATES_LIST,
- "/project-associates", PROJECT_ASSOCIATES_LIST,
- "/service-records", SERVICE_RECORDS_LIST,
- "/settings", SETTINGS_LIST
-
- );
@Init
public void init() {
// eventBus.setProjectEditorData(Collections.singletonMap("id", id));
eventBus.setProjectEditorData(id);
} else {
- if (navigation.containsKey(path)) {
- setPage(navigation.get(path));
+ if (NAVIGATION.containsKey(path)) {
+ setPage(NAVIGATION.get(path));
} else {
setPage(PARTNERS_LIST);
}
+<!--<zk>-->
+<!-- <window title="login">-->
+<!-- <label value="AAAAAAAAA"/>-->
+
+<!-- </window>-->
+
+<!--</zk>-->
<zk xmlns:n="native">
<n:form action="/login" method="POST">
<grid width="450px">
<columns>
- <column width="160px" />
- <column width="280px" />
+ <column width="160px"/>
+ <column width="280px"/>
</columns>
<rows>
<row spans="2" align="center">
</row>
<row>
<label value="User :"/>
- <textbox name="username" value="user"/></row>
+ <textbox name="username" value="user"/>
+ </row>
<row>
<label value="Password :"/>
- <textbox type="password" name="password" value="password"/> </row>
+ <textbox type="password" name="password" value="password"/>
+ </row>
<row spans="2" align="right">
<hlayout>
- <button type="reset" label="Reset" /> <button type="submit" label="Login" />
+ <button type="reset" label="Reset"/>
+ <button type="submit" label="Login"/>
</hlayout>
</row>
</rows>
<listhead sizable="true">
<listheader label="Projekt azonosító" sort="auto(project.humanId)" align="left"/>
<listheader label="Projekt név" sort="auto(project.name)" align="left"/>
- <listheader label="Partner név" sort="auto(partner.name)" align="left"/>
- <listheader label="Munkatárs" sort="auto(name)" align="left"/>
+ <listheader label="Partner név" sort="auto(project.partner.name)" align="left"/>
+ <listheader label="Munkatárs" sort="auto(associate.name)" align="left"/>
<listheader label="Munkanap" sort="auto(workDay)" align="left"/>
<listheader label="Leírás" sort="auto(description)" align="left"/>
<listheader label="Óraszám" sort="auto(workHours)" align="right" style="text-align: center"/>
<artifactId>log4j-api</artifactId>
<version>2.20.0</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.12.0</version>
+ </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>