Update controller pelayanan

Clean code
This commit is contained in:
Salman Manoe 2025-03-20 08:59:45 +07:00
parent c51d5e8018
commit 80887fea4c
77 changed files with 2575 additions and 3812 deletions

View File

@ -13,21 +13,21 @@
<relativePath>../Medifirst2000/pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jasamedika-config</artifactId>
@ -58,7 +58,7 @@
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -79,8 +79,8 @@
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring AOP -->
<dependency>
@ -185,29 +185,29 @@
<artifactId>swagger-springmvc</artifactId>
<version>0.6.5</version>
</dependency>
<!-- jasper -->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/zxing-parent -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
</dependency>
<dependency>
@ -232,39 +232,44 @@
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.barbecue/barbecue -->
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-bridge -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
</dependency>
<!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<version>1.8.4</version> </dependency> -->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- <dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
</dependencies>
<build>

View File

@ -1,27 +1,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-cssd</artifactId>
<packaging>war</packaging>
<name>jasamedika-cssd</name>
<parent>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-cssd</artifactId>
<packaging>war</packaging>
<name>jasamedika-cssd</name>
<parent>
<groupId>com.jasamedika</groupId>
<artifactId>Medifirst2000</artifactId>
<version>1.0.0</version>
<relativePath>../Medifirst2000/pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jasamedika-config</artifactId>
@ -45,14 +45,14 @@
<artifactId>jasamedika-business</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -72,7 +72,7 @@
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
@ -176,29 +176,29 @@
<artifactId>swagger-springmvc</artifactId>
<version>0.6.5</version>
</dependency>
<!-- jasper -->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/zxing-parent -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
</dependency>
<dependency>
@ -223,40 +223,37 @@
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.barbecue/barbecue -->
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-bridge -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
</dependency>
<!-- <dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<version>1.8.4</version> </dependency> -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
@ -268,9 +265,17 @@
<version>${commons-collections.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<build>
<finalName>jasamedika-cssd</finalName>
<plugins>
<plugin>
@ -290,7 +295,7 @@
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
<description>Module Medifirst2000 untuk Web / Controller. Tempat API diexpose oleh REST Client.</description>

View File

@ -1,27 +1,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-ipsrs</artifactId>
<packaging>war</packaging>
<name>jasamedika-ipsrs</name>
<parent>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-ipsrs</artifactId>
<packaging>war</packaging>
<name>jasamedika-ipsrs</name>
<parent>
<groupId>com.jasamedika</groupId>
<artifactId>Medifirst2000</artifactId>
<version>1.0.0</version>
<relativePath>../Medifirst2000/pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jasamedika-config</artifactId>
@ -45,14 +45,14 @@
<artifactId>jasamedika-business</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -72,7 +72,7 @@
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
@ -176,29 +176,29 @@
<artifactId>swagger-springmvc</artifactId>
<version>0.6.5</version>
</dependency>
<!-- jasper -->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/zxing-parent -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
</dependency>
<dependency>
@ -223,40 +223,37 @@
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.barbecue/barbecue -->
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-bridge -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
</dependency>
<!-- <dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<version>1.8.4</version> </dependency> -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
@ -268,9 +265,17 @@
<version>${commons-collections.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<build>
<finalName>jasamedika-ipsrs</finalName>
<plugins>
<plugin>
@ -290,7 +295,7 @@
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
<description>Module Medifirst2000 untuk Web / Controller. Tempat API diexpose oleh REST Client.</description>

View File

@ -1,27 +1,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-it</artifactId>
<packaging>war</packaging>
<name>jasamedika-it</name>
<parent>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-it</artifactId>
<packaging>war</packaging>
<name>jasamedika-it</name>
<parent>
<groupId>com.jasamedika</groupId>
<artifactId>Medifirst2000</artifactId>
<version>1.0.0</version>
<relativePath>../Medifirst2000/pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jasamedika-config</artifactId>
@ -45,14 +45,14 @@
<artifactId>jasamedika-business</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -72,7 +72,7 @@
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
@ -176,29 +176,29 @@
<artifactId>swagger-springmvc</artifactId>
<version>0.6.5</version>
</dependency>
<!-- jasper -->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/zxing-parent -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
</dependency>
<dependency>
@ -223,39 +223,36 @@
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.barbecue/barbecue -->
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-bridge -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
</dependency>
<!-- <dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<version>1.8.4</version> </dependency> -->
<dependency>
<groupId>commons-codec</groupId>
@ -267,10 +264,18 @@
<artifactId>commons-collections</artifactId>
<version>${commons-collections.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<build>
<finalName>jasamedika-it</finalName>
<plugins>
<plugin>
@ -290,7 +295,7 @@
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
<description>Module Medifirst2000 untuk Web / Controller. Tempat API diexpose oleh REST Client.</description>

View File

@ -12,16 +12,16 @@
</parent>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jasamedika-config</artifactId>
@ -45,14 +45,14 @@
<artifactId>jasamedika-business</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -72,7 +72,7 @@
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
@ -176,29 +176,29 @@
<artifactId>swagger-springmvc</artifactId>
<version>0.6.5</version>
</dependency>
<!-- jasper -->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/zxing-parent -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
</dependency>
<dependency>
@ -223,39 +223,36 @@
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.barbecue/barbecue -->
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-bridge -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
</dependency>
<!-- <dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<version>1.8.4</version> </dependency> -->
<dependency>
<groupId>commons-codec</groupId>
@ -268,6 +265,14 @@
<version>${commons-collections.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>jasamedika-k3kl</finalName>
@ -289,7 +294,7 @@
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
<description>Module Medifirst2000 untuk Web / Controller. Tempat API diexpose oleh REST Client.</description>

View File

@ -1,27 +1,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-laundry</artifactId>
<packaging>war</packaging>
<name>jasamedika-laundry</name>
<parent>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-laundry</artifactId>
<packaging>war</packaging>
<name>jasamedika-laundry</name>
<parent>
<groupId>com.jasamedika</groupId>
<artifactId>Medifirst2000</artifactId>
<version>1.0.0</version>
<relativePath>../Medifirst2000/pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jasamedika-config</artifactId>
@ -45,14 +45,14 @@
<artifactId>jasamedika-business</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -72,7 +72,7 @@
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
@ -176,29 +176,29 @@
<artifactId>swagger-springmvc</artifactId>
<version>0.6.5</version>
</dependency>
<!-- jasper -->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/zxing-parent -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
</dependency>
<dependency>
@ -223,39 +223,36 @@
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.barbecue/barbecue -->
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-bridge -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
</dependency>
<!-- <dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<version>1.8.4</version> </dependency> -->
<dependency>
<groupId>commons-codec</groupId>
@ -267,10 +264,18 @@
<artifactId>commons-collections</artifactId>
<version>${commons-collections.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<build>
<finalName>jasamedika-laundry</finalName>
<plugins>
<plugin>
@ -290,7 +295,7 @@
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
<description>Module Medifirst2000 untuk Web / Controller. Tempat API diexpose oleh REST Client.</description>

View File

@ -265,6 +265,14 @@
<version>${commons-collections.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>

View File

@ -9,70 +9,56 @@ import java.text.SimpleDateFormat;
* @author Roberto
*/
public class Constants {
public static final String JASAMEDIKA = "SkFTQU1FRElLQQ==";
public static final String APP_VERSION = "APP_VERSION";
public static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN";
//for example
public static final String IDR = "IDR";
public static final String RP = "RP";
public static final String COMMA = ",";
public static final DecimalFormat ONE_COMA_FORMAT = new DecimalFormat("#.#");
public static final DecimalFormat TWO_COMA_FORMAT = new DecimalFormat(
"#.##");
public static final DecimalFormat MONEY_FORMAT_WITHOUT_COMMA = new DecimalFormat(
"###,###");
public static final DecimalFormat TWO_COMA_FORMAT = new DecimalFormat("#.##");
public static final DecimalFormat MONEY_FORMAT_WITHOUT_COMMA = new DecimalFormat("###,###");
public static final class DateFormat {
public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat(
"yyyyMMdd");
public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat(
"dd MMM yyyy");
public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
public static final SimpleDateFormat yyyy_MM_dd_T_HH_mm_ss = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss");
public static final SimpleDateFormat yyyyMMdd_HH_mm_ss = new SimpleDateFormat(
"yyyyMMdd HH:mm:ss");
public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat("dd MMM yyyy");
public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final SimpleDateFormat yyyy_MM_dd_T_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public static final SimpleDateFormat yyyyMMdd_HH_mm_ss = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
}
/* message */
public static final class MessageInfo {
public static final String INFO_MESSAGE = "INFO_MESSAGE";
public static final String WARNING_MESSAGE = "WARNING_MESSAGE";
public static final String ERROR_MESSAGE = "ERROR_MESSAGE";
public static final String EXCEPTION_MESSAGE = "EXCEPTION_MESSAGE";
}
/* locale id (indonesia / default) and en (english) */
public static final class Locale {
public static final String INA = "ina";
public static final String EN = "en";
}
//Update perubahan di sini, harus disamakan dengan package yang ada di jasamedika-bussiness
//com.jasamedika.medifirst2000.logging.hibernate.async
public static final class HttpHeader {
public static final String SUPERVISING = "Supervising";
public static final String MODULE = "Module";
public static final String FORM = "Form";
public static final String ACTION = "Action";
public static final String URL_FORM = "AlamatUrlForm"; // syamsu
public static final String KD_RUANGAN = "KdRuangan"; // syamsu
public static final String KD_RUANGAN_T = "KdRuanganT"; // syamsu
public static final String KD_RUANGAN_A = "KdRuanganA"; // syamsu
public static final String TGL_KIRIM = "tglKirim"; // syamsu
// public static final String RUANGAN_TUJUAN = "ruanganTujuan"; // syamsu
// public static final String ID_RUANGAN_TUJUAN_ALT = "ruanganTujuanAlt"; // syamsu
public static final String KD_USER = "KdUser"; // syamsu
public static final String URL_FORM = "AlamatUrlForm";
public static final String KD_RUANGAN = "KdRuangan";
public static final String KD_RUANGAN_T = "KdRuanganT";
public static final String KD_RUANGAN_A = "KdRuanganA";
public static final String TGL_KIRIM = "tglKirim";
public static final String KD_USER = "KdUser";
}
}

View File

@ -9,10 +9,13 @@ package com.jasamedika.medifirst2000.constants;
public final class MessageResource {
public static final String LABEL_SUCCESS = "label.success";
public static final String LABEL_ERROR = "label.error";
public static final String LABEL_TRY_AGAIN = "label.try_again";
public static final String LABEL_SUCCESS_CREATED = "label.success.created";
public static final String LABEL_SUCCESS_OK = "label.success.ok";
public static final String LABEL_UPDATE_DATA_CUTI = "label.update.data.cuti";
}

View File

@ -1,161 +1,156 @@
package com.jasamedika.medifirst2000.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.MapRuanganToAkomodasiService;
import com.jasamedika.medifirst2000.service.RuanganService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.MapRuanganToAkomodasiVO;
import com.jasamedika.medifirst2000.vo.RuanganVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.MapRuanganToAkomodasiService;
import com.jasamedika.medifirst2000.service.RuanganService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.MapRuanganToAkomodasiVO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.CommonUtil.isNotNullOrEmpty;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.*;
@RestController
@RequestMapping("/akomodasi")
public class AkomodasiController extends LocaleController<MapRuanganToAkomodasiVO> {
private static final Logger LOGGER = LoggerFactory.getLogger(AkomodasiController.class);
private static final Logger LOGGER = getLogger(AkomodasiController.class);
@Autowired
private MapRuanganToAkomodasiService mapRuanganToAkomodasiService;
@Autowired
private RuanganService ruanganService;
private RuanganService<RuanganVO> ruanganService;
@RequestMapping(value = "/save-mapping", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/save-mapping", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> saveMappingAkomodasi(HttpServletRequest request,
@Valid @RequestBody MapRuanganToAkomodasiVO vo) {
Map<String, Object> result = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<>();
try {
MapRuanganToAkomodasiVO resultVo = new MapRuanganToAkomodasiVO();
if (CommonUtil.isNotNullOrEmpty(vo.getId())) {
MapRuanganToAkomodasiVO resultVo;
if (isNotNullOrEmpty(vo.getId())) {
resultVo = mapRuanganToAkomodasiService.update(vo);
} else {
resultVo = mapRuanganToAkomodasiService.add(vo);
}
result.put("data", resultVo);
if (CommonUtil.isNotNullOrEmpty(result)) {
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage);
if (isNotNullOrEmpty(result)) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, CREATED, mapHeaderMessage);
} else {
return RestUtil.getJsonHttptatus(HttpStatus.NOT_ACCEPTABLE);
return getJsonHttpStatus(NOT_ACCEPTABLE);
}
} catch (ServiceVOException sve) {
LOGGER.error("Got exception {} when add mapping akomodasi", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when mapRuanganToAkomodasiService.update/add", sve.getMessage());
addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when add mapping akomodasi", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when mapRuanganToAkomodasiService.update/add", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/delete-mapping", method = RequestMethod.DELETE)
@RequestMapping(value = "/delete-mapping", method = DELETE)
public ResponseEntity<String> deleteMappingAkomodasi(HttpServletRequest request, @RequestParam("id") Integer id) {
try {
Boolean result = mapRuanganToAkomodasiService.delete(id);
if (result) {
return RestUtil.getJsonResponse("Mapping is deleted successsfully", HttpStatus.OK);
return getJsonResponse("Mapping is deleted successsfully", OK);
} else {
return RestUtil.getJsonHttptatus(HttpStatus.NOT_ACCEPTABLE);
return getJsonHttpStatus(NOT_ACCEPTABLE);
}
} catch (ServiceVOException sve) {
LOGGER.error("Got exception {} when delete mapping akomodasi", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when mapRuanganToAkomodasiService.delete", sve.getMessage());
addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when delete mapping akomodasi", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when mapRuanganToAkomodasiService.delete", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-all-mapping", method = RequestMethod.GET)
@RequestMapping(value = "/get-all-mapping", method = GET)
public ResponseEntity<List<MapRuanganToAkomodasiVO>> getAllMappingAkomodasi(HttpServletRequest request) {
try {
List<MapRuanganToAkomodasiVO> result = mapRuanganToAkomodasiService.getAllActiveAkomodasi();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException sve) {
LOGGER.error("Got exception {} when get all mapping akomodasi", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getAllActiveAkomodasi", sve.getMessage());
addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when get all mapping akomodasi", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getAllActiveAkomodasi", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-mapping", method = RequestMethod.GET)
@RequestMapping(value = "/get-mapping", method = GET)
public ResponseEntity<MapRuanganToAkomodasiVO> getMappingAkomodasi(HttpServletRequest request,
@RequestParam("id") Integer id) {
try {
MapRuanganToAkomodasiVO result = mapRuanganToAkomodasiService.findById(id);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException sve) {
LOGGER.error("Got exception {} when get all mapping akomodasi", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when mapRuanganToAkomodasiService.findById", sve.getMessage());
addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when get all mapping akomodasi", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when mapRuanganToAkomodasiService.findById", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-kamar-by-ruangan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-kamar-by-ruangan", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<List<Map<String, Object>>> getKamarByRuangan(HttpServletRequest request,
@RequestParam(value = "idRuangan", required = true) Integer idRuangan) {
List<Map<String, Object>> result = null;
@RequestParam(value = "idRuangan") Integer idRuangan) {
try {
result = ruanganService.findKamarByRuangan(idRuangan);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
List<Map<String, Object>> result = ruanganService.findKamarByRuangan(idRuangan);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK);
} catch (Exception e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
return RestUtil.getJsonResponse(result, HttpStatus.OK);
}
@RequestMapping(value = "/get-akomodasi-ruangan-by-mapping-produk", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-akomodasi-ruangan-by-mapping-produk", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<List<Map<String, Object>>> getAkomodasiRuanganByMappingProduk(HttpServletRequest request,
@RequestParam(value = "idRuangan", required = true) Integer idRuangan) {
List<Map<String, Object>> result = null;
@RequestParam(value = "idRuangan") Integer idRuangan) {
try {
result = mapRuanganToAkomodasiService.getAkomodasiRuanganByMapProduk(idRuangan);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
List<Map<String, Object>> result = mapRuanganToAkomodasiService.getAkomodasiRuanganByMapProduk(idRuangan);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK);
} catch (Exception e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
return RestUtil.getJsonResponse(result, HttpStatus.OK);
}
}

View File

@ -1,82 +1,50 @@
package com.jasamedika.medifirst2000.controller;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.jasamedika.medifirst2000.base.vo.BaseMasterVO;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import com.jasamedika.medifirst2000.base.vo.BaseTransactionVO;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.service.ModelService;
import com.jasamedika.medifirst2000.util.JsonUtil;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.AntrianPasienRegistrasiVO;
import static com.jasamedika.medifirst2000.util.JsonUtil.ToMaps;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static java.net.URLDecoder.decode;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@RestController
@RequestMapping("/service")
public class GenericServiceController extends LocaleController<AntrianPasienRegistrasiVO> {
public class GenericServiceController extends LocaleController<BaseModelVO> {
private static final String CONTENT_TYPE = "Content-Type";
@Autowired
private ModelService<?> modelService;
private static final String CONTENT_TYPE = "Content-Type";
@SuppressWarnings("rawtypes")
public static List<Field> GetFields(Class data) {
List<Field> items = new ArrayList<Field>();
Class parent = data.getSuperclass();
Class tmpClass = null;
if (BaseModelVO.class.isAssignableFrom(data.getClass())) {
tmpClass = BaseTransactionVO.class;
} else if (BaseTransactionVO.class.isAssignableFrom(data.getClass())) {
tmpClass = BaseMasterVO.class;
}
if ((data == tmpClass)) {
for (Field field : data.getDeclaredFields()) {
items.add(field);
}
return items;
}
if (parent != null) {
for (Field field : GetFields(data.getSuperclass())) {
items.add(field);
}
}
for (Field field : data.getDeclaredFields()) {
items.add(field);
}
return items;
}
@RequestMapping(value = "/get-setting/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-setting/", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<String> getData(@RequestParam(value = "prefix", required = false) String prefix) {
return RestUtil.getJsonResponse(GetSettingDataFixed(prefix), HttpStatus.CREATED, mapHeaderMessage);
return getJsonResponse(GetSettingDataFixed(prefix), CREATED, mapHeaderMessage);
}
@RequestMapping(value = "/list-generic/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/list-generic/", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<List<Map<String, Object>>> listGeneric(
@RequestParam(value = "view", required = false) String entity,
@RequestParam(value = "select", required = false) String field,
@ -91,73 +59,68 @@ public class GenericServiceController extends LocaleController<AntrianPasienRegi
@RequestParam(value = "filter[filters][0][ignoreCase]", required = false) String ignorecase,
@RequestParam(value = "criteria", required = false) String criteria,
@RequestParam(value = "values", required = false) String values, HttpServletRequest request)
throws SecurityException, ClassNotFoundException, JSONException, UnsupportedEncodingException {
throws SecurityException, ClassNotFoundException {
String data = request.getQueryString();
data = URLDecoder.decode(data, "UTF-8");
data = decode(data);
String[] arrQueries = data.split("&");
StringBuilder criteriaBuilder = new StringBuilder(criteria);
StringBuilder valuesBuilder = new StringBuilder(values);
for (String query : arrQueries) {
if (query.indexOf("filter[filters][0][filter][field]") >= 0) {
if (criteria == null)
criteria = query.replace("filter[filters][0][filter][field]=", "");
else
criteria += "," + query.replace("filter[filters][0][filter][field]=", "");
} else if (query.indexOf("filter[filters][0][filter][value]") >= 0) {
if (values == null)
values = query.replace("filter[filters][0][filter][value]=", "");
else
values += "," + query.replace("filter[filters][0][filter][value]=", "");
if (query.contains("filter[filters][0][filter][field]")) {
criteriaBuilder.append(",").append(query.replace("filter[filters][0][filter][field]=", ""));
} else if (query.contains("filter[filters][0][filter][value]")) {
valuesBuilder.append(",").append(query.replace("filter[filters][0][filter][value]=", ""));
}
}
values = valuesBuilder.toString();
criteria = criteriaBuilder.toString();
if (field.equals("*")) {
field = "";
StringBuilder fieldBuilder = new StringBuilder();
for (Field fieldItem : GetFields(Class.forName("com.jasamedika.medifirst2000.entities." + entity))) {
{
String name = fieldItem.getName();
if (name.equals("serialVersionsUID"))
continue;
Boolean valid = false;
for (java.lang.annotation.Annotation annotation : fieldItem.getDeclaredAnnotations()) {
if (annotation instanceof JoinColumn) {
valid = true;
} else if (annotation instanceof Column) {
Column column = (Column) annotation;
if (column.name().endsWith("Fk"))
if (fieldItem.getName().endsWith("Id") == false)
valid = true;
} else if (annotation instanceof OneToMany) {
valid = true;
}
String name = fieldItem.getName();
if (name.equals("serialVersionsUID"))
continue;
boolean valid = false;
for (Annotation annotation : fieldItem.getDeclaredAnnotations()) {
if (annotation instanceof JoinColumn) {
valid = true;
} else if (annotation instanceof Column) {
Column column = (Column) annotation;
if (column.name().endsWith("Fk"))
if (!fieldItem.getName().endsWith("Id"))
valid = true;
} else if (annotation instanceof OneToMany) {
valid = true;
}
if (valid == false)
if (field.equals(""))
field += fieldItem.getName();
else
field += "," + fieldItem.getName();
}
if (!valid)
if (fieldBuilder.toString().isEmpty())
fieldBuilder.append(fieldItem.getName());
else
fieldBuilder.append(",").append(fieldItem.getName());
}
field = fieldBuilder.toString();
} else if (field.equals("**")) {
field = "*";
}
// for dateformat using [date]
List<Map<String, Object>> modelGenericVO = modelService.getAllData(entity, field, take, skip, page, pageSize,
logic, value, fieldS, operator, ignorecase, criteria, values);
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
try {
return new ResponseEntity<List<Map<String, Object>>>(JsonUtil.ToMaps(modelGenericVO), headers,
HttpStatus.OK);
return new ResponseEntity<>(ToMaps(modelGenericVO), headers, OK);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
}
return null;
public static List<Field> GetFields(Class<?> data) {
List<Field> items = new ArrayList<>();
Class<?> parent = data.getSuperclass();
if (parent != null)
items.addAll(GetFields(data.getSuperclass()));
items.addAll(Arrays.asList(data.getDeclaredFields()));
return items;
}
}

View File

@ -1,38 +1,36 @@
package com.jasamedika.medifirst2000.controller;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.KonsultasiService;
import com.jasamedika.medifirst2000.service.RegistrasiPelayananService;
import com.jasamedika.medifirst2000.vo.AntrianPasienDiPeriksaVO;
import com.jasamedika.medifirst2000.vo.KonsultasiVO;
import com.jasamedika.medifirst2000.vo.RegistrasiPelayananVO;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.IBaseRestController;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.KonsultasiService;
import com.jasamedika.medifirst2000.service.RegistrasiPelayananService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.GridAntrianPasienDiPeriksaVO;
import com.jasamedika.medifirst2000.vo.KonsultasiVO;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_ERROR;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.*;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
/**
* Controller class for KonsultasiController
@ -41,46 +39,42 @@ import com.jasamedika.medifirst2000.vo.KonsultasiVO;
*/
@RestController
@RequestMapping("/konsultasi")
@JsonIgnoreProperties(ignoreUnknown = true)
public class KonsultasiController extends LocaleController<KonsultasiVO> implements
IBaseRestController<KonsultasiVO> {
private static final Logger LOGGER = LoggerFactory.getLogger(KonsultasiController.class);
@JsonIgnoreProperties(ignoreUnknown = true)
public class KonsultasiController extends LocaleController<AntrianPasienDiPeriksaVO> {
private static final Logger LOGGER = getLogger(KonsultasiController.class);
@Autowired
private KonsultasiService konsultasiService;
private KonsultasiService<KonsultasiVO> konsultasiService;
@Autowired
private RegistrasiPelayananService registrasiPelayananService;
private RegistrasiPelayananService<RegistrasiPelayananVO> registrasiPelayananService;
@RequestMapping(value = "/save-konsultasi", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String,Object>> save(@Valid @RequestBody KonsultasiVO vo,HttpServletRequest request) {
@RequestMapping(value = "/save-konsultasi", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> save(@Valid @RequestBody KonsultasiVO vo, HttpServletRequest request) {
try {
Map<String,Object> result = konsultasiService.addKonsultasi2(vo);
if (null != result){
mapHeaderMessage.clear();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request ));
}else{
mapHeaderMessage.clear();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_ERROR,getMessage(MessageResource.LABEL_ERROR,request ));
Map<String, Object> result = konsultasiService.addKonsultasi2(vo);
mapHeaderMessage.clear();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
} else {
mapHeaderMessage.put(LABEL_ERROR, getMessage(MessageResource.LABEL_ERROR, request));
}
SaveLog("Konsultasi", "Dokter",request);
return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage);
SaveLog("Konsultasi", "Dokter");
return getJsonResponse(result, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when add kebutuhan dasar", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when addKonsultasi2", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when add kebutuhan dasar", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when addKonsultasi2", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/antrian-pasien-list-konsul/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<GridAntrianPasienDiPeriksaVO>> getAllVOWithQueryString(
@RequestMapping(value = "/antrian-pasien-list-konsul/", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<AntrianPasienDiPeriksaVO>> getAllVOWithQueryString(
@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
@RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit,
@RequestParam(value = "sort", required = false, defaultValue = "noRec") String sort,
@ -90,73 +84,22 @@ public class KonsultasiController extends LocaleController<KonsultasiVO> impleme
@RequestParam(value = "dateEnd", required = false) String dateEnd,
@RequestParam(value = "noCm", required = false) String noCm,
@RequestParam(value = "pegawaiId", required = false) Integer pegawaiId) {
Map<String, Object> resultPageMap = registrasiPelayananService.findAllAntrianPagingKonsultasi(page, limit, sort, dir,
ruanganId, dateStart, dateEnd, noCm, pegawaiId);
Map<String, Object> resultPageMap = registrasiPelayananService.findAllAntrianPagingKonsultasi(page, limit, sort,
dir, ruanganId, dateStart, dateEnd, noCm, pegawaiId);
return constructListPageResult(resultPageMap);
}
@Override
public ResponseEntity<Collection<KonsultasiVO>> getAllVOWithQueryString(HttpServletRequest request,
Integer page, Integer limit, String sort, String dir) {
return null;
}
@Override
public ResponseEntity<KonsultasiVO> getVO(Integer id) {
return null;
}
@Override
public ResponseEntity<String> addVO(KonsultasiVO vo) {
return null;
}
@Override
public ResponseEntity<String> editVO(KonsultasiVO vo) {
return null;
}
@Override
public ResponseEntity<String> deleteVO(Integer id) {
return null;
}
@Override
public ResponseEntity<List<KonsultasiVO>> getAllVO() {
return null;
}
@RequestMapping(value = "/get-riwayat-konsultasi/{noCm}/{startDate}/{endDate}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Map<String, Object>>> getRiwayatKonsultasi(@PathVariable("noCm") String noCm,@PathVariable("startDate") String startDate,
@PathVariable("endDate") String endDate,HttpServletRequest request) {
List<Map<String, Object>> result = null;
@RequestMapping(value = "/get-riwayat-konsultasi/{noCm}/{startDate}/{endDate}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<List<Map<String, Object>>> getRiwayatKonsultasi(@PathVariable("noCm") String noCm,
@PathVariable("startDate") String startDate, @PathVariable("endDate") String endDate,
HttpServletRequest request) {
try {
result = konsultasiService.getRiwayatKonsultasi(noCm, startDate, endDate);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
List<Map<String, Object>> result = konsultasiService.getRiwayatKonsultasi(noCm, startDate, endDate);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK);
} catch (Exception e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
return RestUtil.getJsonResponse(result, HttpStatus.OK);
}
@RequestMapping(value = "/get-konsultasi-kosong", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Map<String, Object>>> getKonsultasiKosong(HttpServletRequest request,
@RequestParam(value = "tglAwal", required = true) String strTglAwal,
@RequestParam(value = "tglAkhir", required = true) String strTglAkhir) {
List<Map<String, Object>> result = null;
try {
result = konsultasiService.findAllKonsultasiTindakanKosong(strTglAwal, strTglAkhir);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
} catch (Exception e) {
e.printStackTrace();
}
return RestUtil.getJsonResponse(result, HttpStatus.OK);
}
}

View File

@ -1,12 +1,10 @@
package com.jasamedika.medifirst2000.controller;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.vo.MapProdukPaketToProdukVO;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.MapProdukPaketToProdukService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.MapProdukPaketToProdukVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@ -18,6 +16,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@ -31,6 +30,7 @@ import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
@RequestMapping("/paket-tindakan")
public class MapProdukPaketController extends LocaleController<MapProdukPaketToProdukVO> {
@Autowired
private MapProdukPaketToProdukService mapProdukPaketToProdukService;
@ -40,11 +40,11 @@ public class MapProdukPaketController extends LocaleController<MapProdukPaketToP
mapProdukPaketToProdukService.save(vo);
Map<String, String> message = new HashMap<>();
message.put(CREATED.getReasonPhrase(), "Berhasil tersimpan");
return RestUtil.getJsonResponse(vo, CREATED, message);
return getJsonResponse(vo, CREATED, message);
} catch (ServiceVOException e) {
Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error);
return getJsonResponse(null, BAD_REQUEST, error);
}
}
@ -53,7 +53,7 @@ public class MapProdukPaketController extends LocaleController<MapProdukPaketToP
List<MapProdukPaketToProdukVO> data = mapProdukPaketToProdukService.get();
Map<String, String> message = new HashMap<>();
message.put(OK.getReasonPhrase(), "Berhasil");
return RestUtil.getJsonResponse(data, OK, message);
return getJsonResponse(data, OK, message);
}
@RequestMapping(value = "/{paketId}", method = GET)
@ -61,7 +61,7 @@ public class MapProdukPaketController extends LocaleController<MapProdukPaketToP
List<MapProdukPaketToProdukVO> data = mapProdukPaketToProdukService.get(paketId);
Map<String, String> message = new HashMap<>();
message.put(OK.getReasonPhrase(), "Berhasil");
return RestUtil.getJsonResponse(data, OK, message);
return getJsonResponse(data, OK, message);
}
@RequestMapping(value = "/{noRec}", method = GET)
@ -69,7 +69,7 @@ public class MapProdukPaketController extends LocaleController<MapProdukPaketToP
MapProdukPaketToProdukVO data = mapProdukPaketToProdukService.get(noRec);
Map<String, String> message = new HashMap<>();
message.put(OK.getReasonPhrase(), "Berhasil");
return RestUtil.getJsonResponse(data, OK, message);
return getJsonResponse(data, OK, message);
}
@RequestMapping(value = "/{noRec}", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ -77,6 +77,7 @@ public class MapProdukPaketController extends LocaleController<MapProdukPaketToP
boolean status = mapProdukPaketToProdukService.delete(noRec);
Map<String, String> message = new HashMap<>();
message.put(OK.getReasonPhrase(), "Berhasil");
return RestUtil.getJsonResponse(status, OK, message);
return getJsonResponse(status, OK, message);
}
}

View File

@ -1,9 +1,7 @@
package com.jasamedika.medifirst2000.controller;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.dto.BatalPaketProdukDto;
import com.jasamedika.medifirst2000.dto.TagihanPendaftaranDto;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
@ -13,10 +11,7 @@ import com.jasamedika.medifirst2000.vo.MapProdukPaketToProdukVO;
import com.jasamedika.medifirst2000.vo.MapProdukPaketVO;
import com.jasamedika.medifirst2000.vo.PelayananPasienVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.*;
@ -26,11 +21,20 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
@RequestMapping("/pelayanan")
public class PelayananController extends LocaleController<PelayananPasienVO> {
private static final Logger LOGGER = LoggerFactory.getLogger(PelayananController.class);
private static final Logger LOGGER = getLogger(PelayananController.class);
@Autowired
private PelayananPasienService pelayananPasienService;
@ -50,275 +54,262 @@ public class PelayananController extends LocaleController<PelayananPasienVO> {
@Autowired
private MapProdukPaketToProdukService mapProdukPaketToProdukService;
@RequestMapping(value = "/calculate-indikator-pelayanan", method = RequestMethod.GET)
@RequestMapping(value = "/calculate-indikator-pelayanan", method = GET)
public ResponseEntity<List<Map<String, Object>>> calculateIndikatorPelayanan(HttpServletRequest request,
@RequestParam("tahun") String tahun) {
try {
List<Map<String, Object>> result = pasienDaftarService.findIndikatorPelayanan(tahun);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException sve) {
LOGGER.error("Got ServiceVOException {} when calculate indikator pelayanan", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when findIndikatorPelayanan", sve.getMessage());
addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when calculate indikator pelayanan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when findIndikatorPelayanan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/validate-nama-produk", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/validate-nama-produk", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> validateNamaProduk(HttpServletRequest request,
@RequestParam(value = "idProduk", required = false) Integer idProduk,
@RequestParam(value = "namaProduk") String namaProduk) {
try {
Map<String, Object> result = produkService.validateNamaProduk(idProduk, namaProduk);
return RestUtil.getJsonResponse(result, HttpStatus.OK);
return getJsonResponse(result, OK);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when validate nama produk", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when validateNamaProduk", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when validate nama produk", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when validateNamaProduk", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/paket-to-produk", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/paket-to-produk", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getMappingPaketToProduk(HttpServletRequest request,
@RequestParam(value = "idMapping") Integer idMapping) {
try {
Map<String, Object> result = produkService.getMappingPaketToProduk(idMapping);
return RestUtil.getJsonResponse(result, HttpStatus.OK);
return getJsonResponse(result, OK);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when get mapping paket to produk", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getMappingPaketToProduk", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when get mapping paket to produk", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getMappingPaketToProduk", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/all-paket-produk", method = RequestMethod.GET)
@RequestMapping(value = "/all-paket-produk", method = GET)
public ResponseEntity<List<Map<String, Object>>> getAllPaketToProduk(HttpServletRequest request) {
try {
List<Map<String, Object>> result = produkService.getAllPaketToProduk();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException sve) {
LOGGER.error("Got ServiceVOException {} when get all data paket to produk", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getAllPaketToProduk", sve.getMessage());
addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when get all data paket to produk", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getAllPaketToProduk", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/master-satuan-standar", method = RequestMethod.GET)
@RequestMapping(value = "/master-satuan-standar", method = GET)
public ResponseEntity<List<Map<String, Object>>> getAllMasterSatuanStandar(HttpServletRequest request) {
try {
List<Map<String, Object>> result = satuanStandarService.getAll();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException sve) {
LOGGER.error("Got ServiceVOException {} when get all master satuan standar distinct on", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when satuanStandarService.getAll", sve.getMessage());
addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when get all master satuan standar distinct on", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when satuanStandarService.getAll", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/klaim-diskon", method = RequestMethod.GET)
@RequestMapping(value = "/klaim-diskon", method = GET)
public ResponseEntity<List<String>> KlaimDiskon(HttpServletRequest request,
@RequestParam(value = "noRegistrasi") String noRegistrasi,
@RequestParam(value = "totalKlaim") Double totalKlaim,
@RequestParam(value = "jenisDiskon") Integer jenisDiskon) {
try {
List<String> result = pelayananPasienService.updateKlaimDiskon(noRegistrasi, totalKlaim, jenisDiskon);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when klaim diskon karyawan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when updateKlaimDiskon", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when klaim diskon karyawan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when updateKlaimDiskon", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/reset-klaim-diskon", method = RequestMethod.GET)
@RequestMapping(value = "/reset-klaim-diskon", method = GET)
public ResponseEntity<String> ResetKlaimDiskon(HttpServletRequest request,
@RequestParam(value = "noRegistrasi") String noRegistrasi) {
try {
String result = pelayananPasienService.resetKlaimDiskon(noRegistrasi);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when reset klaim diskon karyawan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when resetKlaimDiskon", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when reset klaim diskon karyawan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when resetKlaimDiskon", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/check-existing-harga-produk-kelas", method = RequestMethod.GET)
@RequestMapping(value = "/check-existing-harga-produk-kelas", method = GET)
public ResponseEntity<List<Map<String, Object>>> checkExistingHargaProdukKelas(HttpServletRequest request,
@RequestParam(value = "kelasId") Integer idKelas, @RequestParam(value = "produkId") Integer idProduk,
@RequestParam(value = "mappingId", required = false) Integer idMapping) {
try {
List<Map<String, Object>> result = produkService.findExistingMapHargaKelas(idKelas, idProduk, idMapping);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when check existing harga produk kelas", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when findExistingMapHargaKelas", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when check existing harga produk kelas", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when findExistingMapHargaKelas", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/tagihan/daftar/{noRegistrasi}", method = RequestMethod.GET)
@RequestMapping(value = "/tagihan/daftar/{noRegistrasi}", method = GET)
public ResponseEntity<List<TagihanPendaftaranDto>> daftarTagihan(HttpServletRequest request,
@PathVariable String noRegistrasi) {
try {
List<TagihanPendaftaranDto> result = pelayananPasienService.tagihan(noRegistrasi);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when get daftar tagihan {}", e.getMessage(), noRegistrasi);
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when pelayananPasienService.tagihan {}", e.getMessage(),
noRegistrasi);
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when get daftar tagihan {}", jse.getMessage(), noRegistrasi);
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when pelayananPasienService.tagihan {}", jse.getMessage(),
noRegistrasi);
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/tagihan/diskon/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/tagihan/diskon/save", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Object> simpanDiskonTagihan(HttpServletRequest request,
@RequestParam(value = "kode-voucher", required = false) String kodeVoucher,
@RequestBody List<TagihanPendaftaranDto> dtoList) {
try {
pelayananPasienService.diskonTagihan(kodeVoucher, dtoList);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(dtoList, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(dtoList, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when simpan diskon tagihan", e.getMessage());
LOGGER.error("Got ServiceVOException {} when diskonTagihan", e.getMessage());
Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error);
return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when simpan diskon tagihan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when diskonTagihan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/tagihan/diskon/batal-paket", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/tagihan/diskon/batal-paket", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Object> batalPaket(HttpServletRequest request, @RequestBody BatalPaketProdukDto dto) {
try {
pelayananPasienService.batalPaketProduk(request, dto);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(dto, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(dto, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when batal diskon paket", e.getMessage());
LOGGER.error("Got ServiceVOException {} when batalPaketProduk", e.getMessage());
Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error);
return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when batal diskon paket", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when batalPaketProduk", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/vouchers/validity", method = RequestMethod.GET)
@RequestMapping(value = "/vouchers/validity", method = GET)
public ResponseEntity<Object> isValidVoucher(HttpServletRequest request,
@RequestParam("kode-voucher") String kodeVoucher, @RequestParam("no-registrasi") String noRegistrasi) {
try {
boolean validVoucher = pelayananPasienService.isValidVoucher(kodeVoucher, noRegistrasi);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(validVoucher, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(validVoucher, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when check voucher validity", e.getMessage());
LOGGER.error("Got ServiceVOException {} when isValidVoucher", e.getMessage());
Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(false, HttpStatus.BAD_REQUEST, error);
return getJsonResponse(false, BAD_REQUEST, error);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when check voucher validity", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when isValidVoucher", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/produk-paket/paket", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/produk-paket/paket", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Object> simpanMappingListProdukPaket(HttpServletRequest request,
@RequestBody List<MapProdukPaketVO> vos) {
try {
mapProdukPaketService.saveAll(vos);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(vos, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(vos, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when simpan mapping list produk paket", e.getMessage());
LOGGER.error("Got ServiceVOException {} when mapProdukPaketService.saveAll", e.getMessage());
Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error);
return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when simpan mapping list produk paket", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when mapProdukPaketService.saveAll", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/produk-paket/produk", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/produk-paket/produk", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Object> simpanMappingEntriProdukPaket(HttpServletRequest request,
@RequestBody List<MapProdukPaketToProdukVO> vos) {
try {
mapProdukPaketToProdukService.saveAll(vos);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(vos, HttpStatus.OK, mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(vos, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when simpan mapping entri produk paket", e.getMessage());
LOGGER.error("Got ServiceVOException {} when mapProdukPaketToProdukService.saveAll", e.getMessage());
Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error);
return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when simpan mapping entri produk paket", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when mapProdukPaketToProdukService.saveAll", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}

View File

@ -1,16 +1,14 @@
package com.jasamedika.medifirst2000.controller;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.dto.ProdukPaketDto;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.ProdukPaketService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.ProdukVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
@ -21,10 +19,11 @@ import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttptatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.springframework.http.HttpStatus.CREATED;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@ -37,7 +36,7 @@ import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RequestMapping("/produk")
public class ProdukController extends LocaleController<ProdukVO> {
private static final Logger LOGGER = LoggerFactory.getLogger(ProdukController.class);
private static final Logger LOGGER = getLogger(ProdukController.class);
@Autowired
private ProdukPaketService produkPaketService;
@ -49,14 +48,14 @@ public class ProdukController extends LocaleController<ProdukVO> {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(dto, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when simpan produk paket", e.getMessage());
LOGGER.error("Got ServiceVOException {} when produkPaketService.save", e.getMessage());
Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage());
return getJsonResponse(null, HttpStatus.BAD_REQUEST, error);
return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when simpan produk paket", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when produkPaketService.save", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}

View File

@ -1,42 +0,0 @@
package com.jasamedika.medifirst2000.controller.base;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
/**
* Base Rest Operation for Controller Class
*
* @author Roberto
*/
public interface IBaseRestController<V extends BaseModelVO> extends
IRestPageController<V> {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<V> getVO(@PathVariable("id") Integer id);
@RequestMapping(value = "/", method = RequestMethod.PUT, consumes = { "application/json" })
@ResponseBody
public ResponseEntity<String> addVO(@RequestBody V vo);
@RequestMapping(value = "/", method = RequestMethod.POST, consumes = { "application/json" })
@ResponseBody
public ResponseEntity<String> editVO(@RequestBody V vo);
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<String> deleteVO(@PathVariable("id") Integer id);
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<V>> getAllVO();
}

View File

@ -1,41 +0,0 @@
package com.jasamedika.medifirst2000.controller.base;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
/**
* Base Rest Operation for 'pagination' Controller Class
*
* @author Roberto
*/
public interface IRestPageController<V extends BaseModelVO> {
/**
*
* @param page
* : page of
* @param limit
* : limit query
* @param sort
* : sort by
* @param dir
* : direction {asc:desc}
* @return Collection of VO, Total-Count & Total Pages on response header
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Collection<V>> getAllVOWithQueryString(
HttpServletRequest request,
@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
@RequestParam(value = "dir", required = false, defaultValue = "asc") String dir);
}

View File

@ -1,67 +1,55 @@
package com.jasamedika.medifirst2000.controller.base;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.ActivityPegawaiService;
import com.jasamedika.medifirst2000.service.LoginUserService;
import com.jasamedika.medifirst2000.service.ModelService;
import com.jasamedika.medifirst2000.vo.ModelVO;
import com.jasamedika.medifirst2000.vo.PegawaiVO;
import io.socket.client.IO;
import io.socket.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.service.ActivityPegawaiService;
import com.jasamedika.medifirst2000.service.LoginUserService;
import com.jasamedika.medifirst2000.service.ModelService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.ModelVO;
import com.jasamedika.medifirst2000.vo.PasienVO;
import com.jasamedika.medifirst2000.vo.PegawaiVO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.*;
import io.socket.client.IO;
import static com.jasamedika.medifirst2000.constants.Constants.Locale.INA;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER;
import static com.jasamedika.medifirst2000.core.web.WebConstants.PageParameter.*;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* Base Controller Class for handling messaga resource for internationalization
* Base Controller Class for handling message resource for internationalization
* & locale
*
* @author Roberto
*/
public abstract class LocaleController<V extends BaseModelVO> {
/*
* messageSource bean injected for each controller for accessing message
* source
*/
@Autowired
private ActivityPegawaiService activityPegawaiServiceImpl;
@ -74,82 +62,62 @@ public abstract class LocaleController<V extends BaseModelVO> {
@Autowired
private MessageSource messageSource;
@SuppressWarnings("rawtypes")
@Autowired
private ModelService modelService;
private ModelService<ModelVO> modelService;
protected Map<String, String> mapHeaderMessage = new HashMap<String, String>();
protected Map<String, String> mapHeaderMessage = new HashMap<>();
/*
* code locale
*/
protected String getMessage(String code, HttpServletRequest request) {
return messageSource.getMessage(code, null, new Locale(getCoociesLanguage(request)));
}
protected void SaveLog(String keterangan, String group, HttpServletRequest request) {
protected void SaveLog(String keterangan, String group) {
activityPegawaiServiceImpl.record(
pegawaiConverter.transferModelToVO(loginUserService.getLoginUser().getPegawai(), new PegawaiVO()),
new Date(), keterangan, group);
}
protected Object getItem(HttpServletRequest request, Object vo) {
BufferedReader reader;
String read = null;
String resultData = "";
Gson gson = new Gson();
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((read = reader.readLine()) != null) {
resultData += read;
System.out.println(read);
}
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
StringBuilder resultData = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String read;
while ((read = reader.readLine()) != null)
resultData.append(read);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
return gson.fromJson(resultData.toString(), vo.getClass());
} catch (IOException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
return vo = gson.fromJson(resultData, vo.getClass());
}
protected Object getItem2(HttpServletRequest request, Object vo) {
BufferedReader reader;
String read = null;
String resultData = "";
Gson gson = new Gson();
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((read = reader.readLine()) != null) {
resultData += read;
System.out.println(read);
}
String read;
StringBuilder resultData = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((read = reader.readLine()) != null)
resultData.append(read);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if (json.getAsString() instanceof String) {
return new Date();
} else {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
gsonBuilder.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> {
if (json.getAsString() != null) {
return new Date();
} else {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
gson = gsonBuilder.create();
Gson gson = gsonBuilder.create();
return gson.fromJson(resultData.toString(), vo.getClass());
} catch (IOException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
return vo = gson.fromJson(resultData, vo.getClass());
}
@RequestMapping(value = "/lang/{lang}", method = RequestMethod.GET)
@RequestMapping(value = "/lang/{lang}", method = GET)
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
@PathVariable("lang") String lang) throws Exception {
@PathVariable("lang") String lang) {
Cookie[] cookies = request.getCookies();
List<Cookie> cookieList = new ArrayList<Cookie>();
List<Cookie> cookieList;
if (cookies != null) {
cookieList = Arrays.asList(cookies);
for (Cookie cookie : cookieList) {
@ -161,7 +129,6 @@ public abstract class LocaleController<V extends BaseModelVO> {
}
}
}
if (lang.equalsIgnoreCase("en")) {
Cookie c = new Cookie("lang", "en");
c.setPath("/");
@ -178,63 +145,50 @@ public abstract class LocaleController<V extends BaseModelVO> {
c.setDomain("localhost");
response.addCookie(c);
}
return true;
}
/*
* default locale ID
*/
protected String getMessage(String code) {
return messageSource.getMessage(code, null, new Locale(Constants.Locale.INA));
return messageSource.getMessage(code, null, new Locale(INA));
}
protected void addHeaderMessage(String key, String message) {
this.mapHeaderMessage.put(key, message);
}
@RequestMapping(value = "/entity-serelize/{entity}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/entity-serelize/{entity}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<ModelVO> serializeEntity(@PathVariable("entity") String entity, HttpServletRequest request) {
ModelVO modelDTO = modelService.getModelSerializeEntity(entity, getCoociesLanguage(request));
return RestUtil.getJsonResponse(modelDTO, HttpStatus.OK);
return getJsonResponse(modelDTO, OK);
}
public String getCoociesLanguage(HttpServletRequest request) {
Cookie cookie[] = request.getCookies();
Cookie[] cookie = request.getCookies();
Cookie cook;
String lang = Constants.Locale.INA;
String lang = INA;
if (cookie != null) {
for (int i = 0; i < cookie.length; i++) {
cook = cookie[i];
for (Cookie value : cookie) {
cook = value;
if (cook.getName().equalsIgnoreCase("lang"))
lang = cook.getValue();
}
}
return lang;
}
@SuppressWarnings("rawtypes")
protected ResponseEntity constructListPageResult(Map<String, Object> map) {
protected ResponseEntity<Collection<V>> constructListPageResult(Map<String, Object> map) {
if (map == null) {
Map<String, String> mapHeaderMessage = new HashMap<String, String>();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER, "0");
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER, "0");
mapHeaderMessage.put(Constants.MessageInfo.ERROR_MESSAGE, "Data not found.");
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, mapHeaderMessage);
Map<String, String> mapHeaderMessage = new HashMap<>();
mapHeaderMessage.put(TOTAL_PAGE_HEADER, "0");
mapHeaderMessage.put(TOTAL_COUNT_HEADER, "0");
mapHeaderMessage.put(ERROR_MESSAGE, "Data not found.");
return getJsonResponse(null, BAD_REQUEST, mapHeaderMessage);
} else {
@SuppressWarnings("unchecked")
Collection<PasienVO> vos = (Collection<PasienVO>) map.get(WebConstants.PageParameter.LIST_DATA);
Map<String, String> mapHeaderMessage = new HashMap<String, String>();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER,
String.valueOf(map.get(WebConstants.PageParameter.TOTAL_PAGES)));
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER,
String.valueOf(map.get(WebConstants.PageParameter.TOTAL_ELEMENTS)));
return RestUtil.getJsonResponse(vos, HttpStatus.OK, mapHeaderMessage);
Collection<V> vos = (Collection<V>) map.get(LIST_DATA);
Map<String, String> mapHeaderMessage = new HashMap<>();
mapHeaderMessage.put(TOTAL_PAGE_HEADER, String.valueOf(map.get(TOTAL_PAGES)));
mapHeaderMessage.put(TOTAL_COUNT_HEADER, String.valueOf(map.get(TOTAL_ELEMENTS)));
return getJsonResponse(vos, OK, mapHeaderMessage);
}
}
@ -242,86 +196,66 @@ public abstract class LocaleController<V extends BaseModelVO> {
return activityPegawaiServiceImpl.GetSettingDataFixed(prefix);
}
protected void BroadcastMessage(final String to, final Object data) {
final io.socket.client.Socket socket;
protected void BroadcastMessage(final Object data) {
final Socket socket;
try {
String url = GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url);
socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() {
@Override
public void call(Object... args) {
try {
Gson gson = new Gson();
String json = gson.toJson(data);
JSONObject item = new JSONObject(
"{\"to\":\"" + to + "\",\"message\":\"" + json.replace("\"", "'") + "\"}");
socket.emit("subscribe", item);
} catch (JSONException e) {
e.printStackTrace();
}
socket.on(Socket.EVENT_CONNECT, args -> {
try {
Gson gson = new Gson();
String json = gson.toJson(data);
JSONObject item = new JSONObject(
"{\"to\":\"" + "ResultLabDevice" + "\",\"message\":\"" + json.replace("\"", "'") + "\"}");
socket.emit("subscribe", item);
} catch (JSONException e) {
throw new ServiceVOException(e.getMessage());
}
});
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
}
protected void BroadcastMessage(final String to, final String data) {
final io.socket.client.Socket socket;
final Socket socket;
try {
socket = IO.socket(GetSettingDataFixed("UrlSocketMessaging"));
socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() {
@Override
public void call(Object... args) {
try {
JSONObject item = new JSONObject("{\"to\":\"" + to + "\",\"message\":\"" + data + "\"}");
socket.emit("subscribe", item);
} catch (JSONException e) {
e.printStackTrace();
}
socket.on(Socket.EVENT_CONNECT, args -> {
try {
JSONObject item = new JSONObject("{\"to\":\"" + to + "\",\"message\":\"" + data + "\"}");
socket.emit("subscribe", item);
} catch (JSONException e) {
throw new ServiceVOException(e.getMessage());
}
});
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
}
protected void BroadcastMessageOther(final String to, final Object data) {
final io.socket.client.Socket socket;
protected void BroadcastMessageOther(final Object data) {
final Socket socket;
try {
String url = GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url);
socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() {
@Override
public void call(Object... args) {
try {
Map<String, Object> result = new HashMap<>();
result.put("message", data);
result.put("to", to);
Gson gson = new Gson();
JSONObject item = new JSONObject(gson.toJson(result));
socket.emit("subscribe", item);
} catch (JSONException e) {
e.printStackTrace();
}
socket.on(Socket.EVENT_CONNECT, args -> {
try {
Map<String, Object> result = new HashMap<>();
result.put("message", data);
result.put("to", "PermintaanPerbaikan");
Gson gson = new Gson();
JSONObject item = new JSONObject(gson.toJson(result));
socket.emit("subscribe", item);
} catch (JSONException e) {
throw new ServiceVOException(e.getMessage());
}
});
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
}

View File

@ -1,78 +1,64 @@
package com.jasamedika.medifirst2000.controller.base;
import java.util.List;
import org.springframework.core.GenericTypeResolver;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.monitorjbl.json.JsonResult;
import com.monitorjbl.json.JsonView;
import com.monitorjbl.json.Match;
import org.springframework.core.GenericTypeResolver;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import static com.jasamedika.medifirst2000.constants.Constants.COMMA;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* Base Controller Class for handling "include" parameter to controller
* @see https://github.com/monitorjbl/json-view
* Base Controller Class for handling "include" parameter to controller
*
* @see <a href="https://github.com/monitorjbl/json-view">json view</a>
*
* @author Roberto
*/
public abstract class ParamRestController<T extends BaseModelVO> {
private JsonResult jsonResult = JsonResult.instance();
/*
* Belum selesai, baru di parameter includes. Untuk field object juga belom.
* example :
* http://localhost:8080/jasamedika-web/{typeVOClass}/list-using-param
* ?includes =id,nama
*/
@RequestMapping(value = "/list-using-param", method = RequestMethod.GET)
public ResponseEntity<List<T>> listUsingParam(
@RequestParam(value = "includes", required = false) String includes,
private final JsonResult jsonResult = JsonResult.instance();
@RequestMapping(value = "/list-using-param", method = GET)
public ResponseEntity<List<T>> listUsingParam(@RequestParam(value = "includes", required = false) String includes,
@RequestParam(value = "excludes", required = false) String excludes) {
List<T> listVO = getAllVOFromService();
String[] arrExcludes = null;
String[] arrIncludes = null;
if (excludes != null)
arrExcludes = excludes.split(Constants.COMMA);
arrExcludes = excludes.split(COMMA);
if (includes != null)
arrIncludes = includes.split(Constants.COMMA);
arrIncludes = includes.split(COMMA);
if (arrExcludes != null && arrIncludes != null) {
listVO = jsonResult.use(
JsonView.with(listVO).onClass(
getClazz(),
Match.match().exclude(arrExcludes)
.include(arrIncludes))).returnValue();
JsonView.with(listVO).onClass(getClazz(), Match.match().exclude(arrExcludes).include(arrIncludes)))
.returnValue();
}
if (arrExcludes != null && arrIncludes == null) {
listVO = jsonResult.use(
JsonView.with(listVO).onClass(getClazz(),
Match.match().include("*").exclude(arrExcludes)))
listVO = jsonResult
.use(JsonView.with(listVO).onClass(getClazz(), Match.match().include("*").exclude(arrExcludes)))
.returnValue();
}
if (arrExcludes == null && arrIncludes != null) {
listVO = jsonResult.use(
JsonView.with(listVO).onClass(getClazz(),
Match.match().exclude("*").include(arrIncludes)))
listVO = jsonResult
.use(JsonView.with(listVO).onClass(getClazz(), Match.match().exclude("*").include(arrIncludes)))
.returnValue();
}
return RestUtil.getJsonResponse(listVO, HttpStatus.OK);
return RestUtil.getJsonResponse(listVO, OK);
}
@SuppressWarnings("unchecked")
protected Class<T> getClazz() {
return (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(),
ParamRestController.class);
return (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), ParamRestController.class);
}
/*
* method untuk mendapatkan all VO from service
* */
protected abstract List<T> getAllVOFromService();
}

View File

@ -1,184 +1,147 @@
package com.jasamedika.medifirst2000.filter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.jasamedika.medifirst2000.constants.Constants;
import static com.jasamedika.medifirst2000.constants.Constants.HttpHeader.KD_RUANGAN_A;
import static com.jasamedika.medifirst2000.constants.Constants.HttpHeader.KD_RUANGAN_T;
import static org.slf4j.LoggerFactory.getLogger;
/**
* CORSFilter class
*
* @author Roberto
* @author Roberto, Syamsu
*/
@Component
public class CORSFilter implements Filter {
// Start Syamsu
private static final Logger LOGGER = getLogger(CORSFilter.class);
public CORSFilter() {
LOGGER.info("CORSFilter JasaMedika Web init");
}
private static class RequestWrapper extends HttpServletRequestWrapper {
final String body;
public RequestWrapper(ServletRequest req) throws IOException {
super((HttpServletRequest) req);
HttpServletRequest request = (HttpServletRequest) req;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
reader = new BufferedReader(new InputStreamReader(inputStream));
String hasil;
while ( (hasil = reader.readLine()) != null) {
stringBuilder.append(hasil);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
String idRuanganTujuan = request.getHeader(Constants.HttpHeader.KD_RUANGAN_T) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN_T);
if ("".equals(idRuanganTujuan.trim())){
try{
JSONObject jObject = new JSONObject(body);
ExtractObjectJson(jObject, false);
}catch(Exception e){
}
}
}
public String getHeader(String key){
if (key.equals(Constants.HttpHeader.KD_RUANGAN_A)) {
if (autoIdTujuan.length() > 0){
return autoIdTujuan.toString();
}
StringBuilder stringBuilder = getStringBuilder(request);
body = stringBuilder.toString();
String idRuanganTujuan = request.getHeader(KD_RUANGAN_T) == null ? "" : request.getHeader(KD_RUANGAN_T);
if (idRuanganTujuan.trim().isEmpty()) {
JSONObject jObject;
try {
jObject = new JSONObject(body);
} catch (JSONException e) {
throw new RuntimeException(e);
}
try {
ExtractObjectJson(jObject, false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String getHeader(String key) {
if (key.equals(KD_RUANGAN_A)) {
if (autoIdTujuan.length() > 0) {
return autoIdTujuan.toString();
}
}
return super.getHeader(key);
}
JSONArray autoIdTujuan = new JSONArray();
void ExtractObjectJson(JSONObject jObject, boolean ruangan) throws Exception{
Iterator iterator = jObject.keys();
while (iterator.hasNext()){
String key = String.valueOf(iterator.next());
Object o = jObject.get(key);
if (key.toLowerCase().contains("ruangan")){
if (o instanceof Integer){
autoIdTujuan.put(o);
} else if (o instanceof JSONObject){
ExtractObjectJson((JSONObject) o, true);
}
} else if (ruangan && "id".equals(key)){
if (o instanceof Integer){
autoIdTujuan.put(o);
return;
}
} else if (o instanceof JSONObject && !ruangan) {
ExtractObjectJson((JSONObject) o, false);
}
}
void ExtractObjectJson(JSONObject jObject, boolean ruangan) throws Exception {
Iterator<?> iterator = jObject.keys();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
Object o = jObject.get(key);
if (key.toLowerCase().contains("ruangan")) {
if (o instanceof Integer) {
autoIdTujuan.put(o);
} else if (o instanceof JSONObject) {
ExtractObjectJson((JSONObject) o, true);
}
} else if (ruangan && "id".equals(key)) {
if (o instanceof Integer) {
autoIdTujuan.put(o);
return;
}
} else if (o instanceof JSONObject && !ruangan) {
ExtractObjectJson((JSONObject) o, false);
}
}
}
@Override
public ServletInputStream getInputStream() throws IOException {
public ServletInputStream getInputStream() {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return new ServletInputStream() {
public int read() {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
@Override
public BufferedReader getReader() throws IOException {
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
public String getBody() {
return this.body;
}
}
// End Syamsu
private final Logger log = LoggerFactory.getLogger(CORSFilter.class);
public CORSFilter() {
log.info("CORSFilter JasaMedika Web init");
private static StringBuilder getStringBuilder(HttpServletRequest request) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
reader = new BufferedReader(new InputStreamReader(inputStream));
String hasil;
while ((hasil = reader.readLine()) != null) {
stringBuilder.append(hasil);
}
}
} finally {
if (reader != null)
reader.close();
}
return stringBuilder;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// Start Syamsu
RequestWrapper myReq = new RequestWrapper((HttpServletRequest) req);
// End Syamsu
HttpServletRequest request = (HttpServletRequest) myReq;
RequestWrapper myReq = new RequestWrapper(req);
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Origin", myReq.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Content-Type, Accept, X-Requested-With, remember-me, X-AUTH-TOKEN, "
+ "Supervising, RequestSupervisor, Module, Form, Action, AlamatUrlForm, KdRuangan, KdUser, "
+ "MandatoriData, idRuanganTujuan, ruanganTujuan");
response.setHeader("Content-Type", "application/json;application/octet-stream");
// String body = myReq.getBody();
// if (!"".equals(body.trim())){
// log.info("\n\n" + myReq.getBody() + "\n");
// }
response.setHeader("Content-Type", "application/json");
chain.doFilter(myReq, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override

View File

@ -1,8 +1,11 @@
package com.jasamedika.medifirst2000.filter;
import com.fasterxml.jackson.core.JsonParseException;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import io.jsonwebtoken.MalformedJwtException;
import java.io.IOException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
@ -10,14 +13,9 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import com.fasterxml.jackson.core.JsonParseException;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
/**
* StatelessAuthenticationFilter class
@ -25,43 +23,37 @@ import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
* @author Roberto
*/
public class StatelessAuthenticationFilter extends GenericFilterBean {
private final TokenAuthenticationService authenticationService;
public StatelessAuthenticationFilter(
TokenAuthenticationService authenticationService) {
public StatelessAuthenticationFilter(TokenAuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin",
req.getHeader("Origin"));
res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods",
"POST, GET, OPTIONS, DELETE");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers",
"Content-Type, Accept, X-Requested-With, remember-me, X-AUTH-TOKEN, Supervising, "
+ "RequestSupervisor, Module, Form, Action, AlamatUrlForm, KdRuangan, KdUser, "
+ "MandatoriData");
+ "RequestSupervisor, Module, Form, Action, AlamatUrlForm, KdRuangan, KdUser, "
+ "MandatoriData");
Authentication authentication = null;
try {
authentication = authenticationService.getAuthentication(httpRequest);
} catch (JsonParseException | MalformedJwtException e) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.addHeader(Constants.MessageInfo.ERROR_MESSAGE,
"Error Token (Not Valid Token)");
httpResponse.addHeader(ERROR_MESSAGE, "Error Token (Not Valid Token)");
filterChain.doFilter(request, response);
}
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
SecurityContextHolder.getContext().setAuthentication(null);
}
}

View File

@ -1,15 +1,11 @@
package com.jasamedika.medifirst2000.handler;
import java.util.List;
import java.util.Locale;
import com.jasamedika.medifirst2000.base.vo.validation.ValidationErrorVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
@ -18,22 +14,25 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.jasamedika.medifirst2000.base.vo.validation.ValidationErrorVO;
import com.jasamedika.medifirst2000.constants.Constants;;
import java.util.List;
import java.util.Locale;
import static com.jasamedika.medifirst2000.constants.Constants.Locale.INA;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
/**
* Exception Handler Rest Controller class
*
* @author Roberto
*/
@ControllerAdvice
@Order(1) // Pertama masuk
@Order(1)
public class RestErrorHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RestErrorHandler.class);
private static final Logger LOGGER = getLogger(RestErrorHandler.class);
private MessageSource messageSource;
private final MessageSource messageSource;
@Autowired
public RestErrorHandler(MessageSource validationNessageSource) {
@ -41,60 +40,42 @@ public class RestErrorHandler {
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseStatus(BAD_REQUEST)
@ResponseBody
public ValidationErrorVO processValidationError(MethodArgumentNotValidException ex) {
LOGGER.warn("Handling data validation error");
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
return processFieldErrors(fieldErrors);
}
private ValidationErrorVO processFieldErrors(List<FieldError> fieldErrors) {
ValidationErrorVO dto = new ValidationErrorVO();
for (FieldError fieldError : fieldErrors) {
dto.addFieldError(fieldError.getField(), fieldError.getDefaultMessage());
String localizedErrorMessage = resolveIndonesianErrorMessage(fieldError);
dto.addFieldError(fieldError.getField(), localizedErrorMessage);
}
return dto;
}
/*
* resolve error message with parameter locale
*/
private String resolveLocalizedErrorMessage(FieldError fieldError, String locale) {
private String resolveCurrentLocalErrorMessage(FieldError fieldError) {
Locale currentLocale = LocaleContextHolder.getLocale();
String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale);
// If the message was not found, return the most accurate field error
// code instead.
// You can remove this check if you prefer to get the default error
// message.
if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0];
}
return localizedErrorMessage;
}
/*
* resolve error message with default locale
*/
private String resolveLocalizedErrorMessage(FieldError fieldError) {
String localizedErrorMessage = messageSource.getMessage(fieldError, new Locale(Constants.Locale.INA));
// If the message was not found, return the most accurate field error
// code instead.
// You can remove this check if you prefer to get the default error
// message.
private String resolveIndonesianErrorMessage(FieldError fieldError) {
String localizedErrorMessage = messageSource.getMessage(fieldError, new Locale(INA));
if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0];
}
return localizedErrorMessage;
}
}

View File

@ -1,6 +1,5 @@
package com.jasamedika.medifirst2000.interceptor;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.dao.LoginUserDao;
import com.jasamedika.medifirst2000.dao.RuanganDao;
import com.jasamedika.medifirst2000.entities.*;
@ -8,7 +7,6 @@ import com.jasamedika.medifirst2000.notification.MessagePublisher;
import com.jasamedika.medifirst2000.security.model.AppPermission;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.service.*;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.vo.NotifMessagingSchedulerVO;
import com.jasamedika.medifirst2000.vo.NotifMessagingVO;
import com.jasamedika.medifirst2000.vo.NotifikasiMessageObjekModulVO;
@ -29,6 +27,13 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.jasamedika.medifirst2000.constants.Constants.HttpHeader.*;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.INFO_MESSAGE;
import static com.jasamedika.medifirst2000.util.CommonUtil.isNotNullOrEmpty;
import static com.jasamedika.medifirst2000.util.CommonUtil.isNullOrEmpty;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Interceptor class for All annotation method controller @AppPermission
*
@ -80,7 +85,7 @@ public class AppInterceptor implements HandlerInterceptor {
String namaUser;
private boolean contains(String source, String[] matchers) {
if (CommonUtil.isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers))
if (isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers))
return false;
for (String matcher : matchers)
if (source.contains(matcher))
@ -100,10 +105,10 @@ public class AppInterceptor implements HandlerInterceptor {
Authentication authentication = tokenAuthenticationService.getAuthentication(request);
namaUser = authentication.getName();
loginUser = loginUserDao.findByNamaUser(namaUser);
if (CommonUtil.isNullOrEmpty(loginUser)) {
if (isNullOrEmpty(loginUser)) {
response.setHeader("RequireSupervisor", "false");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Empty login user");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setHeader(ERROR_MESSAGE, "Empty login user");
response.setStatus(SC_FORBIDDEN);
return false;
}
return true;
@ -173,19 +178,19 @@ public class AppInterceptor implements HandlerInterceptor {
int action) throws Exception {
List<ObjekModulAplikasiVO> objekModulAplikasi = objekModulAplikasiService
.findByAlamatUrlForm(filterUrlForm(AlamatUrlForm));
if (CommonUtil.isNullOrEmpty(objekModulAplikasi))
if (isNullOrEmpty(objekModulAplikasi))
return true;
if (!checkAuthSecure(request, response))
return false;
int resultUser = checkUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action);
if (resultUser == 0) {
response.setHeader("RequireSupervisor", "true");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader(ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(SC_UNAUTHORIZED);
return false;
} else if (resultUser == 1) {
response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success");
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader(INFO_MESSAGE, "Supervise execution success");
response.setStatus(SC_OK);
return true;
}
int resultKelompokUser = checkKelompokUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action);
@ -195,12 +200,12 @@ public class AppInterceptor implements HandlerInterceptor {
return true;
} else if (resultKelompokUser == 0) {
response.setHeader("RequireSupervisor", "true");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader(ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(SC_UNAUTHORIZED);
return false;
} else {
response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success");
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader(INFO_MESSAGE, "Supervise execution success");
response.setStatus(SC_OK);
return true;
}
}
@ -209,16 +214,14 @@ public class AppInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
HandlerMethod hm;
Method method;
response.setHeader("Access-Control-Expose-Headers", "RequireSupervisor" + ","
+ Constants.MessageInfo.ERROR_MESSAGE + "," + Constants.MessageInfo.INFO_MESSAGE);
String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? ""
: request.getHeader(Constants.HttpHeader.URL_FORM);
String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN);
response.setHeader("Access-Control-Expose-Headers",
"RequireSupervisor" + "," + ERROR_MESSAGE + "," + INFO_MESSAGE);
String AlamatUrlForm = request.getHeader(URL_FORM) == null ? "" : request.getHeader(URL_FORM);
String KdRuangan = request.getHeader(KD_RUANGAN) == null ? "" : request.getHeader(KD_RUANGAN);
int action = AppPermission.VIEW;
if (CommonUtil.isNullOrEmpty(AlamatUrlForm))
if (isNullOrEmpty(AlamatUrlForm))
return true;
if (CommonUtil.isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan))
if (isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan))
return true;
String URI = request.getRequestURI();
String methodHttp = request.getMethod();
@ -264,9 +267,9 @@ public class AppInterceptor implements HandlerInterceptor {
return checkPermission(request, response, AlamatUrlForm, action);
}
} catch (Exception e) {
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Something wrong happened");
response.setHeader(ERROR_MESSAGE, "Something wrong happened");
response.setHeader("RequireSupervisor", "false");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setStatus(SC_INTERNAL_SERVER_ERROR);
return false;
}
return true;
@ -279,46 +282,41 @@ public class AppInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex)
throws Exception {
String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? ""
: request.getHeader(Constants.HttpHeader.URL_FORM);
String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN);
String idRuanganTujuan = request.getHeader(Constants.HttpHeader.KD_RUANGAN_T) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN_T);
String idRuanganTujuanA = request.getHeader(Constants.HttpHeader.KD_RUANGAN_A) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN_A);
String tglKirim = request.getHeader(Constants.HttpHeader.TGL_KIRIM) == null ? ""
: request.getHeader(Constants.HttpHeader.TGL_KIRIM);
boolean notHttpOK = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
boolean notLewatMenu = CommonUtil.isNullOrEmpty(AlamatUrlForm) || CommonUtil.isNullOrEmpty(KdRuangan);
String AlamatUrlForm = request.getHeader(URL_FORM) == null ? "" : request.getHeader(URL_FORM);
String KdRuangan = request.getHeader(KD_RUANGAN) == null ? "" : request.getHeader(KD_RUANGAN);
String idRuanganTujuan = request.getHeader(KD_RUANGAN_T) == null ? "" : request.getHeader(KD_RUANGAN_T);
String idRuanganTujuanA = request.getHeader(KD_RUANGAN_A) == null ? "" : request.getHeader(KD_RUANGAN_A);
String tglKirim = request.getHeader(TGL_KIRIM) == null ? "" : request.getHeader(TGL_KIRIM);
boolean notHttpOK = response.getStatus() >= SC_BAD_REQUEST;
boolean notLewatMenu = isNullOrEmpty(AlamatUrlForm) || isNullOrEmpty(KdRuangan);
Integer ruanganAsalId;
try {
ruanganAsalId = Integer.parseInt(KdRuangan);
} catch (NumberFormatException e) {
ruanganAsalId = 0;
}
boolean adaError = CommonUtil.isNotNullOrEmpty(ex);
boolean adaError = isNotNullOrEmpty(ex);
if (notHttpOK || notLewatMenu || adaError)
return;
Authentication authentication = tokenAuthenticationService.getAuthentication(request);
if (CommonUtil.isNullOrEmpty(authentication))
if (isNullOrEmpty(authentication))
return;
namaUser = authentication.getName();
loginUser = loginUserDao.findByNamaUser(namaUser);
if (CommonUtil.isNullOrEmpty(loginUser))
if (isNullOrEmpty(loginUser))
return;
String potongan = filterUrlForm(AlamatUrlForm);
List<ObjekModulAplikasiVO> objekModulAplikasiVOs = objekModulAplikasiService.findByAlamatUrlForm(potongan);
if (CommonUtil.isNullOrEmpty(objekModulAplikasiVOs))
if (isNullOrEmpty(objekModulAplikasiVOs))
return;
String URI = request.getRequestURI();
Integer objekModulAplikasId = objekModulAplikasiVOs.get(0).getId();
List<NotifMessagingVO> notifMessagingVOs = notifMessagingService
.findByObjekModulAplikasiIdAndUrlBackEndOrUrlBackEndIsNull(objekModulAplikasId, URI);
if (CommonUtil.isNullOrEmpty(notifMessagingVOs))
if (isNullOrEmpty(notifMessagingVOs))
return;
Integer notifMessagingId = notifMessagingVOs.get(0).getId();
if (CommonUtil.isNullOrEmpty(tglKirim)) {
if (isNullOrEmpty(tglKirim)) {
List<Integer> ruanganTujuansId = new ArrayList<>();
if (!"".equals(idRuanganTujuan)) {
JSONArray ruanganTujuanIds = new JSONArray(idRuanganTujuan);
@ -364,4 +362,5 @@ public class AppInterceptor implements HandlerInterceptor {
}
}
}
}

View File

@ -1,43 +1,38 @@
package com.jasamedika.medifirst2000.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.jasamedika.medifirst2000.constants.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static org.apache.commons.httpclient.HttpStatus.SC_FORBIDDEN;
import static org.slf4j.LoggerFactory.getLogger;
/**
* RestAuthenticationEntryPoint class
* set Unauthorized response from "Unauthorized client"
* RestAuthenticationEntryPoint class set Unauthorized response from
* "Unauthorized client"
*
* @author Roberto
* @author Roberto, Syamsu
*/
@Component("RestAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
/// Alter Syamsu
private static final Logger LOGGER = getLogger(RestAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response, AuthenticationException ae)
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae)
throws IOException, ServletException {
LOGGER.error("Mencoba akses tanpa login");
response.getWriter().write("{" + Constants.MessageInfo.ERROR_MESSAGE + ":'Please login to get access'}");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Please login to get access");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
response.getWriter().write("{" + ERROR_MESSAGE + ":'Please login to get access'}");
response.setHeader(ERROR_MESSAGE, "Please login to get access");
response.setStatus(SC_FORBIDDEN);
}
}

View File

@ -1,10 +1,12 @@
package com.jasamedika.medifirst2000.security;
import com.jasamedika.medifirst2000.filter.StatelessAuthenticationFilter;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@ -13,14 +15,11 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.filter.StatelessAuthenticationFilter;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.security.service.UserService;
import static com.jasamedika.medifirst2000.constants.Constants.JASAMEDIKA;
/**
* SpringSecurityConfig class
* Di sini Kita tidak menggunakan XML Config untuk Spring Security
* SpringSecurityConfig class Di sini Kita tidak menggunakan XML Config untuk
* Spring Security
*
* @author Roberto
*/
@ -29,94 +28,35 @@ import com.jasamedika.medifirst2000.security.service.UserService;
@Order(2)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
@Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
private final UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
public SpringSecurityConfig() {
super(true);
this.userService = new UserService();
tokenAuthenticationService = new TokenAuthenticationService(
Constants.JASAMEDIKA, userService);
tokenAuthenticationService = new TokenAuthenticationService(JASAMEDIKA, userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
//restAuthenticationEntryPoint
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.anonymous()
.and()
.servletApi()
.and()
.headers()
.cacheControl()
.and()
.authorizeRequests()
// Allow anonymous resource requests
.antMatchers("/favicon.ico")
.permitAll()
.antMatchers("**/*.html")
.permitAll()
.antMatchers("**/*.css")
.permitAll()
.antMatchers("**/*.js")
.permitAll()
// Allow anonymous logins
.antMatchers("/auth/**")
.permitAll()
// Allow SMS gateway
.antMatchers("/registrasi-pasien-sms/**")
.permitAll()
// Allow SMS gateway
.antMatchers("/report/**")
.permitAll()
// URL tanpa auth deklarasikan di sini
.antMatchers("/test-tanpa-auth/**")
.permitAll()
.antMatchers("/test/**")
.permitAll()
.antMatchers("/api-docs.json")
.permitAll()
.antMatchers("/api-docs/**")
.permitAll()
/*//Allow Download File Surat Masuk
.antMatchers("/surat-masuk/download-dokumen-template/**")
.permitAll()
.antMatchers("/surat-masuk/get-draft-surat/**")
.permitAll()*/
// All other request need to be authenticated
.anyRequest()
.authenticated()
.and()
// Custom Token based authentication based on the header
// previously given to the client
.addFilterBefore(
new StatelessAuthenticationFilter(
tokenAuthenticationService),
http.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint).and().anonymous().and()
.servletApi().and().headers().cacheControl().and().authorizeRequests().antMatchers("/favicon.ico")
.permitAll().antMatchers("**/*.html").permitAll().antMatchers("**/*.css").permitAll()
.antMatchers("**/*.js").permitAll().antMatchers("/auth/**").permitAll()
.antMatchers("/registrasi-pasien-sms/**").permitAll().antMatchers("/report/**").permitAll()
.antMatchers("/test-tanpa-auth/**").permitAll().antMatchers("/test/**").permitAll()
.antMatchers("/api-docs.json").permitAll().antMatchers("/api-docs/**").permitAll().anyRequest()
.authenticated().and().addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(
new BCryptPasswordEncoder());
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
@ -135,11 +75,5 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
public TokenAuthenticationService tokenAuthenticationService() {
return tokenAuthenticationService;
}
// @Bean(name = "springSecurityFilterChain", autowire = Autowire.BY_NAME)
// public DelegatingFilterProxy springSecurityFilterChain(){
// return new DelegatingFilterProxy();
// }
}

View File

@ -1,40 +1,35 @@
package com.jasamedika.medifirst2000.security.handler;
import com.jasamedika.medifirst2000.security.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.User;
import com.jasamedika.medifirst2000.security.service.UserService;
import static io.jsonwebtoken.SignatureAlgorithm.HS512;
/**
* TokenHandler class
* using jjwt https://github.com/jwtk/jjwt
*
* TokenHandler class using jjwt <a href="https://github.com/jwtk/jjwt">jjwt</a>
*
* @author Roberto
*/
public class TokenHandler {
private final String secret;
private final UserService userService;
public TokenHandler(String secret, UserService userService) {
this.secret = secret;
this.userService = userService;
}
private final String secret;
public User parseUserFromToken(String token) {
String username = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
return userService.loadUserByUsername(username);
}
private final UserService userService;
public TokenHandler(String secret, UserService userService) {
this.secret = secret;
this.userService = userService;
}
public User parseUserFromToken(String token) {
String username = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
return userService.loadUserByUsername(username);
}
public String createTokenForUser(User user) {
return Jwts.builder().setHeaderParam("typ", "JWT").setSubject(user.getUsername()).signWith(HS512, secret)
.compact();
}
public String createTokenForUser(User user) {
return Jwts.builder().setHeaderParam("typ", "JWT")
.setSubject(user.getUsername())
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
}

View File

@ -6,20 +6,21 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* AppPermission annotation, digunakan untuk method yang butuh authorized dari database
* can use in method only.
* AppPermission annotation, digunakan untuk method yang butuh authorized dari
* database can use in method only.
*
* @author Roberto
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AppPermission {
public static final int ADD = 100;
public static final int UPDATE = 200;
public static final int DELETE = 300;
public static final int PRINT = 400;
public static final int VIEW = 500;
public static final int SPECIALS = 600;
public @interface AppPermission {
int ADD = 100;
int UPDATE = 200;
int DELETE = 300;
int PRINT = 400;
int VIEW = 500;
int SPECIALS = 600;
int value();
}

View File

@ -1,22 +1,22 @@
package com.jasamedika.medifirst2000.security.model;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
/**
* UserAuthentication class
*
* @author Roberto
*/
public class UserAuthentication implements Authentication {
/**
* serialVersionUID
*/
private static final long serialVersionUID = -7410905698525654537L;
private final User user;
private boolean authenticated = true;
public UserAuthentication(User user) {
@ -57,4 +57,5 @@ public class UserAuthentication implements Authentication {
public void setAuthenticated(boolean authenticated) {
this.authenticated = authenticated;
}
}

View File

@ -1,72 +1,59 @@
package com.jasamedika.medifirst2000.security.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonParseException;
import com.jasamedika.medifirst2000.security.handler.TokenHandler;
import com.jasamedika.medifirst2000.security.model.UserAuthentication;
import lombok.NoArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonParseException;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.security.handler.TokenHandler;
import com.jasamedika.medifirst2000.security.model.UserAuthentication;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import static com.jasamedika.medifirst2000.core.web.WebConstants.AUTH_HEADER_NAME;
/**
* TokenAuthenticationService class
*
* @author Roberto
*/
@NoArgsConstructor
@Component
public class TokenAuthenticationService {
public static TokenHandler tokenHandler;
public TokenAuthenticationService() {
}
public static TokenHandler tokenHandler;
public TokenAuthenticationService(String secret, UserService userService) {
tokenHandler = new TokenHandler(secret, userService);
}
public String addAuthentication(HttpServletResponse response,
UserAuthentication authentication) {
public String addAuthentication(UserAuthentication authentication) {
final User user = authentication.getDetails();
return tokenHandler.createTokenForUser(user);
return tokenHandler.createTokenForUser(user);
}
public Authentication getAuthentication(HttpServletRequest request)
throws JsonParseException {
String token = request.getHeader(WebConstants.AUTH_HEADER_NAME);
public Authentication getAuthentication(HttpServletRequest request) throws JsonParseException {
String token = request.getHeader(AUTH_HEADER_NAME);
if (token != null) {
final User user = tokenHandler.parseUserFromToken(token);
if (user != null) {
if (user != null)
return new UserAuthentication(user);
}
}
else{
try
{
if(request.getQueryString()=="")return null;
final String[] tokens= request.getQueryString().split("&");
for (String tokenTemp : tokens) {
if(tokenTemp.toLowerCase().indexOf(WebConstants.AUTH_HEADER_NAME.toLowerCase())>=0)
{
token =tokenTemp.split("=")[1];
final User user = tokenHandler.parseUserFromToken(token);
if (user != null) {
return new UserAuthentication(user);
}
} else {
if (Objects.equals(request.getQueryString(), ""))
return null;
final String[] tokens = request.getQueryString().split("&");
for (String tokenTemp : tokens) {
if (tokenTemp.toLowerCase().contains(AUTH_HEADER_NAME.toLowerCase())) {
token = tokenTemp.split("=")[1];
final User user = tokenHandler.parseUserFromToken(token);
if (user != null) {
return new UserAuthentication(user);
}
}
}
catch(Exception e)
{
}
}
return null;
}
}

View File

@ -1,29 +1,28 @@
package com.jasamedika.medifirst2000.security.service;
import java.util.Arrays;
import java.util.List;
import com.jasamedika.medifirst2000.dao.LoginUserDao;
import com.jasamedika.medifirst2000.entities.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.jasamedika.medifirst2000.dao.LoginUserDao;
import com.jasamedika.medifirst2000.entities.LoginUser;
import java.util.List;
import static java.util.Collections.singletonList;
/**
* UserService implements
org.springframework.security.core.userdetails.UserDetailsService
* org.springframework.security.core.userdetails.UserDetailsService
*
* @author Roberto
*/
@Component
public class UserService implements
org.springframework.security.core.userdetails.UserDetailsService {
public class UserService implements UserDetailsService {
@Autowired
private LoginUserDao loginUserDao;
@ -34,28 +33,16 @@ public class UserService implements
super();
}
/**
* this method is called for rest authentication from client
*
* @author Roberto
*/
@Override
public final User loadUserByUsername(String username)
throws UsernameNotFoundException {
public final User loadUserByUsername(String username) throws UsernameNotFoundException {
List<LoginUser> loginUsers = loginUserDao.findByNamaUser(username);
if (loginUsers.isEmpty()) {
if (loginUsers.isEmpty())
throw new UsernameNotFoundException("user not found");
}
LoginUser loginUser = loginUsers.get(0);
//validasi tambahan lakukan di sini
// GrantedAuthority authority = new SimpleGrantedAuthority(loginUser
// .getKelompokUser().getKelompokUser());
GrantedAuthority authority = new SimpleGrantedAuthority("USER");
UserDetails userDetails = (UserDetails) new User(
loginUser.getNamaUser(), loginUser.getKataSandi(),
Arrays.asList(authority));
User userDetails = new User(loginUser.getNamaUser(), loginUser.getKataSandi(), singletonList(authority));
detailsChecker.check(userDetails);
return (User) userDetails;
return userDetails;
}
}

View File

@ -1,6 +1,7 @@
package com.jasamedika.medifirst2000.task.schedule;
import com.jasamedika.medifirst2000.dao.*;
import com.jasamedika.medifirst2000.dao.PelayananPasienPetugasDao;
import com.jasamedika.medifirst2000.dao.RekapLogbookDokterDao;
import com.jasamedika.medifirst2000.entities.KelompokPasien;
import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.entities.RekapLogbookDokter;
@ -10,7 +11,6 @@ import com.jasamedika.medifirst2000.service.RekapLogbookDokterService;
import com.jasamedika.medifirst2000.service.RemunerasiService;
import com.jasamedika.medifirst2000.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@ -23,6 +23,8 @@ import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import static org.slf4j.LoggerFactory.getLogger;
/**
* @author salmanoe
* @version 1.0.0
@ -30,7 +32,8 @@ import java.util.*;
*/
@Component
public class LogbookTask {
private static final Logger LOGGER = LoggerFactory.getLogger(LogbookTask.class);
private static final Logger LOGGER = getLogger(LogbookTask.class);
@Autowired
private PelayananPasienPetugasDao pelayananPasienPetugasDao;
@ -59,8 +62,10 @@ public class LogbookTask {
Date tglAwal = DateUtil.startMonth(date);
Date tglAkhir = DateUtil.endMonth(date);
{
// Delete untuk pembaharuan data
rekapLogbookDokterService.deleteByPeriod(tglAwal, tglAkhir);
rekapLogbookDokterService.deleteByPeriod(tglAwal, tglAkhir); // Delete
// untuk
// pembaharuan
// data
}
Set<Integer> idPegawaiByTglPelayanan = pelayananPasienPetugasDao.findPegawaiByTglPelayanan(tglAwal, tglAkhir);
DateFormat df = new SimpleDateFormat("yyyy-MM");

View File

@ -6,7 +6,6 @@ import com.jasamedika.medifirst2000.dto.PesertaBpjsDto;
import com.jasamedika.medifirst2000.entities.Pasien;
import com.jasamedika.medifirst2000.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
@ -20,6 +19,7 @@ import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
@ -31,7 +31,7 @@ import static org.springframework.http.HttpStatus.OK;
*/
@Component
public class PasienTask {
private static final Logger LOGGER = LoggerFactory.getLogger(PasienTask.class);
private static final Logger LOGGER = getLogger(PasienTask.class);
@Autowired
private ObjectMapper objectMapper;

View File

@ -1,29 +1,25 @@
package com.jasamedika.medifirst2000.util.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
@NoArgsConstructor
@Component
public class JacksonConfiguration {
private ObjectMapper mapper;
public JacksonConfiguration() {
}
public JacksonConfiguration(ObjectMapper mapper) {
this.mapper = mapper;
configureJackson(mapper);
}
public static ObjectMapper configureJackson(ObjectMapper mapper) {
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
return mapper;
public static void configureJackson(ObjectMapper mapper) {
mapper.enable(INDENT_OUTPUT);
mapper.setSerializationInclusion(NON_NULL);
mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
}
}

View File

@ -1,16 +1,17 @@
package com.jasamedika.medifirst2000.util.rest;
import com.google.gson.Gson;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import com.google.gson.Gson;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
/**
* Rest Util Class
@ -23,197 +24,133 @@ public class RestUtil {
/**
* get JSON response from Object
*
* @param src
*
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<T> getJsonResponse(T src) {
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<T>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get JSON response from Object with HTTP status
*
* @param src
* @param status
*
* @param <T>
* source class
* @return @ResponseEntity
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> ResponseEntity<T> getJsonResponse(T src, HttpStatus status) {
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
Map<String, Object> map = new HashMap<String, Object>();
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
Map<String, Object> map = new HashMap<>();
map.put("data", src);
return new ResponseEntity(map, headers, status);
}
/**
*
* @param src
* @param status
* @param mapHeaderMessage
* @param <T>
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> ResponseEntity<T> getJsonResponse(T src, HttpStatus status,
Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
if (null != mapHeaderMessage) {
for (String key : mapHeaderMessage.keySet()) {
if (null != mapHeaderMessage)
for (String key : mapHeaderMessage.keySet())
headers.add(key, mapHeaderMessage.get(key));
}
}
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> map = new HashMap<>();
map.put("messages", mapHeaderMessage);
map.put("data", src);
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity(map, headers, status);
}
/**
*
* @param status
* @param mapHeaderMessage
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> ResponseEntity<T> getJsonResponse(HttpStatus status, Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
Map<String, Object> map = new HashMap<String, Object>();
map.put("messages", mapHeaderMessage);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity(map, headers, status);
}
/**
* get JSON response from HTTP status only
*
*
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<T> getJsonHttptatus(HttpStatus status) {
return new ResponseEntity<T>(status);
public static <T> ResponseEntity<T> getJsonHttpStatus(HttpStatus status) {
return new ResponseEntity<>(status);
}
public static <T> ResponseEntity<T> getJsonHttptatus(HttpStatus status, Map<String, String> mapHeaderMessage) {
public static <T> ResponseEntity<T> getJsonHttpStatus(HttpStatus status, Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
if (null != mapHeaderMessage) {
for (String key : mapHeaderMessage.keySet()) {
if (null != mapHeaderMessage)
for (String key : mapHeaderMessage.keySet())
headers.add(key, mapHeaderMessage.get(key));
}
}
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<T>(headers, status);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(headers, status);
}
/**
* get JSON response from Set Object
*
* @param src
*
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<Set<T>> defaultJsonResponse(Set<T> src) {
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<Set<T>>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get JSON response from Set Object with custom header
*
* @param src
* @param mapHeaderMessage
*
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<Set<T>> defaultJsonResponse(Set<T> src, Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
if (null != mapHeaderMessage) {
for (String key : mapHeaderMessage.keySet()) {
if (null != mapHeaderMessage)
for (String key : mapHeaderMessage.keySet())
headers.add(key, mapHeaderMessage.get(key));
}
}
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<Set<T>>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get JSON response from List Object with custom header
*
* @param src
* @param mapHeaderMessage
*
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<List<T>> defaultJsonResponse(List<T> src, Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
if (null != mapHeaderMessage) {
for (String key : mapHeaderMessage.keySet()) {
if (null != mapHeaderMessage)
for (String key : mapHeaderMessage.keySet())
headers.add(key, mapHeaderMessage.get(key));
}
}
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<List<T>>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get JSON response from List Object
*
* @param src
*
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<List<T>> defaultJsonResponse(List<T> src) {
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<List<T>>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get default JSON response from Object
*
* @param src
*
* @return @ResponseEntity
*/
public static ResponseEntity<String> defaultJsonResponse(Object src) {
Gson gson = new Gson();
HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<String>(gson.toJson(src), headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(gson.toJson(src), headers, OK);
}
/**
@ -223,8 +160,6 @@ public class RestUtil {
* string source JSON
* @param type
* class type result
* @param <T>
* @return
*/
public static <T> T jsonToObject(String strJson, Class<T> type) {
Gson gson = new Gson();
@ -234,8 +169,6 @@ public class RestUtil {
/**
* convert object to json
*
* @param object
* @return
*/
public static String toJson(Object object) {
Gson gson = new Gson();

View File

@ -1,8 +1,10 @@
package com.monitorjbl.json;
public class JsonResult {
private static final JsonResult instance = new JsonResult();
private static final ThreadLocal<JsonView> current = new ThreadLocal<>();
private static final ThreadLocal<JsonView<?>> current = new ThreadLocal<>();
private JsonResult() {
}
@ -16,7 +18,6 @@ public class JsonResult {
* Type of object being rendered
* @return ResultWrapper to provide return value
*/
@SuppressWarnings("unchecked")
public <E> ResultWrapper<E> use(JsonView<E> view) {
current.set(view);
return new ResultWrapper<>(view);
@ -26,7 +27,7 @@ public class JsonResult {
return instance;
}
static JsonView get() {
static JsonView<?> get() {
return current.get();
}
@ -35,7 +36,7 @@ public class JsonResult {
}
public static class ResultWrapper<T> {
private JsonView<T> obj;
private final JsonView<T> obj;
private ResultWrapper(JsonView<T> obj) {
this.obj = obj;
@ -50,4 +51,5 @@ public class JsonResult {
return obj.getValue();
}
}
}

View File

@ -1,18 +1,15 @@
package com.monitorjbl.json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonResultRetriever {
private static final Logger log = LoggerFactory.getLogger(JsonResultRetriever.class);
static boolean hasValue() {
return JsonResult.get() != null;
}
static boolean hasValue() {
return JsonResult.get() != null;
}
static JsonView<?> retrieve() {
JsonView<?> val = JsonResult.get();
JsonResult.unset();
return val;
}
static JsonView retrieve() {
JsonView val = JsonResult.get();
JsonResult.unset();
return val;
}
}

View File

@ -11,23 +11,19 @@ import java.util.List;
public class JsonViewHttpEntityMethodProcessor extends HttpEntityMethodProcessor {
public JsonViewHttpEntityMethodProcessor(List<HttpMessageConverter<?>> converters) {
super(converters);
}
public JsonViewHttpEntityMethodProcessor(List<HttpMessageConverter<?>> converters) {
super(converters);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if(returnValue instanceof ResponseEntity && JsonResultRetriever.hasValue()) {
JsonView json = JsonResultRetriever.retrieve();
ResponseEntity re = (ResponseEntity) returnValue;
returnValue = ResponseEntity.status(re.getStatusCode())
.headers(re.getHeaders())
.body(json);
}
super.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
if (returnValue instanceof ResponseEntity && JsonResultRetriever.hasValue()) {
JsonView<?> json = JsonResultRetriever.retrieve();
ResponseEntity<?> re = (ResponseEntity<?>) returnValue;
returnValue = ResponseEntity.status(re.getStatusCode()).headers(re.getHeaders()).body(json);
}
super.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
}
}

View File

@ -10,26 +10,27 @@ import java.io.IOException;
public class JsonViewMessageConverter extends MappingJackson2HttpMessageConverter {
public JsonViewMessageConverter() {
super();
ObjectMapper defaultMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
defaultMapper.registerModule(module);
setObjectMapper(defaultMapper);
}
public JsonViewMessageConverter() {
super();
ObjectMapper defaultMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
defaultMapper.registerModule(module);
setObjectMapper(defaultMapper);
}
public JsonViewMessageConverter(ObjectMapper mapper) {
super();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
setObjectMapper(mapper);
}
public JsonViewMessageConverter(ObjectMapper mapper) {
super();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
setObjectMapper(mapper);
}
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
super.writeInternal(object, outputMessage);
}
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
super.writeInternal(object, outputMessage);
}
}

View File

@ -6,7 +6,9 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBody
import java.util.List;
public class JsonViewResponseProcessor extends RequestResponseBodyMethodProcessor {
public JsonViewResponseProcessor(List<HttpMessageConverter<?>> messageConverters) {
super(messageConverters);
}
public JsonViewResponseProcessor(List<HttpMessageConverter<?>> messageConverters) {
super(messageConverters);
}
}

View File

@ -11,30 +11,31 @@ import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.List;
public class JsonViewReturnValueHandler implements HandlerMethodReturnValueHandler {
private static final Logger log = LoggerFactory.getLogger(JsonViewReturnValueHandler.class);
private final HandlerMethodReturnValueHandler delegate;
private static final Logger LOGGER = LoggerFactory.getLogger(JsonViewReturnValueHandler.class);
public JsonViewReturnValueHandler(List<HttpMessageConverter<?>> converters) {
this.delegate = new JsonViewResponseProcessor(converters);
}
private final HandlerMethodReturnValueHandler delegate;
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return delegate.supportsReturnType(returnType);
}
public JsonViewReturnValueHandler(List<HttpMessageConverter<?>> converters) {
this.delegate = new JsonViewResponseProcessor(converters);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
Object val = returnValue;
if(JsonResultRetriever.hasValue()) {
val = JsonResultRetriever.retrieve();
log.debug("Found [" + ((JsonView) val).getValue().getClass() + "] to serialize");
} else {
log.debug("No JsonView found for thread, using returned value");
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return delegate.supportsReturnType(returnType);
}
delegate.handleReturnValue(val, returnType, mavContainer, webRequest);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
Object val = returnValue;
if (JsonResultRetriever.hasValue()) {
val = JsonResultRetriever.retrieve();
LOGGER.debug("Found [{}] to serialize", ((JsonView<?>) val).getValue().getClass());
} else {
LOGGER.debug("No JsonView found for thread, using returned value");
}
delegate.handleReturnValue(val, returnType, mavContainer, webRequest);
}
}

View File

@ -15,38 +15,39 @@ import java.util.List;
public class JsonViewSupportFactoryBean implements InitializingBean {
@Autowired
private RequestMappingHandlerAdapter adapter;
private final JsonViewMessageConverter converter;
@Autowired
private RequestMappingHandlerAdapter adapter;
public JsonViewSupportFactoryBean() {
this(new ObjectMapper());
}
private final JsonViewMessageConverter converter;
public JsonViewSupportFactoryBean(ObjectMapper mapper) {
this.converter = new JsonViewMessageConverter(mapper.copy());
}
public JsonViewSupportFactoryBean() {
this(new ObjectMapper());
}
@Override
public void afterPropertiesSet() throws Exception {
List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(adapter.getReturnValueHandlers());
adapter.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
decorateHandlers(handlers);
adapter.setReturnValueHandlers(handlers);
}
public JsonViewSupportFactoryBean(ObjectMapper mapper) {
this.converter = new JsonViewMessageConverter(mapper.copy());
}
private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
List<HttpMessageConverter<?>> converters = new ArrayList<>(adapter.getMessageConverters());
converters.add(converter);
for(HandlerMethodReturnValueHandler handler : handlers) {
int index = handlers.indexOf(handler);
if(handler instanceof HttpEntityMethodProcessor) {
handlers.set(index, new JsonViewHttpEntityMethodProcessor(converters));
} else if(handler instanceof RequestResponseBodyMethodProcessor) {
handlers.set(index, new JsonViewReturnValueHandler(converters));
break;
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(adapter.getReturnValueHandlers());
adapter.setMessageConverters(Collections.singletonList(converter));
decorateHandlers(handlers);
adapter.setReturnValueHandlers(handlers);
}
private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
List<HttpMessageConverter<?>> converters = new ArrayList<>(adapter.getMessageConverters());
converters.add(converter);
for (HandlerMethodReturnValueHandler handler : handlers) {
int index = handlers.indexOf(handler);
if (handler instanceof HttpEntityMethodProcessor) {
handlers.set(index, new JsonViewHttpEntityMethodProcessor(converters));
} else if (handler instanceof RequestResponseBodyMethodProcessor) {
handlers.set(index, new JsonViewReturnValueHandler(converters));
break;
}
}
}
}

View File

@ -19,12 +19,14 @@
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.data.web.PageableArgumentResolver" />
<bean class="net.kaczmarzyk.spring.data.jpa.web.SpecificationArgumentResolver"/>
<ref bean="customArgumentResolver" />
<bean
class="net.kaczmarzyk.spring.data.jpa.web.SpecificationArgumentResolver" />
<ref bean="customArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
<bean id="customArgumentResolver" class="net.kaczmarzyk.spring.data.jpa.web.SpecificationArgumentResolver"/>
<bean id="customArgumentResolver"
class="net.kaczmarzyk.spring.data.jpa.web.SpecificationArgumentResolver" />
<mvc:default-servlet-handler />
@ -38,23 +40,23 @@
class="com.jasamedika.medifirst2000.util.rest.JacksonConfiguration">
<constructor-arg ref="mapper" />
</bean>
<!-- <bean id="jsonViewSupport" class="com.monitorjbl.json.JsonViewSupportFactoryBean">
<constructor-arg ref="mapper" />
</bean> -->
<!-- <bean id="jsonViewSupport" class="com.monitorjbl.json.JsonViewSupportFactoryBean">
<constructor-arg ref="mapper" /> </bean> -->
<bean id="mapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean id="xmlMessageConverter"
<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean id="xmlMessageConverter"
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter"/>
<ref bean="xmlMessageConverter"/>
<ref bean="jsonMessageConverter" />
<ref bean="xmlMessageConverter" />
</list>
</property>
</bean>
@ -64,12 +66,13 @@
class="com.mangofactory.swagger.configuration.DocumentationConfig" />
<context:property-placeholder location="classpath:swagger.properties" />
<bean id="jasperViewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views"/>
<property name="order" value="0"/>
</bean>
<aop:aspectj-autoproxy />
</beans>
<bean id="jasperViewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
<property name="order" value="0" />
</bean>
<aop:aspectj-autoproxy />
</beans>

View File

@ -1,10 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-reporting</artifactId>
<packaging>war</packaging>
<name>jasamedika-reporting</name>
<parent>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jasamedika-reporting</artifactId>
<packaging>war</packaging>
<name>jasamedika-reporting</name>
<parent>
<groupId>com.jasamedika</groupId>
<artifactId>Medifirst2000</artifactId>
<version>1.0.0</version>
@ -12,12 +12,12 @@
</parent>
<dependencies>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jasamedika-config</artifactId>
@ -41,14 +41,14 @@
<artifactId>jasamedika-business</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
@ -68,7 +68,7 @@
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
@ -172,31 +172,31 @@
<artifactId>swagger-springmvc</artifactId>
<version>0.6.5</version>
</dependency>
<!-- jasper -->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/zxing-parent -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
<groupId>com.google.zxing</groupId>
<artifactId>zxing-parent</artifactId>
<version>3.2.0</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
@ -212,11 +212,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>4.0.0</version>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
@ -246,39 +246,36 @@
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.barbecue/barbecue -->
<dependency>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
<groupId>net.sourceforge.barbecue</groupId>
<artifactId>barbecue</artifactId>
<version>1.5-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-bridge -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-bridge</artifactId>
<version>1.7</version>
</dependency>
<!-- <dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<version>1.8.4</version> </dependency> -->
<dependency>
<groupId>commons-codec</groupId>
@ -290,10 +287,18 @@
<artifactId>commons-collections</artifactId>
<version>${commons-collections.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<build>
<finalName>jasamedika-reporting</finalName>
<plugins>
<plugin>
@ -313,7 +318,7 @@
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
<description>Module Medifirst2000 untuk Web / Controller. Tempat API diexpose oleh REST Client.</description>

View File

@ -9,70 +9,56 @@ import java.text.SimpleDateFormat;
* @author Roberto
*/
public class Constants {
public static final String JASAMEDIKA = "SkFTQU1FRElLQQ==";
public static final String APP_VERSION = "APP_VERSION";
public static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN";
//for example
public static final String IDR = "IDR";
public static final String RP = "RP";
public static final String COMMA = ",";
public static final DecimalFormat ONE_COMA_FORMAT = new DecimalFormat("#.#");
public static final DecimalFormat TWO_COMA_FORMAT = new DecimalFormat(
"#.##");
public static final DecimalFormat MONEY_FORMAT_WITHOUT_COMMA = new DecimalFormat(
"###,###");
public static final DecimalFormat TWO_COMA_FORMAT = new DecimalFormat("#.##");
public static final DecimalFormat MONEY_FORMAT_WITHOUT_COMMA = new DecimalFormat("###,###");
public static final class DateFormat {
public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat(
"yyyyMMdd");
public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat(
"dd MMM yyyy");
public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
public static final SimpleDateFormat yyyy_MM_dd_T_HH_mm_ss = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss");
public static final SimpleDateFormat yyyyMMdd_HH_mm_ss = new SimpleDateFormat(
"yyyyMMdd HH:mm:ss");
public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat("dd MMM yyyy");
public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final SimpleDateFormat yyyy_MM_dd_T_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public static final SimpleDateFormat yyyyMMdd_HH_mm_ss = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
}
/* message */
public static final class MessageInfo {
public static final String INFO_MESSAGE = "INFO_MESSAGE";
public static final String WARNING_MESSAGE = "WARNING_MESSAGE";
public static final String ERROR_MESSAGE = "ERROR_MESSAGE";
public static final String EXCEPTION_MESSAGE = "EXCEPTION_MESSAGE";
}
/* locale id (indonesia / default) and en (english) */
public static final class Locale {
public static final String INA = "ina";
public static final String EN = "en";
}
//Update perubahan di sini, harus disamakan dengan package yang ada di jasamedika-bussiness
//com.jasamedika.medifirst2000.logging.hibernate.async
public static final class HttpHeader {
public static final String SUPERVISING = "Supervising";
public static final String MODULE = "Module";
public static final String FORM = "Form";
public static final String ACTION = "Action";
public static final String URL_FORM = "AlamatUrlForm"; // syamsu
public static final String KD_RUANGAN = "KdRuangan"; // syamsu
public static final String KD_RUANGAN_T = "KdRuanganT"; // syamsu
public static final String KD_RUANGAN_A = "KdRuanganA"; // syamsu
public static final String TGL_KIRIM = "tglKirim"; // syamsu
// public static final String RUANGAN_TUJUAN = "ruanganTujuan"; // syamsu
// public static final String ID_RUANGAN_TUJUAN_ALT = "ruanganTujuanAlt"; // syamsu
public static final String KD_USER = "KdUser"; // syamsu
public static final String URL_FORM = "AlamatUrlForm";
public static final String KD_RUANGAN = "KdRuangan";
public static final String KD_RUANGAN_T = "KdRuanganT";
public static final String KD_RUANGAN_A = "KdRuanganA";
public static final String TGL_KIRIM = "tglKirim";
public static final String KD_USER = "KdUser";
}
}

View File

@ -7,9 +7,15 @@ package com.jasamedika.medifirst2000.constants;
* @author Roberto
*/
public final class MessageResource {
public static final String LABEL_SUCCESS = "label.success";
public static final String LABEL_ERROR = "label.error";
public static final String LABEL_TRY_AGAIN = "label.try_again";
public static final String LABEL_SUCCESS_CREATED = "label.success.created";
public static final String LABEL_SUCCESS_OK = "label.success.ok";
}

View File

@ -1,182 +1,199 @@
package com.jasamedika.medifirst2000.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PemeriksaanAngkaKumanUdaraService;
import com.jasamedika.medifirst2000.vo.PemeriksaanAngkaKumanUdaraVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PemeriksaanAngkaKumanUdaraService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.PemeriksaanAngkaKumanUdaraVO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
@RequestMapping("/pemeriksaan-angka-kuman-udara")
public class PemeriksaanAngkaKumanUdaraController extends LocaleController<PemeriksaanAngkaKumanUdaraVO>{
public class PemeriksaanAngkaKumanUdaraController extends LocaleController<PemeriksaanAngkaKumanUdaraVO> {
private static final Logger LOGGER = getLogger(PemeriksaanAngkaKumanUdaraController.class);
@Autowired
private PemeriksaanAngkaKumanUdaraService service;
private static final Logger LOGGER = LoggerFactory.getLogger(PemeriksaanAngkaKumanUdaraController.class);
@RequestMapping(value = "/get-unit-ruangan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-unit-ruangan", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getUnitRuangan(HttpServletRequest request) {
try {
Map<String,Object> result = service.getUnitRuangan();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getUnitRuangan();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getUnitRuangan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getUnitRuangan", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getUnitRuangan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getUnitRuangan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-baku-mutu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-baku-mutu", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getBakuMutu(HttpServletRequest request) {
try {
Map<String,Object> result = service.getBakuMutu();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getBakuMutu();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getBakuMutu", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getBakuMutu", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getBakuMutu", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getBakuMutu", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/save-pemeriksaan-angka-kuman-udara", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePemeriksaanAngkaKumanUdara(@Valid @RequestBody PemeriksaanAngkaKumanUdaraVO vo, HttpServletRequest request) {
try {
Map<String,Object> result = service.savePemeriksaanAngkaKumanUdara(vo);
if (null != result)
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage);
@RequestMapping(value = "/save-pemeriksaan-angka-kuman-udara", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePemeriksaanAngkaKumanUdara(
@Valid @RequestBody PemeriksaanAngkaKumanUdaraVO vo, HttpServletRequest request) {
try {
Map<String, Object> result = service.savePemeriksaanAngkaKumanUdara(vo);
if (null != result)
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePemeriksaanAngkaKumanUdara", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when savePemeriksaanAngkaKumanUdara", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePemeriksaanAngkaKumanUdara", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when savePemeriksaanAngkaKumanUdara", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-pemeriksaan-angka-kuman-udara", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-pemeriksaan-angka-kuman-udara", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getPemeriksaanAngkaKumanUdara(HttpServletRequest request) {
try {
Map<String,Object> result = service.getPemeriksaanAngkaKumanUdara();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getPemeriksaanAngkaKumanUdara();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getPemeriksaanAngkaKumanUdara", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getPemeriksaanAngkaKumanUdara", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getPemeriksaanAngkaKumanUdara", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getPemeriksaanAngkaKumanUdara", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/update-pemeriksaan-angka-kuman-udara", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> updatePemeriksaanAngkaKumanUdara(@Valid @RequestBody PemeriksaanAngkaKumanUdaraVO vo, HttpServletRequest request) {
@RequestMapping(value = "/update-pemeriksaan-angka-kuman-udara", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> updatePemeriksaanAngkaKumanUdara(@Valid @RequestBody PemeriksaanAngkaKumanUdaraVO vo,
HttpServletRequest request) {
try {
Boolean result = service.updatePemeriksaanAngkaKumanUdara(vo);
if (result)
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when updatePemeriksaanAngkaKumanUdara", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when updatePemeriksaanAngkaKumanUdara", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when updatePemeriksaanAngkaKumanUdara", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when updatePemeriksaanAngkaKumanUdara", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/delete-pemeriksaan-angka-kuman-udara", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> deletePemeriksaanAngkaKumanUdara(
@RequestParam(value = "id", required = true) Integer id, HttpServletRequest request) {
@RequestMapping(value = "/delete-pemeriksaan-angka-kuman-udara", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> deletePemeriksaanAngkaKumanUdara(@RequestParam(value = "id") Integer id,
HttpServletRequest request) {
try {
Boolean result = service.deletePemeriksaanAngkaKumanUdara(id);
if (result)
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when deletePemeriksaanAngkaKumanUdara", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when deletePemeriksaanAngkaKumanUdara", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when deletePemeriksaanAngkaKumanUdara", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when deletePemeriksaanAngkaKumanUdara", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping("/lapPemeriksaanAngkaKumanUdara")
public ModelAndView generateLapHasilPemeriksaanSWAPantauLimbahCair(ModelAndView m,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "startDate", required = true) String startDate,
@RequestParam(value = "endDate", required = true) String endDate) {
@RequestParam(value = "startDate") String startDate, @RequestParam(value = "endDate") String endDate) {
Map<String, Object> result = this.service.getRepotingPemeriksaanAngkaKumanUdaraByPeriode(startDate, endDate);
Map<String, Object> header = (Map<String, Object>) result.get("header");
String periode = header.get("startDate") == null ? "" : (String) header.get("startDate");
periode = periode + (header.get("endDate") == null ? "" : " sd " + (String) header.get("endDate"));
periode = periode + (header.get("endDate") == null ? "" : " sd " + header.get("endDate"));
m.addObject("dataSource", result.get("listData"));
m.addObject("periode", periode);
m.addObject("format", "pdf");
if (format != null && !format.isEmpty()) {
if (format != null && !format.isEmpty())
m.addObject("format", format);
}
return m;
}
@RequestMapping(value = "/download-file-hasil-pemantauan", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> downloadFileHasilPemantauan(@RequestParam(value = "id") Integer id,
HttpServletRequest request) {
try {
Map<String, Object> result = service.downloadFileHasilPemantauan(id);
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when downloadFileHasilPemantauan", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when downloadFileHasilPemantauan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
}

View File

@ -1,144 +1,140 @@
package com.jasamedika.medifirst2000.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PengukuranKebisinganService;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PengukuranKebisinganService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
@RequestMapping("/pengukuran-kebisingan")
public class PengukuranKebisinganController extends LocaleController<PengukuranKebisinganVO>{
public class PengukuranKebisinganController extends LocaleController<PengukuranKebisinganVO> {
private static final Logger LOGGER = getLogger(PengukuranKebisinganController.class);
@Autowired
private PengukuranKebisinganService service;
private static final Logger LOGGER = LoggerFactory.getLogger(PengukuranKebisinganController.class);
@RequestMapping(value = "/get-unit-ruangan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-unit-ruangan", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getUnitRuangan(HttpServletRequest request) {
try {
Map<String,Object> result = service.getUnitRuangan();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getUnitRuangan();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getUnitRuangan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getUnitRuangan", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getUnitRuangan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getUnitRuangan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-baku-mutu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-baku-mutu", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getBakuMutu(HttpServletRequest request) {
try {
Map<String,Object> result = service.getBakuMutu();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getBakuMutu();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getBakuMutu", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getBakuMutu", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getBakuMutu", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getBakuMutu", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/save-pengukuran-kebisingan", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePengukuranKebisingan(@Valid @RequestBody PengukuranKebisinganVO vo, HttpServletRequest request) {
try {
Map<String,Object> result = service.savePengukuranKebisingan(vo);
if (null != result)
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage);
@RequestMapping(value = "/save-pengukuran-kebisingan", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePengukuranKebisingan(@Valid @RequestBody PengukuranKebisinganVO vo,
HttpServletRequest request) {
try {
vo.setMenutype("kebisingan");
Map<String, Object> result = service.savePengukuranKebisingan(vo);
if (null != result)
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePengukuranKebisingan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when savePengukuranKebisingan", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePengukuranKebisingan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when savePengukuranKebisingan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-pengukuran-kebisingan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-pengukuran-kebisingan", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getPengukuranKebisingan(HttpServletRequest request) {
try {
Map<String,Object> result = service.getPengukuranKebisingan();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getPengukuranKebisingan();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getPengukuranKebisingan", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getPengukuranKebisingan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping("/lapPengukuranKebisingan")
public ModelAndView generateLapHasilPemeriksaanSWAPantauLimbahCair(ModelAndView m,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "startDate", required = true) String startDate,
@RequestParam(value = "endDate", required = true) String endDate) {
@RequestParam(value = "startDate") String startDate, @RequestParam(value = "endDate") String endDate) {
Map<String, Object> result = this.service.getRepotingPengukurangKebisingan(startDate, endDate);
Map<String, Object> header = (Map<String, Object>) result.get("header");
String periode = header.get("startDate") == null ? "" : (String) header.get("startDate");
periode = periode + (header.get("endDate") == null ? "" : " sd " + (String) header.get("endDate"));
periode = periode + (header.get("endDate") == null ? "" : " sd " + header.get("endDate"));
m.addObject("dataSource", result.get("listData"));
m.addObject("periode", periode);
m.addObject("format", "pdf");
if (format != null && !format.isEmpty()) {
if (format != null && !format.isEmpty())
m.addObject("format", format);
}
return m;
}
}

View File

@ -1,143 +1,98 @@
package com.jasamedika.medifirst2000.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PengukuranKelembabanService;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PengukuranKelembabanService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
@RequestMapping("/pengukuran-kelembaban")
public class PengukuranKelembabanController extends LocaleController<PengukuranKebisinganVO>{
public class PengukuranKelembabanController extends LocaleController<PengukuranKebisinganVO> {
private static final Logger LOGGER = getLogger(PengukuranKelembabanController.class);
@Autowired
private PengukuranKelembabanService service;
private static final Logger LOGGER = LoggerFactory.getLogger(PengukuranKelembabanController.class);
@RequestMapping(value = "/get-unit-ruangan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getUnitRuangan(HttpServletRequest request) {
try {
Map<String,Object> result = service.getUnitRuangan();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getUnitRuangan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getUnitRuangan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-baku-mutu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getBakuMutu(HttpServletRequest request) {
try {
Map<String,Object> result = service.getBakuMutu();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getBakuMutu", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getBakuMutu", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/save-pengukuran-kelembaban", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePengukuranKelembaban(@Valid @RequestBody PengukuranKebisinganVO vo, HttpServletRequest request) {
@RequestMapping(value = "/save-pengukuran-kelembaban", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePengukuranKelembaban(@Valid @RequestBody PengukuranKebisinganVO vo,
HttpServletRequest request) {
try {
vo.setMenutype("kelembaban");
Map<String,Object> result = service.savePengukuranKelembaban(vo);
Map<String, Object> result = service.savePengukuranKelembaban(vo);
if (null != result)
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePengukuranKelembaban", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when savePengukuranKelembaban", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePengukuranKelembaban", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when savePengukuranKelembaban", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-pengukuran-kelembaban", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-pengukuran-kelembaban", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getPengukuranKelembaban(HttpServletRequest request) {
try {
Map<String,Object> result = service.getPengukuranKelembaban();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getPengukuranKelembaban();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getPengukuranKelembaban", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getPengukuranKelembaban", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping("/lapPengukuranKelembaban")
public ModelAndView lapPengukuranKelembaban(ModelAndView m,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "startDate", required = true) String startDate,
@RequestParam(value = "endDate", required = true) String endDate) {
@RequestParam(value = "startDate") String startDate, @RequestParam(value = "endDate") String endDate) {
Map<String, Object> result = this.service.getRepotingPengukurangKelembaban(startDate, endDate);
Map<String, Object> header = (Map<String, Object>) result.get("header");
String periode = header.get("startDate") == null ? "" : (String) header.get("startDate");
periode = periode + (header.get("endDate") == null ? "" : " sd " + (String) header.get("endDate"));
periode = periode + (header.get("endDate") == null ? "" : " sd " + header.get("endDate"));
m.addObject("dataSource", result.get("listData"));
m.addObject("periode", periode);
m.addObject("format", "pdf");
if (format != null && !format.isEmpty()) {
if (format != null && !format.isEmpty())
m.addObject("format", format);
}
return m;
}
}

View File

@ -1,145 +1,98 @@
package com.jasamedika.medifirst2000.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PengukuranPencahayaanService;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PengukuranPencahayaanService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
@RequestMapping("/pengukuran-pencahayaan")
public class PengukuranPencahayaanController extends LocaleController<PengukuranKebisinganVO>{
public class PengukuranPencahayaanController extends LocaleController<PengukuranKebisinganVO> {
private static final Logger LOGGER = getLogger(PengukuranPencahayaanController.class);
@Autowired
private PengukuranPencahayaanService service;
private static final Logger LOGGER = LoggerFactory.getLogger(PengukuranPencahayaanController.class);
@RequestMapping(value = "/get-unit-ruangan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getUnitRuangan(HttpServletRequest request) {
try {
Map<String,Object> result = service.getUnitRuangan();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getUnitRuangan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getUnitRuangan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-baku-mutu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getBakuMutu(HttpServletRequest request) {
try {
Map<String,Object> result = service.getBakuMutu();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getBakuMutu", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getBakuMutu", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/save-pengukuran-pencahayaan", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePengukuranPencahayaan(@Valid @RequestBody PengukuranKebisinganVO vo, HttpServletRequest request) {
@RequestMapping(value = "/save-pengukuran-pencahayaan", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePengukuranPencahayaan(@Valid @RequestBody PengukuranKebisinganVO vo,
HttpServletRequest request) {
try {
vo.setMenutype("pencahayaan");
Map<String,Object> result = service.savePengukuranPencahayaan(vo);
Map<String, Object> result = service.savePengukuranPencahayaan(vo);
if (null != result)
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePengukuranPencahayaan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when savePengukuranPencahayaan", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePengukuranPencahayaan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when savePengukuranPencahayaan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-pengukuran-pencahayaan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-pengukuran-pencahayaan", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getPengukuranPencahayaan(HttpServletRequest request) {
try {
Map<String,Object> result = service.getPengukuranPencahayaan();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getPengukuranPencahayaan();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getPengukuranPencahayaan", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getPengukuranPencahayaan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
}
@RequestMapping("/lapPengukuranPencahayaan")
public ModelAndView lapPengukuranPencahayaan(ModelAndView m,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "startDate", required = true) String startDate,
@RequestParam(value = "endDate", required = true) String endDate) {
@RequestParam(value = "startDate") String startDate, @RequestParam(value = "endDate") String endDate) {
Map<String, Object> result = this.service.getRepotingPengukurangPencahayaan(startDate, endDate);
Map<String, Object> header = (Map<String, Object>) result.get("header");
String periode = header.get("startDate") == null ? "" : (String) header.get("startDate");
periode = periode + (header.get("endDate") == null ? "" : " sd " + (String) header.get("endDate"));
periode = periode + (header.get("endDate") == null ? "" : " sd " + header.get("endDate"));
m.addObject("dataSource", result.get("listData"));
m.addObject("periode", periode);
m.addObject("format", "pdf");
if (format != null && !format.isEmpty()) {
if (format != null && !format.isEmpty())
m.addObject("format", format);
}
return m;
}
}

View File

@ -1,143 +1,97 @@
package com.jasamedika.medifirst2000.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PengukuranSuhuService;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.PengukuranSuhuService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
@RequestMapping("/pengukuran-suhu")
public class PengukuranSuhuController extends LocaleController<PengukuranKebisinganVO>{
public class PengukuranSuhuController extends LocaleController<PengukuranKebisinganVO> {
private static final Logger LOGGER = getLogger(PengukuranSuhuController.class);
@Autowired
private PengukuranSuhuService service;
private static final Logger LOGGER = LoggerFactory.getLogger(PengukuranSuhuController.class);
@RequestMapping(value = "/get-unit-ruangan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getUnitRuangan(HttpServletRequest request) {
try {
Map<String,Object> result = service.getUnitRuangan();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getUnitRuangan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getUnitRuangan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-baku-mutu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getBakuMutu(HttpServletRequest request) {
try {
Map<String,Object> result = service.getBakuMutu();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getBakuMutu", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getBakuMutu", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/save-pengukuran-suhu", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePengukuranPencahayaan(@Valid @RequestBody PengukuranKebisinganVO vo, HttpServletRequest request) {
@RequestMapping(value = "/save-pengukuran-suhu", method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePengukuranPencahayaan(@Valid @RequestBody PengukuranKebisinganVO vo,
HttpServletRequest request) {
try {
vo.setMenutype("suhu");
Map<String,Object> result = service.savePengukuranSuhu(vo);
Map<String, Object> result = service.savePengukuranSuhu(vo);
if (null != result)
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePengukuranPencahayaan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when savePengukuranPencahayaan", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePengukuranPencahayaan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when savePengukuranPencahayaan", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping(value = "/get-pengukuran-suhu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/get-pengukuran-suhu", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getPengukuranKelembaban(HttpServletRequest request) {
try {
Map<String,Object> result = service.getPengukuranSuhu();
if (null != result){
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage);
} else{
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage);
Map<String, Object> result = service.getPengukuranSuhu();
if (null != result) {
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK, mapHeaderMessage);
} else {
return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
LOGGER.error("Got ServiceVOException {} when getPengukuranSuhu", e.getMessage());
addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
LOGGER.error("Got JpaSystemException {} when getPengukuranSuhu", jse.getMessage());
addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
}
@RequestMapping("/lapPengukuranSuhu")
public ModelAndView lapPengukuranSuhu(ModelAndView m,
@RequestParam(value = "format", required = false) String format,
@RequestParam(value = "startDate", required = true) String startDate,
@RequestParam(value = "endDate", required = true) String endDate) {
@RequestParam(value = "startDate") String startDate, @RequestParam(value = "endDate") String endDate) {
Map<String, Object> result = this.service.getRepotingPengukurangSuhu(startDate, endDate);
Map<String, Object> header = (Map<String, Object>) result.get("header");
String periode = header.get("startDate") == null ? "" : (String) header.get("startDate");
periode = periode + (header.get("endDate") == null ? "" : " sd " + (String) header.get("endDate"));
periode = periode + (header.get("endDate") == null ? "" : " sd " + header.get("endDate"));
m.addObject("dataSource", result.get("listData"));
m.addObject("periode", periode);
m.addObject("format", "pdf");
if (format != null && !format.isEmpty()) {
if (format != null && !format.isEmpty())
m.addObject("format", format);
}
return m;
}
}

View File

@ -1,42 +0,0 @@
package com.jasamedika.medifirst2000.controller.base;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
/**
* Base Rest Operation for Controller Class
*
* @author Roberto
*/
public interface IBaseRestController<V extends BaseModelVO> extends
IRestPageController<V> {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<V> getVO(@PathVariable("id") Integer id);
@RequestMapping(value = "/", method = RequestMethod.PUT, consumes = { "application/json" })
@ResponseBody
public ResponseEntity<String> addVO(@RequestBody V vo);
@RequestMapping(value = "/", method = RequestMethod.POST, consumes = { "application/json" })
@ResponseBody
public ResponseEntity<String> editVO(@RequestBody V vo);
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<String> deleteVO(@PathVariable("id") Integer id);
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<V>> getAllVO();
}

View File

@ -1,41 +0,0 @@
package com.jasamedika.medifirst2000.controller.base;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
/**
* Base Rest Operation for 'pagination' Controller Class
*
* @author Roberto
*/
public interface IRestPageController<V extends BaseModelVO> {
/**
*
* @param page
* : page of
* @param limit
* : limit query
* @param sort
* : sort by
* @param dir
* : direction {asc:desc}
* @return Collection of VO, Total-Count & Total Pages on response header
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Collection<V>> getAllVOWithQueryString(
HttpServletRequest request,
@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
@RequestParam(value = "dir", required = false, defaultValue = "asc") String dir);
}

View File

@ -1,60 +1,46 @@
package com.jasamedika.medifirst2000.controller.base;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.ActivityPegawaiService;
import com.jasamedika.medifirst2000.service.LoginUserService;
import com.jasamedika.medifirst2000.service.ModelService;
import com.jasamedika.medifirst2000.vo.ModelVO;
import com.jasamedika.medifirst2000.vo.PegawaiVO;
import io.socket.client.IO;
import io.socket.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.service.ActivityPegawaiService;
import com.jasamedika.medifirst2000.service.AgamaService;
import com.jasamedika.medifirst2000.service.LoginUserService;
import com.jasamedika.medifirst2000.service.ModelService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.ModelVO;
import com.jasamedika.medifirst2000.vo.PasienVO;
import com.jasamedika.medifirst2000.vo.PegawaiVO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.*;
import io.socket.client.IO;
import static com.jasamedika.medifirst2000.constants.Constants.Locale.INA;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER;
import static com.jasamedika.medifirst2000.core.web.WebConstants.PageParameter.*;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* Base Controller Class for handling messaga resource for internationalization
@ -63,104 +49,75 @@ import io.socket.client.IO;
* @author Roberto
*/
public abstract class LocaleController<V extends BaseModelVO> {
/*
* messageSource bean injected for each controller for accessing message
* source
*/
@Autowired
private ActivityPegawaiService activityPegawaiServiceImpl;
@Autowired
private BaseConverterImpl<PegawaiVO, Pegawai> pegawaiConverter;
@Autowired
private LoginUserService loginUserService;
@Autowired
private MessageSource messageSource;
@Autowired
private ModelService modelService;
private ModelService<ModelVO> modelService;
@Autowired
private AgamaService agamaService;
protected Map<String, String> mapHeaderMessage = new HashMap<String, String>();
protected Map<String, String> mapHeaderMessage = new HashMap<>();
/*
* code locale
*/
protected String getMessage(String code, HttpServletRequest request) {
return messageSource.getMessage(code, null, new Locale(getCoociesLanguage(request)));
}
protected void SaveLog(String keterangan,String group, HttpServletRequest request) {
activityPegawaiServiceImpl.record(pegawaiConverter.transferModelToVO(loginUserService.getLoginUser().getPegawai(), new PegawaiVO()) , new Date(), keterangan,group);
}
protected Object getItem(HttpServletRequest request,Object vo)
{
BufferedReader reader;
String read = null;
String resultData = "";
Gson gson = new Gson();
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((read = reader.readLine()) != null) {
resultData += read;
System.out.println(read);
}
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")//.excludeFieldsWithoutExposeAnnotation()
.create();
protected void SaveLog(String keterangan, String group) {
activityPegawaiServiceImpl.record(
pegawaiConverter.transferModelToVO(loginUserService.getLoginUser().getPegawai(), new PegawaiVO()),
new Date(), keterangan, group);
}
protected Object getItem(HttpServletRequest request, Object vo) {
try {
StringBuilder resultData = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String read;
while ((read = reader.readLine()) != null)
resultData.append(read);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
return gson.fromJson(resultData.toString(), vo.getClass());
} catch (IOException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
return vo= gson.fromJson(resultData, vo.getClass());
}
protected Object getItem2(HttpServletRequest request,Object vo)
{
BufferedReader reader;
String read = null;
String resultData = "";
Gson gson = new Gson();
protected Object getItem2(HttpServletRequest request, Object vo) {
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((read = reader.readLine()) != null) {
resultData += read;
System.out.println(read);
}
String read;
StringBuilder resultData = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((read = reader.readLine()) != null)
resultData.append(read);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if(json.getAsString() instanceof String){
return new Date();
}else{
return new Date(json.getAsJsonPrimitive().getAsLong());
}
}
});
gson = gsonBuilder.create();
gsonBuilder.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> {
if (json.getAsString() != null) {
return new Date();
} else {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = gsonBuilder.create();
return gson.fromJson(resultData.toString(), vo.getClass());
} catch (IOException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
return vo= gson.fromJson(resultData, vo.getClass());
}
@RequestMapping(value = "/lang/{lang}", method = RequestMethod.GET)
@RequestMapping(value = "/lang/{lang}", method = GET)
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
@PathVariable("lang") String lang) throws Exception {
@PathVariable("lang") String lang) {
Cookie[] cookies = request.getCookies();
List<Cookie> cookieList = new ArrayList<Cookie>();
List<Cookie> cookieList;
if (cookies != null) {
cookieList = Arrays.asList(cookies);
for (Cookie cookie : cookieList) {
@ -172,7 +129,6 @@ public abstract class LocaleController<V extends BaseModelVO> {
}
}
}
if (lang.equalsIgnoreCase("en")) {
Cookie c = new Cookie("lang", "en");
c.setPath("/");
@ -189,156 +145,117 @@ public abstract class LocaleController<V extends BaseModelVO> {
c.setDomain("localhost");
response.addCookie(c);
}
return true;
}
/*
* default locale ID
*/
protected String getMessage(String code) {
return messageSource.getMessage(code, null, new Locale(Constants.Locale.INA));
return messageSource.getMessage(code, null, new Locale(INA));
}
protected void addHeaderMessage(String key, String message) {
this.mapHeaderMessage.put(key, message);
}
@RequestMapping(value = "/entity-serelize/{entity}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/entity-serelize/{entity}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<ModelVO> serializeEntity(@PathVariable("entity") String entity, HttpServletRequest request) {
ModelVO modelDTO = modelService.getModelSerializeEntity(entity, getCoociesLanguage(request));
return RestUtil.getJsonResponse(modelDTO, HttpStatus.OK);
return getJsonResponse(modelDTO, OK);
}
public String getCoociesLanguage(HttpServletRequest request) {
Cookie cookie[] = request.getCookies();
Cookie[] cookie = request.getCookies();
Cookie cook;
String lang = Constants.Locale.INA;
String lang = INA;
if (cookie != null) {
for (int i = 0; i < cookie.length; i++) {
cook = cookie[i];
for (Cookie value : cookie) {
cook = value;
if (cook.getName().equalsIgnoreCase("lang"))
lang = cook.getValue();
}
}
return lang;
}
@SuppressWarnings("rawtypes")
protected ResponseEntity constructListPageResult(Map<String, Object> map) {
protected ResponseEntity<Collection<V>> constructListPageResult(Map<String, Object> map) {
if (map == null) {
Map<String, String> mapHeaderMessage = new HashMap<String, String>();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER, "0");
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER, "0");
mapHeaderMessage.put(Constants.MessageInfo.ERROR_MESSAGE, "Data not found.");
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, mapHeaderMessage);
Map<String, String> mapHeaderMessage = new HashMap<>();
mapHeaderMessage.put(TOTAL_PAGE_HEADER, "0");
mapHeaderMessage.put(TOTAL_COUNT_HEADER, "0");
mapHeaderMessage.put(ERROR_MESSAGE, "Data not found.");
return getJsonResponse(null, BAD_REQUEST, mapHeaderMessage);
} else {
@SuppressWarnings("unchecked")
Collection<PasienVO> vos = (Collection<PasienVO>) map.get(WebConstants.PageParameter.LIST_DATA);
Map<String, String> mapHeaderMessage = new HashMap<String, String>();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER,
String.valueOf(map.get(WebConstants.PageParameter.TOTAL_PAGES)));
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER,
String.valueOf(map.get(WebConstants.PageParameter.TOTAL_ELEMENTS)));
return RestUtil.getJsonResponse(vos, HttpStatus.OK, mapHeaderMessage);
Collection<V> vos = (Collection<V>) map.get(LIST_DATA);
Map<String, String> mapHeaderMessage = new HashMap<>();
mapHeaderMessage.put(TOTAL_PAGE_HEADER, String.valueOf(map.get(TOTAL_PAGES)));
mapHeaderMessage.put(TOTAL_COUNT_HEADER, String.valueOf(map.get(TOTAL_ELEMENTS)));
return getJsonResponse(vos, OK, mapHeaderMessage);
}
}
// @PersistenceContext
// protected EntityManager em;
public String GetSettingDataFixed(String prefix) {
return activityPegawaiServiceImpl.GetSettingDataFixed(prefix);
// StringBuffer buffer = new StringBuffer();
// buffer.append("select model.nilaiField from SettingDataFixed ")
// .append(" model where model.namaField ='" + prefix + "' ");
// Query query = em.createQuery(buffer.toString());
//
// return (String) query.getSingleResult();
}
protected void BroadcastMessage(final String to, final Object data) {
final io.socket.client.Socket socket;
try {
String url =GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url);
socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() {
@Override
public void call(Object... args) {
try {
Gson gson = new Gson();
String json = gson.toJson(data);
JSONObject item= new JSONObject("{\"to\":\""+to+"\",\"message\":\""+json.replace("\"", "'")+"\"}");
socket.emit("subscribe", item);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
protected void BroadcastMessage(final String to, final String data) {
final io.socket.client.Socket socket;
protected void BroadcastMessage(final Object data) {
final Socket socket;
try {
socket = IO.socket(GetSettingDataFixed("UrlSocketMessaging"));
socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() {
@Override
public void call(Object... args) {
try {
JSONObject item= new JSONObject("{\"to\":\""+to+"\",\"message\":\""+data+"\"}");
socket.emit("subscribe", item);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
protected void BroadcastMessageOther(final String to, final Object data) {
final io.socket.client.Socket socket;
try {
String url = GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url);
socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() {
@Override
public void call(Object... args) {
try {
Map<String, Object> result = new HashMap<>();
result.put("message", data);
result.put("to", to);
Gson gson = new Gson();
JSONObject item = new JSONObject(gson.toJson(result));
socket.emit("subscribe", item);
} catch (JSONException e) {
e.printStackTrace();
}
socket.on(Socket.EVENT_CONNECT, args -> {
try {
Gson gson = new Gson();
String json = gson.toJson(data);
JSONObject item = new JSONObject(
"{\"to\":\"" + "ResultLabDevice" + "\",\"message\":\"" + json.replace("\"", "'") + "\"}");
socket.emit("subscribe", item);
} catch (JSONException e) {
throw new ServiceVOException(e.getMessage());
}
});
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
throw new ServiceVOException(e.getMessage());
}
}
protected void BroadcastMessage(final String to, final String data) {
final Socket socket;
try {
socket = IO.socket(GetSettingDataFixed("UrlSocketMessaging"));
socket.on(Socket.EVENT_CONNECT, args -> {
try {
JSONObject item = new JSONObject("{\"to\":\"" + to + "\",\"message\":\"" + data + "\"}");
socket.emit("subscribe", item);
} catch (JSONException e) {
throw new ServiceVOException(e.getMessage());
}
});
socket.connect();
} catch (URISyntaxException e) {
throw new ServiceVOException(e.getMessage());
}
}
protected void BroadcastMessageOther(final Object data) {
final Socket socket;
try {
String url = GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url);
socket.on(Socket.EVENT_CONNECT, args -> {
try {
Map<String, Object> result = new HashMap<>();
result.put("message", data);
result.put("to", "PermintaanPerbaikan");
Gson gson = new Gson();
JSONObject item = new JSONObject(gson.toJson(result));
socket.emit("subscribe", item);
} catch (JSONException e) {
throw new ServiceVOException(e.getMessage());
}
});
socket.connect();
} catch (URISyntaxException e) {
throw new ServiceVOException(e.getMessage());
}
}

View File

@ -1,78 +1,64 @@
package com.jasamedika.medifirst2000.controller.base;
import java.util.List;
import org.springframework.core.GenericTypeResolver;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.monitorjbl.json.JsonResult;
import com.monitorjbl.json.JsonView;
import com.monitorjbl.json.Match;
import org.springframework.core.GenericTypeResolver;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import static com.jasamedika.medifirst2000.constants.Constants.COMMA;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* Base Controller Class for handling "include" parameter to controller
* @see https://github.com/monitorjbl/json-view
* Base Controller Class for handling "include" parameter to controller
*
* @see <a href="https://github.com/monitorjbl/json-view">reference</a>
*
* @author Roberto
*/
public abstract class ParamRestController<T extends BaseModelVO> {
private JsonResult jsonResult = JsonResult.instance();
/*
* Belum selesai, baru di parameter includes. Untuk field object juga belom.
* example :
* http://localhost:8080/jasamedika-web/{typeVOClass}/list-using-param
* ?includes =id,nama
*/
@RequestMapping(value = "/list-using-param", method = RequestMethod.GET)
public ResponseEntity<List<T>> listUsingParam(
@RequestParam(value = "includes", required = false) String includes,
private final JsonResult jsonResult = JsonResult.instance();
@RequestMapping(value = "/list-using-param", method = GET)
public ResponseEntity<List<T>> listUsingParam(@RequestParam(value = "includes", required = false) String includes,
@RequestParam(value = "excludes", required = false) String excludes) {
List<T> listVO = getAllVOFromService();
String[] arrExcludes = null;
String[] arrIncludes = null;
if (excludes != null)
arrExcludes = excludes.split(Constants.COMMA);
arrExcludes = excludes.split(COMMA);
if (includes != null)
arrIncludes = includes.split(Constants.COMMA);
arrIncludes = includes.split(COMMA);
if (arrExcludes != null && arrIncludes != null) {
listVO = jsonResult.use(
JsonView.with(listVO).onClass(
getClazz(),
Match.match().exclude(arrExcludes)
.include(arrIncludes))).returnValue();
JsonView.with(listVO).onClass(getClazz(), Match.match().exclude(arrExcludes).include(arrIncludes)))
.returnValue();
}
if (arrExcludes != null && arrIncludes == null) {
listVO = jsonResult.use(
JsonView.with(listVO).onClass(getClazz(),
Match.match().include("*").exclude(arrExcludes)))
listVO = jsonResult
.use(JsonView.with(listVO).onClass(getClazz(), Match.match().include("*").exclude(arrExcludes)))
.returnValue();
}
if (arrExcludes == null && arrIncludes != null) {
listVO = jsonResult.use(
JsonView.with(listVO).onClass(getClazz(),
Match.match().exclude("*").include(arrIncludes)))
listVO = jsonResult
.use(JsonView.with(listVO).onClass(getClazz(), Match.match().exclude("*").include(arrIncludes)))
.returnValue();
}
return RestUtil.getJsonResponse(listVO, HttpStatus.OK);
return RestUtil.getJsonResponse(listVO, OK);
}
@SuppressWarnings("unchecked")
protected Class<T> getClazz() {
return (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(),
ParamRestController.class);
return (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), ParamRestController.class);
}
/*
* method untuk mendapatkan all VO from service
* */
protected abstract List<T> getAllVOFromService();
}

View File

@ -1,30 +1,21 @@
package com.jasamedika.medifirst2000.filter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.jasamedika.medifirst2000.constants.Constants;
import static com.jasamedika.medifirst2000.constants.Constants.HttpHeader.KD_RUANGAN_A;
import static com.jasamedika.medifirst2000.constants.Constants.HttpHeader.KD_RUANGAN_T;
import static org.slf4j.LoggerFactory.getLogger;
/**
* CORSFilter class
@ -33,132 +24,112 @@ import com.jasamedika.medifirst2000.constants.Constants;
*/
@Component
public class CORSFilter implements Filter {
// Start Syamsu
private static final Logger LOGGER = getLogger(CORSFilter.class);
public CORSFilter() {
LOGGER.info("CORSFilter JasaMedika Web init");
}
private static class RequestWrapper extends HttpServletRequestWrapper {
final String body;
public RequestWrapper(ServletRequest req) throws IOException {
super((HttpServletRequest) req);
HttpServletRequest request = (HttpServletRequest) req;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
reader = new BufferedReader(new InputStreamReader(inputStream));
String hasil;
while ( (hasil = reader.readLine()) != null) {
stringBuilder.append(hasil);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
String idRuanganTujuan = request.getHeader(Constants.HttpHeader.KD_RUANGAN_T) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN_T);
if ("".equals(idRuanganTujuan.trim())){
try{
JSONObject jObject = new JSONObject(body);
ExtractObjectJson(jObject, false);
}catch(Exception e){
}
}
}
public String getHeader(String key){
if (key.equals(Constants.HttpHeader.KD_RUANGAN_A)) {
if (autoIdTujuan.length() > 0){
return autoIdTujuan.toString();
}
StringBuilder stringBuilder = getStringBuilder(request);
body = stringBuilder.toString();
String idRuanganTujuan = request.getHeader(KD_RUANGAN_T) == null ? "" : request.getHeader(KD_RUANGAN_T);
if (idRuanganTujuan.trim().isEmpty()) {
JSONObject jObject;
try {
jObject = new JSONObject(body);
} catch (JSONException e) {
throw new RuntimeException(e);
}
try {
ExtractObjectJson(jObject, false);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String getHeader(String key) {
if (key.equals(KD_RUANGAN_A)) {
if (autoIdTujuan.length() > 0) {
return autoIdTujuan.toString();
}
}
return super.getHeader(key);
}
JSONArray autoIdTujuan = new JSONArray();
void ExtractObjectJson(JSONObject jObject, boolean ruangan) throws Exception{
Iterator iterator = jObject.keys();
while (iterator.hasNext()){
String key = String.valueOf(iterator.next());
Object o = jObject.get(key);
if (key.toLowerCase().contains("ruangan")){
if (o instanceof Integer){
autoIdTujuan.put(o);
} else if (o instanceof JSONObject){
ExtractObjectJson((JSONObject) o, true);
}
} else if (ruangan && "id".equals(key)){
if (o instanceof Integer){
autoIdTujuan.put(o);
return;
}
} else if (o instanceof JSONObject && !ruangan) {
ExtractObjectJson((JSONObject) o, false);
}
}
void ExtractObjectJson(JSONObject jObject, boolean ruangan) throws Exception {
Iterator<?> iterator = jObject.keys();
while (iterator.hasNext()) {
String key = String.valueOf(iterator.next());
Object o = jObject.get(key);
if (key.toLowerCase().contains("ruangan")) {
if (o instanceof Integer) {
autoIdTujuan.put(o);
} else if (o instanceof JSONObject) {
ExtractObjectJson((JSONObject) o, true);
}
} else if (ruangan && "id".equals(key)) {
if (o instanceof Integer) {
autoIdTujuan.put(o);
return;
}
} else if (o instanceof JSONObject && !ruangan) {
ExtractObjectJson((JSONObject) o, false);
}
}
}
@Override
public ServletInputStream getInputStream() throws IOException {
public ServletInputStream getInputStream() {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return new ServletInputStream() {
public int read() {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
@Override
public BufferedReader getReader() throws IOException {
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
public String getBody() {
return this.body;
}
}
// End Syamsu
private final Logger log = LoggerFactory.getLogger(CORSFilter.class);
public CORSFilter() {
log.info("CORSFilter JasaMedika Web init");
private static StringBuilder getStringBuilder(HttpServletRequest request) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
reader = new BufferedReader(new InputStreamReader(inputStream));
String hasil;
while ((hasil = reader.readLine()) != null) {
stringBuilder.append(hasil);
}
}
} finally {
if (reader != null)
reader.close();
}
return stringBuilder;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// Start Syamsu
RequestWrapper myReq = new RequestWrapper((HttpServletRequest) req);
// End Syamsu
HttpServletRequest request = (HttpServletRequest) myReq;
RequestWrapper myReq = new RequestWrapper(req);
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Origin", myReq.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
@ -166,19 +137,11 @@ public class CORSFilter implements Filter {
+ "Supervising, RequestSupervisor, Module, Form, Action, AlamatUrlForm, KdRuangan, KdUser, "
+ "MandatoriData, idRuanganTujuan, ruanganTujuan");
response.setHeader("Content-Type", "application/json");
// String body = myReq.getBody();
// if (!"".equals(body.trim())){
// log.info("\n\n" + myReq.getBody() + "\n");
// }
chain.doFilter(myReq, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override

View File

@ -1,8 +1,11 @@
package com.jasamedika.medifirst2000.filter;
import com.fasterxml.jackson.core.JsonParseException;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import io.jsonwebtoken.MalformedJwtException;
import java.io.IOException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
@ -10,14 +13,9 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import com.fasterxml.jackson.core.JsonParseException;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
/**
* StatelessAuthenticationFilter class
@ -25,43 +23,37 @@ import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
* @author Roberto
*/
public class StatelessAuthenticationFilter extends GenericFilterBean {
private final TokenAuthenticationService authenticationService;
public StatelessAuthenticationFilter(
TokenAuthenticationService authenticationService) {
public StatelessAuthenticationFilter(TokenAuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin",
req.getHeader("Origin"));
res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods",
"POST, GET, OPTIONS, DELETE");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers",
"Content-Type, Accept, X-Requested-With, remember-me, X-AUTH-TOKEN, Supervising, "
+ "RequestSupervisor, Module, Form, Action, AlamatUrlForm, KdRuangan, KdUser, "
+ "MandatoriData");
+ "RequestSupervisor, Module, Form, Action, AlamatUrlForm, KdRuangan, KdUser, "
+ "MandatoriData");
Authentication authentication = null;
try {
authentication = authenticationService.getAuthentication(httpRequest);
} catch (JsonParseException | MalformedJwtException e) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.addHeader(Constants.MessageInfo.ERROR_MESSAGE,
"Error Token (Not Valid Token)");
httpResponse.addHeader(ERROR_MESSAGE, "Error Token (Not Valid Token)");
filterChain.doFilter(request, response);
}
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
SecurityContextHolder.getContext().setAuthentication(null);
}
}

View File

@ -1,15 +1,11 @@
package com.jasamedika.medifirst2000.handler;
import java.util.List;
import java.util.Locale;
import com.jasamedika.medifirst2000.base.vo.validation.ValidationErrorVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
@ -18,8 +14,13 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.jasamedika.medifirst2000.base.vo.validation.ValidationErrorVO;
import com.jasamedika.medifirst2000.constants.Constants;;
import java.util.List;
import java.util.Locale;
import static com.jasamedika.medifirst2000.constants.Constants.Locale.INA;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
/**
* Exception Handler Rest Controller class
*
@ -27,13 +28,12 @@ import com.jasamedika.medifirst2000.constants.Constants;;
*/
@ControllerAdvice
@Order(1) // Pertama masuk
@Order(1)
public class RestErrorHandler {
private static final Logger LOGGER = LoggerFactory
.getLogger(RestErrorHandler.class);
private static final Logger LOGGER = getLogger(RestErrorHandler.class);
private MessageSource messageSource;
private final MessageSource messageSource;
@Autowired
public RestErrorHandler(MessageSource validationNessageSource) {
@ -41,64 +41,42 @@ public class RestErrorHandler {
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseStatus(BAD_REQUEST)
@ResponseBody
public ValidationErrorVO processValidationError(
MethodArgumentNotValidException ex) {
public ValidationErrorVO processValidationError(MethodArgumentNotValidException ex) {
LOGGER.warn("Handling data validation error");
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
return processFieldErrors(fieldErrors);
}
private ValidationErrorVO processFieldErrors(List<FieldError> fieldErrors) {
ValidationErrorVO dto = new ValidationErrorVO();
for (FieldError fieldError : fieldErrors) {
String localizedErrorMessage = resolveLocalizedErrorMessage(fieldError);
String localizedErrorMessage = resolveIndonesianErrorMessage(fieldError);
dto.addFieldError(fieldError.getField(), localizedErrorMessage);
}
return dto;
}
/*
* resolve error message with parameter locale
*/
private String resolveLocalizedErrorMessage(FieldError fieldError, String locale) {
private String resolveCurrentLocalErrorMessage(FieldError fieldError) {
Locale currentLocale = LocaleContextHolder.getLocale();
String localizedErrorMessage = messageSource.getMessage(fieldError,
currentLocale);
// If the message was not found, return the most accurate field error
// code instead.
// You can remove this check if you prefer to get the default error
// message.
String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale);
if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0];
}
return localizedErrorMessage;
}
/*
* resolve error message with default locale
*/
private String resolveLocalizedErrorMessage(FieldError fieldError) {
String localizedErrorMessage = messageSource.getMessage(fieldError,
new Locale(Constants.Locale.INA));
// If the message was not found, return the most accurate field error
// code instead.
// You can remove this check if you prefer to get the default error
// message.
private String resolveIndonesianErrorMessage(FieldError fieldError) {
String localizedErrorMessage = messageSource.getMessage(fieldError, new Locale(INA));
if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0];
}
return localizedErrorMessage;
}
}

View File

@ -1,6 +1,5 @@
package com.jasamedika.medifirst2000.interceptor;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.dao.LoginUserDao;
import com.jasamedika.medifirst2000.dao.RuanganDao;
import com.jasamedika.medifirst2000.entities.*;
@ -8,7 +7,6 @@ import com.jasamedika.medifirst2000.notification.MessagePublisher;
import com.jasamedika.medifirst2000.security.model.AppPermission;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.service.*;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.vo.NotifMessagingSchedulerVO;
import com.jasamedika.medifirst2000.vo.NotifMessagingVO;
import com.jasamedika.medifirst2000.vo.NotifikasiMessageObjekModulVO;
@ -29,6 +27,13 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.jasamedika.medifirst2000.constants.Constants.HttpHeader.*;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.INFO_MESSAGE;
import static com.jasamedika.medifirst2000.util.CommonUtil.isNotNullOrEmpty;
import static com.jasamedika.medifirst2000.util.CommonUtil.isNullOrEmpty;
import static javax.servlet.http.HttpServletResponse.*;
/**
* Interceptor class for All annotation method controller @AppPermission
*
@ -80,7 +85,7 @@ public class AppInterceptor implements HandlerInterceptor {
String namaUser;
private boolean contains(String source, String[] matchers) {
if (CommonUtil.isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers))
if (isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers))
return false;
for (String matcher : matchers)
if (source.contains(matcher))
@ -100,10 +105,10 @@ public class AppInterceptor implements HandlerInterceptor {
Authentication authentication = tokenAuthenticationService.getAuthentication(request);
namaUser = authentication.getName();
loginUser = loginUserDao.findByNamaUser(namaUser);
if (CommonUtil.isNullOrEmpty(loginUser)) {
if (isNullOrEmpty(loginUser)) {
response.setHeader("RequireSupervisor", "false");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Empty login user");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setHeader(ERROR_MESSAGE, "Empty login user");
response.setStatus(SC_FORBIDDEN);
return false;
}
return true;
@ -173,19 +178,19 @@ public class AppInterceptor implements HandlerInterceptor {
int action) throws Exception {
List<ObjekModulAplikasiVO> objekModulAplikasi = objekModulAplikasiService
.findByAlamatUrlForm(filterUrlForm(AlamatUrlForm));
if (CommonUtil.isNullOrEmpty(objekModulAplikasi))
if (isNullOrEmpty(objekModulAplikasi))
return true;
if (!checkAuthSecure(request, response))
return false;
int resultUser = checkUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action);
if (resultUser == 0) {
response.setHeader("RequireSupervisor", "true");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader(ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(SC_UNAUTHORIZED);
return false;
} else if (resultUser == 1) {
response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success");
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader(INFO_MESSAGE, "Supervise execution success");
response.setStatus(SC_OK);
return true;
}
int resultKelompokUser = checkKelompokUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action);
@ -195,12 +200,12 @@ public class AppInterceptor implements HandlerInterceptor {
return true;
} else if (resultKelompokUser == 0) {
response.setHeader("RequireSupervisor", "true");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader(ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(SC_UNAUTHORIZED);
return false;
} else {
response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success");
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader(INFO_MESSAGE, "Supervise execution success");
response.setStatus(SC_OK);
return true;
}
}
@ -209,21 +214,19 @@ public class AppInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
HandlerMethod hm;
Method method;
response.setHeader("Access-Control-Expose-Headers", "RequireSupervisor" + ","
+ Constants.MessageInfo.ERROR_MESSAGE + "," + Constants.MessageInfo.INFO_MESSAGE);
String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? ""
: request.getHeader(Constants.HttpHeader.URL_FORM);
String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN);
response.setHeader("Access-Control-Expose-Headers",
"RequireSupervisor" + "," + ERROR_MESSAGE + "," + INFO_MESSAGE);
String AlamatUrlForm = request.getHeader(URL_FORM) == null ? "" : request.getHeader(URL_FORM);
String KdRuangan = request.getHeader(KD_RUANGAN) == null ? "" : request.getHeader(KD_RUANGAN);
int action = AppPermission.VIEW;
if (CommonUtil.isNullOrEmpty(AlamatUrlForm))
if (isNullOrEmpty(AlamatUrlForm))
return true;
if (CommonUtil.isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan))
if (isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan))
return true;
String URI = request.getRequestURI();
String methodHttp = request.getMethod();
try {
if (handler instanceof org.springframework.web.method.HandlerMethod) {
if (handler instanceof HandlerMethod) {
hm = (HandlerMethod) handler;
method = hm.getMethod();
} else {
@ -264,9 +267,9 @@ public class AppInterceptor implements HandlerInterceptor {
return checkPermission(request, response, AlamatUrlForm, action);
}
} catch (Exception e) {
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Something wrong happened");
response.setHeader(ERROR_MESSAGE, "Something wrong happened");
response.setHeader("RequireSupervisor", "false");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setStatus(SC_INTERNAL_SERVER_ERROR);
return false;
}
return true;
@ -279,46 +282,41 @@ public class AppInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex)
throws Exception {
String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? ""
: request.getHeader(Constants.HttpHeader.URL_FORM);
String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN);
String idRuanganTujuan = request.getHeader(Constants.HttpHeader.KD_RUANGAN_T) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN_T);
String idRuanganTujuanA = request.getHeader(Constants.HttpHeader.KD_RUANGAN_A) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN_A);
String tglKirim = request.getHeader(Constants.HttpHeader.TGL_KIRIM) == null ? ""
: request.getHeader(Constants.HttpHeader.TGL_KIRIM);
boolean notHttpOK = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
boolean notLewatMenu = CommonUtil.isNullOrEmpty(AlamatUrlForm) || CommonUtil.isNullOrEmpty(KdRuangan);
String AlamatUrlForm = request.getHeader(URL_FORM) == null ? "" : request.getHeader(URL_FORM);
String KdRuangan = request.getHeader(KD_RUANGAN) == null ? "" : request.getHeader(KD_RUANGAN);
String idRuanganTujuan = request.getHeader(KD_RUANGAN_T) == null ? "" : request.getHeader(KD_RUANGAN_T);
String idRuanganTujuanA = request.getHeader(KD_RUANGAN_A) == null ? "" : request.getHeader(KD_RUANGAN_A);
String tglKirim = request.getHeader(TGL_KIRIM) == null ? "" : request.getHeader(TGL_KIRIM);
boolean notHttpOK = response.getStatus() >= SC_BAD_REQUEST;
boolean notLewatMenu = isNullOrEmpty(AlamatUrlForm) || isNullOrEmpty(KdRuangan);
Integer ruanganAsalId;
try {
ruanganAsalId = Integer.parseInt(KdRuangan);
} catch (NumberFormatException e) {
ruanganAsalId = 0;
}
boolean adaError = CommonUtil.isNotNullOrEmpty(ex);
boolean adaError = isNotNullOrEmpty(ex);
if (notHttpOK || notLewatMenu || adaError)
return;
Authentication authentication = tokenAuthenticationService.getAuthentication(request);
if (CommonUtil.isNullOrEmpty(authentication))
if (isNullOrEmpty(authentication))
return;
namaUser = authentication.getName();
loginUser = loginUserDao.findByNamaUser(namaUser);
if (CommonUtil.isNullOrEmpty(loginUser))
if (isNullOrEmpty(loginUser))
return;
String potongan = filterUrlForm(AlamatUrlForm);
List<ObjekModulAplikasiVO> objekModulAplikasiVOs = objekModulAplikasiService.findByAlamatUrlForm(potongan);
if (CommonUtil.isNullOrEmpty(objekModulAplikasiVOs))
if (isNullOrEmpty(objekModulAplikasiVOs))
return;
String URI = request.getRequestURI();
Integer objekModulAplikasId = objekModulAplikasiVOs.get(0).getId();
List<NotifMessagingVO> notifMessagingVOs = notifMessagingService
.findByObjekModulAplikasiIdAndUrlBackEndOrUrlBackEndIsNull(objekModulAplikasId, URI);
if (CommonUtil.isNullOrEmpty(notifMessagingVOs))
if (isNullOrEmpty(notifMessagingVOs))
return;
Integer notifMessagingId = notifMessagingVOs.get(0).getId();
if (CommonUtil.isNullOrEmpty(tglKirim)) {
if (isNullOrEmpty(tglKirim)) {
List<Integer> ruanganTujuansId = new ArrayList<>();
if (!"".equals(idRuanganTujuan)) {
JSONArray ruanganTujuanIds = new JSONArray(idRuanganTujuan);
@ -364,4 +362,5 @@ public class AppInterceptor implements HandlerInterceptor {
}
}
}
}

View File

@ -1,43 +1,38 @@
package com.jasamedika.medifirst2000.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.jasamedika.medifirst2000.constants.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import static org.apache.commons.httpclient.HttpStatus.SC_FORBIDDEN;
import static org.slf4j.LoggerFactory.getLogger;
/**
* RestAuthenticationEntryPoint class
* set Unauthorized response from "Unauthorized client"
* RestAuthenticationEntryPoint class set Unauthorized response from
* "Unauthorized client"
*
* @author Roberto
* @author Roberto, Syamsu
*/
@Component("RestAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
/// Alter Syamsu
private static final Logger LOGGER = getLogger(RestAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response, AuthenticationException ae)
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae)
throws IOException, ServletException {
LOGGER.error("Mencoba akses tanpa login");
response.getWriter().write("{" + Constants.MessageInfo.ERROR_MESSAGE + ":'Please login to get access'}");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Please login to get access");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
response.getWriter().write("{" + ERROR_MESSAGE + ":'Please login to get access'}");
response.setHeader(ERROR_MESSAGE, "Please login to get access");
response.setStatus(SC_FORBIDDEN);
}
}

View File

@ -1,10 +1,12 @@
package com.jasamedika.medifirst2000.security;
import com.jasamedika.medifirst2000.filter.StatelessAuthenticationFilter;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@ -13,14 +15,11 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.filter.StatelessAuthenticationFilter;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.security.service.UserService;
import static com.jasamedika.medifirst2000.constants.Constants.JASAMEDIKA;
/**
* SpringSecurityConfig class
* Di sini Kita tidak menggunakan XML Config untuk Spring Security
* SpringSecurityConfig class Di sini Kita tidak menggunakan XML Config untuk
* Spring Security
*
* @author Roberto
*/
@ -29,94 +28,35 @@ import com.jasamedika.medifirst2000.security.service.UserService;
@Order(2)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
@Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
private final UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
public SpringSecurityConfig() {
super(true);
this.userService = new UserService();
tokenAuthenticationService = new TokenAuthenticationService(
Constants.JASAMEDIKA, userService);
tokenAuthenticationService = new TokenAuthenticationService(JASAMEDIKA, userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
//restAuthenticationEntryPoint
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.anonymous()
.and()
.servletApi()
.and()
.headers()
.cacheControl()
.and()
.authorizeRequests()
// Allow anonymous resource requests
.antMatchers("/favicon.ico")
.permitAll()
.antMatchers("**/*.html")
.permitAll()
.antMatchers("**/*.css")
.permitAll()
.antMatchers("**/*.js")
.permitAll()
// Allow anonymous logins
.antMatchers("/auth/**")
.permitAll()
// Allow SMS gateway
.antMatchers("/registrasi-pasien-sms/**")
.permitAll()
// Allow SMS gateway
.antMatchers("/report/**")
.permitAll()
// URL tanpa auth deklarasikan di sini
.antMatchers("/test-tanpa-auth/**")
.permitAll()
.antMatchers("/test/**")
.permitAll()
.antMatchers("/api-docs.json")
.permitAll()
.antMatchers("/api-docs/**")
.permitAll()
/*//Allow Download File Surat Masuk
.antMatchers("/surat-masuk/download-dokumen-template/**")
.permitAll()
.antMatchers("/surat-masuk/get-draft-surat/**")
.permitAll()*/
// All other request need to be authenticated
.anyRequest()
.authenticated()
.and()
// Custom Token based authentication based on the header
// previously given to the client
.addFilterBefore(
new StatelessAuthenticationFilter(
tokenAuthenticationService),
http.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint).and().anonymous().and()
.servletApi().and().headers().cacheControl().and().authorizeRequests().antMatchers("/favicon.ico")
.permitAll().antMatchers("**/*.html").permitAll().antMatchers("**/*.css").permitAll()
.antMatchers("**/*.js").permitAll().antMatchers("/auth/**").permitAll()
.antMatchers("/registrasi-pasien-sms/**").permitAll().antMatchers("/report/**").permitAll()
.antMatchers("/test-tanpa-auth/**").permitAll().antMatchers("/test/**").permitAll()
.antMatchers("/api-docs.json").permitAll().antMatchers("/api-docs/**").permitAll().anyRequest()
.authenticated().and().addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(
new BCryptPasswordEncoder());
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
@ -135,11 +75,5 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
public TokenAuthenticationService tokenAuthenticationService() {
return tokenAuthenticationService;
}
// @Bean(name = "springSecurityFilterChain", autowire = Autowire.BY_NAME)
// public DelegatingFilterProxy springSecurityFilterChain(){
// return new DelegatingFilterProxy();
// }
}

View File

@ -1,40 +1,35 @@
package com.jasamedika.medifirst2000.security.handler;
import com.jasamedika.medifirst2000.security.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.User;
import com.jasamedika.medifirst2000.security.service.UserService;
import static io.jsonwebtoken.SignatureAlgorithm.HS512;
/**
* TokenHandler class
* using jjwt https://github.com/jwtk/jjwt
*
* TokenHandler class using <a href="https://github.com/jwtk/jjwt">jjwt</a>
*
* @author Roberto
*/
public class TokenHandler {
private final String secret;
private final UserService userService;
public TokenHandler(String secret, UserService userService) {
this.secret = secret;
this.userService = userService;
}
private final String secret;
public User parseUserFromToken(String token) {
String username = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
return userService.loadUserByUsername(username);
}
private final UserService userService;
public TokenHandler(String secret, UserService userService) {
this.secret = secret;
this.userService = userService;
}
public User parseUserFromToken(String token) {
String username = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
return userService.loadUserByUsername(username);
}
public String createTokenForUser(User user) {
return Jwts.builder().setHeaderParam("typ", "JWT").setSubject(user.getUsername()).signWith(HS512, secret)
.compact();
}
public String createTokenForUser(User user) {
return Jwts.builder().setHeaderParam("typ", "JWT")
.setSubject(user.getUsername())
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
}

View File

@ -6,20 +6,21 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* AppPermission annotation, digunakan untuk method yang butuh authorized dari database
* can use in method only.
* AppPermission annotation, digunakan untuk method yang butuh authorized dari
* database can use in method only.
*
* @author Roberto
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AppPermission {
public static final int ADD = 100;
public static final int UPDATE = 200;
public static final int DELETE = 300;
public static final int PRINT = 400;
public static final int VIEW = 500;
public static final int SPECIALS = 600;
public @interface AppPermission {
int ADD = 100;
int UPDATE = 200;
int DELETE = 300;
int PRINT = 400;
int VIEW = 500;
int SPECIALS = 600;
int value();
}

View File

@ -1,22 +1,22 @@
package com.jasamedika.medifirst2000.security.model;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
/**
* UserAuthentication class
*
* @author Roberto
*/
public class UserAuthentication implements Authentication {
/**
* serialVersionUID
*/
private static final long serialVersionUID = -7410905698525654537L;
private final User user;
private boolean authenticated = true;
public UserAuthentication(User user) {
@ -57,4 +57,5 @@ public class UserAuthentication implements Authentication {
public void setAuthenticated(boolean authenticated) {
this.authenticated = authenticated;
}
}

View File

@ -1,72 +1,59 @@
package com.jasamedika.medifirst2000.security.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonParseException;
import com.jasamedika.medifirst2000.security.handler.TokenHandler;
import com.jasamedika.medifirst2000.security.model.UserAuthentication;
import lombok.NoArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonParseException;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.security.handler.TokenHandler;
import com.jasamedika.medifirst2000.security.model.UserAuthentication;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import static com.jasamedika.medifirst2000.core.web.WebConstants.AUTH_HEADER_NAME;
/**
* TokenAuthenticationService class
*
* @author Roberto
*/
@NoArgsConstructor
@Component
public class TokenAuthenticationService {
public static TokenHandler tokenHandler;
public TokenAuthenticationService() {
}
public static TokenHandler tokenHandler;
public TokenAuthenticationService(String secret, UserService userService) {
tokenHandler = new TokenHandler(secret, userService);
}
public String addAuthentication(HttpServletResponse response,
UserAuthentication authentication) {
public String addAuthentication(UserAuthentication authentication) {
final User user = authentication.getDetails();
return tokenHandler.createTokenForUser(user);
return tokenHandler.createTokenForUser(user);
}
public Authentication getAuthentication(HttpServletRequest request)
throws JsonParseException {
String token = request.getHeader(WebConstants.AUTH_HEADER_NAME);
public Authentication getAuthentication(HttpServletRequest request) throws JsonParseException {
String token = request.getHeader(AUTH_HEADER_NAME);
if (token != null) {
final User user = tokenHandler.parseUserFromToken(token);
if (user != null) {
if (user != null)
return new UserAuthentication(user);
}
}
else{
try
{
if(request.getQueryString()=="")return null;
final String[] tokens= request.getQueryString().split("&");
for (String tokenTemp : tokens) {
if(tokenTemp.toLowerCase().indexOf(WebConstants.AUTH_HEADER_NAME.toLowerCase())>=0)
{
token =tokenTemp.split("=")[1];
final User user = tokenHandler.parseUserFromToken(token);
if (user != null) {
return new UserAuthentication(user);
}
} else {
if (Objects.equals(request.getQueryString(), ""))
return null;
final String[] tokens = request.getQueryString().split("&");
for (String tokenTemp : tokens) {
if (tokenTemp.toLowerCase().contains(AUTH_HEADER_NAME.toLowerCase())) {
token = tokenTemp.split("=")[1];
final User user = tokenHandler.parseUserFromToken(token);
if (user != null) {
return new UserAuthentication(user);
}
}
}
catch(Exception e)
{
}
}
return null;
}
}

View File

@ -1,29 +1,28 @@
package com.jasamedika.medifirst2000.security.service;
import java.util.Arrays;
import java.util.List;
import com.jasamedika.medifirst2000.dao.LoginUserDao;
import com.jasamedika.medifirst2000.entities.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.jasamedika.medifirst2000.dao.LoginUserDao;
import com.jasamedika.medifirst2000.entities.LoginUser;
import java.util.List;
import static java.util.Collections.singletonList;
/**
* UserService implements
org.springframework.security.core.userdetails.UserDetailsService
* org.springframework.security.core.userdetails.UserDetailsService
*
* @author Roberto
*/
@Component
public class UserService implements
org.springframework.security.core.userdetails.UserDetailsService {
public class UserService implements UserDetailsService {
@Autowired
private LoginUserDao loginUserDao;
@ -34,28 +33,16 @@ public class UserService implements
super();
}
/**
* this method is called for rest authentication from client
*
* @author Roberto
*/
@Override
public final User loadUserByUsername(String username)
throws UsernameNotFoundException {
public final User loadUserByUsername(String username) throws UsernameNotFoundException {
List<LoginUser> loginUsers = loginUserDao.findByNamaUser(username);
if (loginUsers.isEmpty()) {
if (loginUsers.isEmpty())
throw new UsernameNotFoundException("user not found");
}
LoginUser loginUser = loginUsers.get(0);
//validasi tambahan lakukan di sini
// GrantedAuthority authority = new SimpleGrantedAuthority(loginUser
// .getKelompokUser().getKelompokUser());
GrantedAuthority authority = new SimpleGrantedAuthority("USER");
UserDetails userDetails = (UserDetails) new User(
loginUser.getNamaUser(), loginUser.getKataSandi(),
Arrays.asList(authority));
User userDetails = new User(loginUser.getNamaUser(), loginUser.getKataSandi(), singletonList(authority));
detailsChecker.check(userDetails);
return (User) userDetails;
return userDetails;
}
}

View File

@ -1,29 +1,25 @@
package com.jasamedika.medifirst2000.util.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
@NoArgsConstructor
@Component
public class JacksonConfiguration {
private ObjectMapper mapper;
public JacksonConfiguration() {
}
public JacksonConfiguration(ObjectMapper mapper) {
this.mapper = mapper;
configureJackson(mapper);
}
public static ObjectMapper configureJackson(ObjectMapper mapper) {
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
return mapper;
public static void configureJackson(ObjectMapper mapper) {
mapper.enable(INDENT_OUTPUT);
mapper.setSerializationInclusion(NON_NULL);
mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
}
}

View File

@ -1,16 +1,17 @@
package com.jasamedika.medifirst2000.util.rest;
import com.google.gson.Gson;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import com.google.gson.Gson;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
/**
* Rest Util Class
@ -20,67 +21,45 @@ import com.google.gson.Gson;
public class RestUtil {
private static final String CONTENT_TYPE = "Content-Type";
private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
/**
* get JSON response from Object
*
* @param src
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<T> getJsonResponse(T src) {
HttpHeaders headers = new HttpHeaders();
//headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<T>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get JSON response from Object with HTTP status
*
* @param src
*
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<T> getJsonResponse(T src, HttpStatus status) {
HttpHeaders headers = new HttpHeaders();
// headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
Map<String,Object> map=new HashMap<String,Object>();
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
Map<String, Object> map = new HashMap<>();
map.put("data", src);
return new ResponseEntity(map, headers, status);
}
/**
*
* @param src
* @param status
* @param mapHeaderMessage
* @param <T>
* @return
*/
public static <T> ResponseEntity<T> getJsonResponse(T src,
HttpStatus status, Map<String, String> mapHeaderMessage) {
public static <T> ResponseEntity<T> getJsonResponse(T src, HttpStatus status,
Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
if (null != mapHeaderMessage) {
for (String key : mapHeaderMessage.keySet()) {
if (null != mapHeaderMessage)
for (String key : mapHeaderMessage.keySet())
headers.add(key, mapHeaderMessage.get(key));
}
}
Map<String,Object> map=new HashMap<String,Object>();
Map<String, Object> map = new HashMap<>();
map.put("messages", mapHeaderMessage);
map.put("data", src);
//headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity(map, headers, status);
}
@ -91,123 +70,87 @@ public class RestUtil {
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<T> getJsonHttptatus(HttpStatus status) {
return new ResponseEntity<T>(status);
public static <T> ResponseEntity<T> getJsonHttpStatus(HttpStatus status) {
return new ResponseEntity<>(status);
}
public static <T> ResponseEntity<T> getJsonHttptatus(HttpStatus status,
Map<String, String> mapHeaderMessage) {
public static <T> ResponseEntity<T> getJsonHttpStatus(HttpStatus status, Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
if (null != mapHeaderMessage) {
for (String key : mapHeaderMessage.keySet()) {
if (null != mapHeaderMessage)
for (String key : mapHeaderMessage.keySet())
headers.add(key, mapHeaderMessage.get(key));
}
}
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<T>(headers, status);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(headers, status);
}
/**
* get JSON response from Set Object
*
* @param src
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<Set<T>> defaultJsonResponse(Set<T> src) {
HttpHeaders headers = new HttpHeaders();
// headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<Set<T>>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get JSON response from Set Object with custom header
*
* @param src
* @param mapHeaderMessage
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<Set<T>> defaultJsonResponse(Set<T> src, Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
if (null != mapHeaderMessage) {
for (String key : mapHeaderMessage.keySet()) {
if (null != mapHeaderMessage)
for (String key : mapHeaderMessage.keySet())
headers.add(key, mapHeaderMessage.get(key));
}
}// headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<Set<T>>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get JSON response from List Object with custom header
*
* @param src
* @param mapHeaderMessage
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<List<T>> defaultJsonResponse(List<T> src, Map<String, String> mapHeaderMessage) {
HttpHeaders headers = new HttpHeaders();
if (null != mapHeaderMessage) {
for (String key : mapHeaderMessage.keySet()) {
if (null != mapHeaderMessage)
for (String key : mapHeaderMessage.keySet())
headers.add(key, mapHeaderMessage.get(key));
}
}
// headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<List<T>>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get JSON response from List Object
*
* @param src
* @param <T>
* source class
* @return @ResponseEntity
*/
public static <T> ResponseEntity<List<T>> defaultJsonResponse(List<T> src) {
HttpHeaders headers = new HttpHeaders();
// headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<List<T>>(src, headers, HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(src, headers, OK);
}
/**
* get default JSON response from Object
*
* @param src
* @return @ResponseEntity
*/
public static ResponseEntity<String> defaultJsonResponse(Object src) {
Gson gson = new Gson();
HttpHeaders headers = new HttpHeaders();
// headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<String>(gson.toJson(src), headers,
HttpStatus.OK);
headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
return new ResponseEntity<>(gson.toJson(src), headers, OK);
}
/**
@ -217,8 +160,6 @@ public class RestUtil {
* string source JSON
* @param type
* class type result
* @param <T>
* @return
*/
public static <T> T jsonToObject(String strJson, Class<T> type) {
Gson gson = new Gson();
@ -228,8 +169,6 @@ public class RestUtil {
/**
* convert object to json
*
* @param object
* @return
*/
public static String toJson(Object object) {
Gson gson = new Gson();

View File

@ -1,8 +1,10 @@
package com.monitorjbl.json;
public class JsonResult {
private static final JsonResult instance = new JsonResult();
private static final ThreadLocal<JsonView> current = new ThreadLocal<>();
private static final ThreadLocal<JsonView<?>> current = new ThreadLocal<>();
private JsonResult() {
}
@ -16,7 +18,6 @@ public class JsonResult {
* Type of object being rendered
* @return ResultWrapper to provide return value
*/
@SuppressWarnings("unchecked")
public <E> ResultWrapper<E> use(JsonView<E> view) {
current.set(view);
return new ResultWrapper<>(view);
@ -26,7 +27,7 @@ public class JsonResult {
return instance;
}
static JsonView get() {
static JsonView<?> get() {
return current.get();
}
@ -35,7 +36,7 @@ public class JsonResult {
}
public static class ResultWrapper<T> {
private JsonView<T> obj;
private final JsonView<T> obj;
private ResultWrapper(JsonView<T> obj) {
this.obj = obj;
@ -50,4 +51,5 @@ public class JsonResult {
return obj.getValue();
}
}
}

View File

@ -1,18 +1,15 @@
package com.monitorjbl.json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonResultRetriever {
private static final Logger log = LoggerFactory.getLogger(JsonResultRetriever.class);
static boolean hasValue() {
return JsonResult.get() != null;
}
static boolean hasValue() {
return JsonResult.get() != null;
}
static JsonView<?> retrieve() {
JsonView<?> val = JsonResult.get();
JsonResult.unset();
return val;
}
static JsonView retrieve() {
JsonView val = JsonResult.get();
JsonResult.unset();
return val;
}
}

View File

@ -11,23 +11,19 @@ import java.util.List;
public class JsonViewHttpEntityMethodProcessor extends HttpEntityMethodProcessor {
public JsonViewHttpEntityMethodProcessor(List<HttpMessageConverter<?>> converters) {
super(converters);
}
public JsonViewHttpEntityMethodProcessor(List<HttpMessageConverter<?>> converters) {
super(converters);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if(returnValue instanceof ResponseEntity && JsonResultRetriever.hasValue()) {
JsonView json = JsonResultRetriever.retrieve();
ResponseEntity re = (ResponseEntity) returnValue;
returnValue = ResponseEntity.status(re.getStatusCode())
.headers(re.getHeaders())
.body(json);
}
super.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
if (returnValue instanceof ResponseEntity && JsonResultRetriever.hasValue()) {
JsonView<?> json = JsonResultRetriever.retrieve();
ResponseEntity<?> re = (ResponseEntity<?>) returnValue;
returnValue = ResponseEntity.status(re.getStatusCode()).headers(re.getHeaders()).body(json);
}
super.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
}
}

View File

@ -10,26 +10,27 @@ import java.io.IOException;
public class JsonViewMessageConverter extends MappingJackson2HttpMessageConverter {
public JsonViewMessageConverter() {
super();
ObjectMapper defaultMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
defaultMapper.registerModule(module);
setObjectMapper(defaultMapper);
}
public JsonViewMessageConverter() {
super();
ObjectMapper defaultMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
defaultMapper.registerModule(module);
setObjectMapper(defaultMapper);
}
public JsonViewMessageConverter(ObjectMapper mapper) {
super();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
setObjectMapper(mapper);
}
public JsonViewMessageConverter(ObjectMapper mapper) {
super();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
setObjectMapper(mapper);
}
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
super.writeInternal(object, outputMessage);
}
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
super.writeInternal(object, outputMessage);
}
}

View File

@ -6,7 +6,9 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBody
import java.util.List;
public class JsonViewResponseProcessor extends RequestResponseBodyMethodProcessor {
public JsonViewResponseProcessor(List<HttpMessageConverter<?>> messageConverters) {
super(messageConverters);
}
public JsonViewResponseProcessor(List<HttpMessageConverter<?>> messageConverters) {
super(messageConverters);
}
}

View File

@ -11,30 +11,31 @@ import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.List;
public class JsonViewReturnValueHandler implements HandlerMethodReturnValueHandler {
private static final Logger log = LoggerFactory.getLogger(JsonViewReturnValueHandler.class);
private final HandlerMethodReturnValueHandler delegate;
private static final Logger LOGGER = LoggerFactory.getLogger(JsonViewReturnValueHandler.class);
public JsonViewReturnValueHandler(List<HttpMessageConverter<?>> converters) {
this.delegate = new JsonViewResponseProcessor(converters);
}
private final HandlerMethodReturnValueHandler delegate;
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return delegate.supportsReturnType(returnType);
}
public JsonViewReturnValueHandler(List<HttpMessageConverter<?>> converters) {
this.delegate = new JsonViewResponseProcessor(converters);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
Object val = returnValue;
if(JsonResultRetriever.hasValue()) {
val = JsonResultRetriever.retrieve();
log.debug("Found [" + ((JsonView) val).getValue().getClass() + "] to serialize");
} else {
log.debug("No JsonView found for thread, using returned value");
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return delegate.supportsReturnType(returnType);
}
delegate.handleReturnValue(val, returnType, mavContainer, webRequest);
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
Object val = returnValue;
if (JsonResultRetriever.hasValue()) {
val = JsonResultRetriever.retrieve();
LOGGER.debug("Found [{}] to serialize", ((JsonView<?>) val).getValue().getClass());
} else {
LOGGER.debug("No JsonView found for thread, using returned value");
}
delegate.handleReturnValue(val, returnType, mavContainer, webRequest);
}
}

View File

@ -15,38 +15,39 @@ import java.util.List;
public class JsonViewSupportFactoryBean implements InitializingBean {
@Autowired
private RequestMappingHandlerAdapter adapter;
private final JsonViewMessageConverter converter;
@Autowired
private RequestMappingHandlerAdapter adapter;
public JsonViewSupportFactoryBean() {
this(new ObjectMapper());
}
private final JsonViewMessageConverter converter;
public JsonViewSupportFactoryBean(ObjectMapper mapper) {
this.converter = new JsonViewMessageConverter(mapper.copy());
}
public JsonViewSupportFactoryBean() {
this(new ObjectMapper());
}
@Override
public void afterPropertiesSet() throws Exception {
List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(adapter.getReturnValueHandlers());
adapter.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
decorateHandlers(handlers);
adapter.setReturnValueHandlers(handlers);
}
public JsonViewSupportFactoryBean(ObjectMapper mapper) {
this.converter = new JsonViewMessageConverter(mapper.copy());
}
private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
List<HttpMessageConverter<?>> converters = new ArrayList<>(adapter.getMessageConverters());
converters.add(converter);
for(HandlerMethodReturnValueHandler handler : handlers) {
int index = handlers.indexOf(handler);
if(handler instanceof HttpEntityMethodProcessor) {
handlers.set(index, new JsonViewHttpEntityMethodProcessor(converters));
} else if(handler instanceof RequestResponseBodyMethodProcessor) {
handlers.set(index, new JsonViewReturnValueHandler(converters));
break;
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(adapter.getReturnValueHandlers());
adapter.setMessageConverters(Collections.singletonList(converter));
decorateHandlers(handlers);
adapter.setReturnValueHandlers(handlers);
}
private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
List<HttpMessageConverter<?>> converters = new ArrayList<>(adapter.getMessageConverters());
converters.add(converter);
for (HandlerMethodReturnValueHandler handler : handlers) {
int index = handlers.indexOf(handler);
if (handler instanceof HttpEntityMethodProcessor) {
handlers.set(index, new JsonViewHttpEntityMethodProcessor(converters));
} else if (handler instanceof RequestResponseBodyMethodProcessor) {
handlers.set(index, new JsonViewReturnValueHandler(converters));
break;
}
}
}
}

View File

@ -15,7 +15,7 @@
</context-param>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>mirroring</param-value>
<param-value>localhost</param-value>
</context-param>
<listener>

View File

@ -18,7 +18,7 @@ import static org.slf4j.LoggerFactory.getLogger;
* RestAuthenticationEntryPoint class set Unauthorized response from
* "Unauthorized client"
*
* @author Roberto
* @author Roberto, Syamsu
*/
@Component("RestAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {