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

@ -18,16 +18,16 @@
<artifactId>socket.io-client</artifactId> <artifactId>socket.io-client</artifactId>
<version>0.7.0</version> <version>0.7.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.5.2</version> <version>4.5.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-httpclient</groupId> <groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>
<version>3.1</version> <version>3.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
<artifactId>jasamedika-config</artifactId> <artifactId>jasamedika-config</artifactId>
@ -260,11 +260,16 @@
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<!-- <dependency> <!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<groupId>org.codehaus.groovy</groupId> <version>1.8.4</version> </dependency> -->
<artifactId>groovy-all</artifactId>
<version>1.8.4</version> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
</dependency> --> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${project.lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -10,12 +10,12 @@
<version>1.0.0</version> <version>1.0.0</version>
<relativePath>../Medifirst2000/pom.xml</relativePath> <relativePath>../Medifirst2000/pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>commons-httpclient</groupId> <groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>
<version>3.1</version> <version>3.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.socket</groupId> <groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId> <artifactId>socket.io-client</artifactId>
@ -251,11 +251,8 @@
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<!-- <dependency> <!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<groupId>org.codehaus.groovy</groupId> <version>1.8.4</version> </dependency> -->
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
@ -268,6 +265,14 @@
<version>${commons-collections.version}</version> <version>${commons-collections.version}</version>
</dependency> </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> </dependencies>
<build> <build>

View File

@ -10,12 +10,12 @@
<version>1.0.0</version> <version>1.0.0</version>
<relativePath>../Medifirst2000/pom.xml</relativePath> <relativePath>../Medifirst2000/pom.xml</relativePath>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>commons-httpclient</groupId> <groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>
<version>3.1</version> <version>3.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.socket</groupId> <groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId> <artifactId>socket.io-client</artifactId>
@ -251,11 +251,8 @@
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<!-- <dependency> <!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<groupId>org.codehaus.groovy</groupId> <version>1.8.4</version> </dependency> -->
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
@ -268,6 +265,14 @@
<version>${commons-collections.version}</version> <version>${commons-collections.version}</version>
</dependency> </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> </dependencies>
<build> <build>

View File

@ -15,7 +15,7 @@
<groupId>commons-httpclient</groupId> <groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>
<version>3.1</version> <version>3.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.socket</groupId> <groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId> <artifactId>socket.io-client</artifactId>
@ -251,11 +251,8 @@
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<!-- <dependency> <!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<groupId>org.codehaus.groovy</groupId> <version>1.8.4</version> </dependency> -->
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
@ -268,6 +265,14 @@
<version>${commons-collections.version}</version> <version>${commons-collections.version}</version>
</dependency> </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> </dependencies>
<build> <build>

View File

@ -15,7 +15,7 @@
<groupId>commons-httpclient</groupId> <groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>
<version>3.1</version> <version>3.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.socket</groupId> <groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId> <artifactId>socket.io-client</artifactId>
@ -251,11 +251,8 @@
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<!-- <dependency> <!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<groupId>org.codehaus.groovy</groupId> <version>1.8.4</version> </dependency> -->
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
@ -268,6 +265,14 @@
<version>${commons-collections.version}</version> <version>${commons-collections.version}</version>
</dependency> </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> </dependencies>
<build> <build>
<finalName>jasamedika-k3kl</finalName> <finalName>jasamedika-k3kl</finalName>

View File

@ -15,7 +15,7 @@
<groupId>commons-httpclient</groupId> <groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>
<version>3.1</version> <version>3.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.socket</groupId> <groupId>io.socket</groupId>
<artifactId>socket.io-client</artifactId> <artifactId>socket.io-client</artifactId>
@ -251,11 +251,8 @@
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<!-- <dependency> <!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<groupId>org.codehaus.groovy</groupId> <version>1.8.4</version> </dependency> -->
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
@ -268,6 +265,14 @@
<version>${commons-collections.version}</version> <version>${commons-collections.version}</version>
</dependency> </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> </dependencies>
<build> <build>

View File

@ -265,6 +265,14 @@
<version>${commons-collections.version}</version> <version>${commons-collections.version}</version>
</dependency> </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> </dependencies>
<build> <build>

View File

@ -9,70 +9,56 @@ import java.text.SimpleDateFormat;
* @author Roberto * @author Roberto
*/ */
public class Constants { public class Constants {
public static final String JASAMEDIKA = "SkFTQU1FRElLQQ=="; public static final String JASAMEDIKA = "SkFTQU1FRElLQQ==";
public static final String APP_VERSION = "APP_VERSION"; public static final String APP_VERSION = "APP_VERSION";
public static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN"; public static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN";
//for example
public static final String IDR = "IDR"; public static final String IDR = "IDR";
public static final String RP = "RP"; public static final String RP = "RP";
public static final String COMMA = ","; public static final String COMMA = ",";
public static final DecimalFormat ONE_COMA_FORMAT = new DecimalFormat("#.#"); 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 class DateFormat {
public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat( public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
"yyyyMMdd"); public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat("dd MMM yyyy");
public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat( public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
"dd MMM yyyy"); public static final SimpleDateFormat yyyy_MM_dd_T_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat( public static final SimpleDateFormat yyyyMMdd_HH_mm_ss = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
"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 class MessageInfo {
public static final String INFO_MESSAGE = "INFO_MESSAGE"; public static final String INFO_MESSAGE = "INFO_MESSAGE";
public static final String WARNING_MESSAGE = "WARNING_MESSAGE"; public static final String WARNING_MESSAGE = "WARNING_MESSAGE";
public static final String ERROR_MESSAGE = "ERROR_MESSAGE"; public static final String ERROR_MESSAGE = "ERROR_MESSAGE";
public static final String EXCEPTION_MESSAGE = "EXCEPTION_MESSAGE"; public static final String EXCEPTION_MESSAGE = "EXCEPTION_MESSAGE";
} }
/* locale id (indonesia / default) and en (english) */
public static final class Locale { public static final class Locale {
public static final String INA = "ina"; public static final String INA = "ina";
public static final String EN = "en"; 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 class HttpHeader {
public static final String SUPERVISING = "Supervising"; public static final String SUPERVISING = "Supervising";
public static final String MODULE = "Module"; public static final String MODULE = "Module";
public static final String FORM = "Form"; public static final String FORM = "Form";
public static final String ACTION = "Action"; public static final String ACTION = "Action";
public static final String URL_FORM = "AlamatUrlForm";
public static final String URL_FORM = "AlamatUrlForm"; // syamsu public static final String KD_RUANGAN = "KdRuangan";
public static final String KD_RUANGAN = "KdRuangan"; // syamsu public static final String KD_RUANGAN_T = "KdRuanganT";
public static final String KD_RUANGAN_T = "KdRuanganT"; // syamsu public static final String KD_RUANGAN_A = "KdRuanganA";
public static final String KD_RUANGAN_A = "KdRuanganA"; // syamsu public static final String TGL_KIRIM = "tglKirim";
public static final String TGL_KIRIM = "tglKirim"; // syamsu public static final String KD_USER = "KdUser";
// 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
} }
} }

View File

@ -9,10 +9,13 @@ package com.jasamedika.medifirst2000.constants;
public final class MessageResource { public final class MessageResource {
public static final String LABEL_SUCCESS = "label.success"; public static final String LABEL_SUCCESS = "label.success";
public static final String LABEL_ERROR = "label.error"; public static final String LABEL_ERROR = "label.error";
public static final String LABEL_TRY_AGAIN = "label.try_again"; 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_CREATED = "label.success.created";
public static final String LABEL_SUCCESS_OK = "label.success.ok"; 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; package com.jasamedika.medifirst2000.controller;
import java.util.HashMap; import com.jasamedika.medifirst2000.constants.MessageResource;
import java.util.List; import com.jasamedika.medifirst2000.controller.base.LocaleController;
import java.util.Map; import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.MapRuanganToAkomodasiService;
import javax.servlet.http.HttpServletRequest; import com.jasamedika.medifirst2000.service.RuanganService;
import javax.validation.Valid; 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.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; 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.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException; import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; 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.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.jasamedika.medifirst2000.constants.Constants; import javax.servlet.http.HttpServletRequest;
import com.jasamedika.medifirst2000.constants.MessageResource; import javax.validation.Valid;
import com.jasamedika.medifirst2000.controller.base.LocaleController; import java.util.HashMap;
import com.jasamedika.medifirst2000.core.web.WebConstants; import java.util.List;
import com.jasamedika.medifirst2000.exception.ServiceVOException; import java.util.Map;
import com.jasamedika.medifirst2000.service.MapRuanganToAkomodasiService;
import com.jasamedika.medifirst2000.service.RuanganService; import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import com.jasamedika.medifirst2000.util.CommonUtil; import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import com.jasamedika.medifirst2000.util.rest.RestUtil; import static com.jasamedika.medifirst2000.util.CommonUtil.isNotNullOrEmpty;
import com.jasamedika.medifirst2000.vo.MapRuanganToAkomodasiVO; 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 @RestController
@RequestMapping("/akomodasi") @RequestMapping("/akomodasi")
public class AkomodasiController extends LocaleController<MapRuanganToAkomodasiVO> { public class AkomodasiController extends LocaleController<MapRuanganToAkomodasiVO> {
private static final Logger LOGGER = LoggerFactory.getLogger(AkomodasiController.class); private static final Logger LOGGER = getLogger(AkomodasiController.class);
@Autowired @Autowired
private MapRuanganToAkomodasiService mapRuanganToAkomodasiService; private MapRuanganToAkomodasiService mapRuanganToAkomodasiService;
@Autowired @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, public ResponseEntity<Map<String, Object>> saveMappingAkomodasi(HttpServletRequest request,
@Valid @RequestBody MapRuanganToAkomodasiVO vo) { @Valid @RequestBody MapRuanganToAkomodasiVO vo) {
Map<String, Object> result = new HashMap<String, Object>(); Map<String, Object> result = new HashMap<>();
try { try {
MapRuanganToAkomodasiVO resultVo = new MapRuanganToAkomodasiVO(); MapRuanganToAkomodasiVO resultVo;
if (CommonUtil.isNotNullOrEmpty(vo.getId())) { if (isNotNullOrEmpty(vo.getId())) {
resultVo = mapRuanganToAkomodasiService.update(vo); resultVo = mapRuanganToAkomodasiService.update(vo);
} else { } else {
resultVo = mapRuanganToAkomodasiService.add(vo); resultVo = mapRuanganToAkomodasiService.add(vo);
} }
result.put("data", resultVo); result.put("data", resultVo);
if (CommonUtil.isNotNullOrEmpty(result)) { if (isNotNullOrEmpty(result)) {
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, CREATED, mapHeaderMessage);
return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage);
} else { } else {
return RestUtil.getJsonHttptatus(HttpStatus.NOT_ACCEPTABLE); return getJsonHttpStatus(NOT_ACCEPTABLE);
} }
} catch (ServiceVOException sve) { } catch (ServiceVOException sve) {
LOGGER.error("Got exception {} when add mapping akomodasi", sve.getMessage()); LOGGER.error("Got ServiceVOException {} when mapRuanganToAkomodasiService.update/add", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when add mapping akomodasi", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when mapRuanganToAkomodasiService.update/add", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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) { public ResponseEntity<String> deleteMappingAkomodasi(HttpServletRequest request, @RequestParam("id") Integer id) {
try { try {
Boolean result = mapRuanganToAkomodasiService.delete(id); Boolean result = mapRuanganToAkomodasiService.delete(id);
if (result) { if (result) {
return RestUtil.getJsonResponse("Mapping is deleted successsfully", HttpStatus.OK); return getJsonResponse("Mapping is deleted successsfully", OK);
} else { } else {
return RestUtil.getJsonHttptatus(HttpStatus.NOT_ACCEPTABLE); return getJsonHttpStatus(NOT_ACCEPTABLE);
} }
} catch (ServiceVOException sve) { } catch (ServiceVOException sve) {
LOGGER.error("Got exception {} when delete mapping akomodasi", sve.getMessage()); LOGGER.error("Got ServiceVOException {} when mapRuanganToAkomodasiService.delete", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when delete mapping akomodasi", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when mapRuanganToAkomodasiService.delete", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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) { public ResponseEntity<List<MapRuanganToAkomodasiVO>> getAllMappingAkomodasi(HttpServletRequest request) {
try { try {
List<MapRuanganToAkomodasiVO> result = mapRuanganToAkomodasiService.getAllActiveAkomodasi(); List<MapRuanganToAkomodasiVO> result = mapRuanganToAkomodasiService.getAllActiveAkomodasi();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException sve) { } catch (ServiceVOException sve) {
LOGGER.error("Got exception {} when get all mapping akomodasi", sve.getMessage()); LOGGER.error("Got ServiceVOException {} when getAllActiveAkomodasi", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when get all mapping akomodasi", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when getAllActiveAkomodasi", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
} }
} }
@RequestMapping(value = "/get-mapping", method = RequestMethod.GET) @RequestMapping(value = "/get-mapping", method = GET)
public ResponseEntity<MapRuanganToAkomodasiVO> getMappingAkomodasi(HttpServletRequest request, public ResponseEntity<MapRuanganToAkomodasiVO> getMappingAkomodasi(HttpServletRequest request,
@RequestParam("id") Integer id) { @RequestParam("id") Integer id) {
try { try {
MapRuanganToAkomodasiVO result = mapRuanganToAkomodasiService.findById(id); MapRuanganToAkomodasiVO result = mapRuanganToAkomodasiService.findById(id);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException sve) { } catch (ServiceVOException sve) {
LOGGER.error("Got exception {} when get all mapping akomodasi", sve.getMessage()); LOGGER.error("Got ServiceVOException {} when mapRuanganToAkomodasiService.findById", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when get all mapping akomodasi", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when mapRuanganToAkomodasiService.findById", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<List<Map<String, Object>>> getKamarByRuangan(HttpServletRequest request,
@RequestParam(value = "idRuangan", required = true) Integer idRuangan) { @RequestParam(value = "idRuangan") Integer idRuangan) {
List<Map<String, Object>> result = null;
try { try {
result = ruanganService.findKamarByRuangan(idRuangan); List<Map<String, Object>> result = ruanganService.findKamarByRuangan(idRuangan);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK);
} catch (Exception e) { } 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, public ResponseEntity<List<Map<String, Object>>> getAkomodasiRuanganByMappingProduk(HttpServletRequest request,
@RequestParam(value = "idRuangan", required = true) Integer idRuangan) { @RequestParam(value = "idRuangan") Integer idRuangan) {
List<Map<String, Object>> result = null;
try { try {
result = mapRuanganToAkomodasiService.getAkomodasiRuanganByMapProduk(idRuangan); List<Map<String, Object>> result = mapRuanganToAkomodasiService.getAkomodasiRuanganByMapProduk(idRuangan);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK);
} catch (Exception e) { } 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; package com.jasamedika.medifirst2000.controller;
import java.io.UnsupportedEncodingException; import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import java.lang.reflect.Field; import com.jasamedika.medifirst2000.controller.base.LocaleController;
import java.net.URLDecoder; import com.jasamedika.medifirst2000.exception.ServiceVOException;
import java.util.ArrayList; import com.jasamedika.medifirst2000.service.ModelService;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map; 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.Column;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.servlet.http.HttpServletRequest; 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 static com.jasamedika.medifirst2000.util.JsonUtil.ToMaps;
import org.springframework.beans.factory.annotation.Autowired; import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import org.springframework.http.HttpHeaders; import static java.net.URLDecoder.decode;
import org.springframework.http.HttpStatus; import static org.springframework.http.HttpStatus.CREATED;
import org.springframework.http.MediaType; import static org.springframework.http.HttpStatus.OK;
import org.springframework.http.ResponseEntity; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import org.springframework.web.bind.annotation.RequestMapping; import static org.springframework.web.bind.annotation.RequestMethod.GET;
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;
@RestController @RestController
@RequestMapping("/service") @RequestMapping("/service")
public class GenericServiceController extends LocaleController<AntrianPasienRegistrasiVO> { public class GenericServiceController extends LocaleController<BaseModelVO> {
private static final String CONTENT_TYPE = "Content-Type";
@Autowired @Autowired
private ModelService<?> modelService; private ModelService<?> modelService;
private static final String CONTENT_TYPE = "Content-Type";
@SuppressWarnings("rawtypes") @RequestMapping(value = "/get-setting/", method = GET, produces = APPLICATION_JSON_VALUE)
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)
public ResponseEntity<String> getData(@RequestParam(value = "prefix", required = false) String prefix) { public ResponseEntity<String> getData(@RequestParam(value = "prefix", required = false) String prefix) {
return getJsonResponse(GetSettingDataFixed(prefix), CREATED, mapHeaderMessage);
return RestUtil.getJsonResponse(GetSettingDataFixed(prefix), HttpStatus.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( public ResponseEntity<List<Map<String, Object>>> listGeneric(
@RequestParam(value = "view", required = false) String entity, @RequestParam(value = "view", required = false) String entity,
@RequestParam(value = "select", required = false) String field, @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 = "filter[filters][0][ignoreCase]", required = false) String ignorecase,
@RequestParam(value = "criteria", required = false) String criteria, @RequestParam(value = "criteria", required = false) String criteria,
@RequestParam(value = "values", required = false) String values, HttpServletRequest request) @RequestParam(value = "values", required = false) String values, HttpServletRequest request)
throws SecurityException, ClassNotFoundException, JSONException, UnsupportedEncodingException { throws SecurityException, ClassNotFoundException {
String data = request.getQueryString(); String data = request.getQueryString();
data = URLDecoder.decode(data, "UTF-8"); data = decode(data);
String[] arrQueries = data.split("&"); String[] arrQueries = data.split("&");
StringBuilder criteriaBuilder = new StringBuilder(criteria);
StringBuilder valuesBuilder = new StringBuilder(values);
for (String query : arrQueries) { for (String query : arrQueries) {
if (query.indexOf("filter[filters][0][filter][field]") >= 0) { if (query.contains("filter[filters][0][filter][field]")) {
if (criteria == null) criteriaBuilder.append(",").append(query.replace("filter[filters][0][filter][field]=", ""));
criteria = query.replace("filter[filters][0][filter][field]=", ""); } else if (query.contains("filter[filters][0][filter][value]")) {
else valuesBuilder.append(",").append(query.replace("filter[filters][0][filter][value]=", ""));
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]=", "");
} }
} }
values = valuesBuilder.toString();
criteria = criteriaBuilder.toString();
if (field.equals("*")) { if (field.equals("*")) {
field = ""; StringBuilder fieldBuilder = new StringBuilder();
for (Field fieldItem : GetFields(Class.forName("com.jasamedika.medifirst2000.entities." + entity))) { for (Field fieldItem : GetFields(Class.forName("com.jasamedika.medifirst2000.entities." + entity))) {
{
String name = fieldItem.getName(); String name = fieldItem.getName();
if (name.equals("serialVersionsUID")) if (name.equals("serialVersionsUID"))
continue; continue;
Boolean valid = false; boolean valid = false;
for (java.lang.annotation.Annotation annotation : fieldItem.getDeclaredAnnotations()) { for (Annotation annotation : fieldItem.getDeclaredAnnotations()) {
if (annotation instanceof JoinColumn) { if (annotation instanceof JoinColumn) {
valid = true; valid = true;
} else if (annotation instanceof Column) { } else if (annotation instanceof Column) {
Column column = (Column) annotation; Column column = (Column) annotation;
if (column.name().endsWith("Fk")) if (column.name().endsWith("Fk"))
if (fieldItem.getName().endsWith("Id") == false) if (!fieldItem.getName().endsWith("Id"))
valid = true; valid = true;
} else if (annotation instanceof OneToMany) { } else if (annotation instanceof OneToMany) {
valid = true; valid = true;
} }
} }
if (valid == false) if (!valid)
if (field.equals("")) if (fieldBuilder.toString().isEmpty())
field += fieldItem.getName(); fieldBuilder.append(fieldItem.getName());
else else
field += "," + fieldItem.getName(); fieldBuilder.append(",").append(fieldItem.getName());
}
} }
field = fieldBuilder.toString();
} else if (field.equals("**")) { } else if (field.equals("**")) {
field = "*"; field = "*";
} }
// for dateformat using [date]
List<Map<String, Object>> modelGenericVO = modelService.getAllData(entity, field, take, skip, page, pageSize, List<Map<String, Object>> modelGenericVO = modelService.getAllData(entity, field, take, skip, page, pageSize,
logic, value, fieldS, operator, ignorecase, criteria, values); logic, value, fieldS, operator, ignorecase, criteria, values);
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); headers.set(CONTENT_TYPE, APPLICATION_JSON_VALUE);
try { try {
return new ResponseEntity<List<Map<String, Object>>>(JsonUtil.ToMaps(modelGenericVO), headers, return new ResponseEntity<>(ToMaps(modelGenericVO), headers, OK);
HttpStatus.OK);
} catch (IllegalArgumentException | IllegalAccessException e) { } 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; 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.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import javax.validation.Valid; import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_ERROR;
import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import org.slf4j.Logger; import static com.jasamedika.medifirst2000.util.rest.RestUtil.*;
import org.slf4j.LoggerFactory; import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import org.springframework.beans.factory.annotation.Autowired; import static org.slf4j.LoggerFactory.getLogger;
import org.springframework.http.HttpStatus; import static org.springframework.http.HttpStatus.*;
import org.springframework.http.MediaType; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import org.springframework.http.ResponseEntity; import static org.springframework.web.bind.annotation.RequestMethod.GET;
import org.springframework.orm.jpa.JpaSystemException; import static org.springframework.web.bind.annotation.RequestMethod.POST;
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;
/** /**
* Controller class for KonsultasiController * Controller class for KonsultasiController
@ -42,45 +40,41 @@ import com.jasamedika.medifirst2000.vo.KonsultasiVO;
@RestController @RestController
@RequestMapping("/konsultasi") @RequestMapping("/konsultasi")
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class KonsultasiController extends LocaleController<KonsultasiVO> implements public class KonsultasiController extends LocaleController<AntrianPasienDiPeriksaVO> {
IBaseRestController<KonsultasiVO> {
private static final Logger LOGGER = LoggerFactory.getLogger(KonsultasiController.class); private static final Logger LOGGER = getLogger(KonsultasiController.class);
@Autowired @Autowired
private KonsultasiService konsultasiService; private KonsultasiService<KonsultasiVO> konsultasiService;
@Autowired @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) @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) { public ResponseEntity<Map<String, Object>> save(@Valid @RequestBody KonsultasiVO vo, HttpServletRequest request) {
try { try {
Map<String,Object> result = konsultasiService.addKonsultasi2(vo); Map<String, Object> result = konsultasiService.addKonsultasi2(vo);
if (null != result){
mapHeaderMessage.clear(); mapHeaderMessage.clear();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request )); if (null != result) {
}else{ mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
mapHeaderMessage.clear(); } else {
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_ERROR,getMessage(MessageResource.LABEL_ERROR,request )); mapHeaderMessage.put(LABEL_ERROR, getMessage(MessageResource.LABEL_ERROR, request));
} }
SaveLog("Konsultasi", "Dokter",request); SaveLog("Konsultasi", "Dokter");
return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage); return getJsonResponse(result, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got exception {} when add kebutuhan dasar", e.getMessage()); LOGGER.error("Got ServiceVOException {} when addKonsultasi2", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when add kebutuhan dasar", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when addKonsultasi2", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
}
} }
} @RequestMapping(value = "/antrian-pasien-list-konsul/", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<AntrianPasienDiPeriksaVO>> getAllVOWithQueryString(
@RequestMapping(value = "/antrian-pasien-list-konsul/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<GridAntrianPasienDiPeriksaVO>> getAllVOWithQueryString(
@RequestParam(value = "page", required = false, defaultValue = "1") Integer page, @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
@RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit, @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit,
@RequestParam(value = "sort", required = false, defaultValue = "noRec") String sort, @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 = "dateEnd", required = false) String dateEnd,
@RequestParam(value = "noCm", required = false) String noCm, @RequestParam(value = "noCm", required = false) String noCm,
@RequestParam(value = "pegawaiId", required = false) Integer pegawaiId) { @RequestParam(value = "pegawaiId", required = false) Integer pegawaiId) {
Map<String, Object> resultPageMap = registrasiPelayananService.findAllAntrianPagingKonsultasi(page, limit, sort, dir, Map<String, Object> resultPageMap = registrasiPelayananService.findAllAntrianPagingKonsultasi(page, limit, sort,
ruanganId, dateStart, dateEnd, noCm, pegawaiId); dir, ruanganId, dateStart, dateEnd, noCm, pegawaiId);
return constructListPageResult(resultPageMap); return constructListPageResult(resultPageMap);
} }
@Override @RequestMapping(value = "/get-riwayat-konsultasi/{noCm}/{startDate}/{endDate}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<KonsultasiVO>> getAllVOWithQueryString(HttpServletRequest request, public ResponseEntity<List<Map<String, Object>>> getRiwayatKonsultasi(@PathVariable("noCm") String noCm,
Integer page, Integer limit, String sort, String dir) { @PathVariable("startDate") String startDate, @PathVariable("endDate") String endDate,
return null; HttpServletRequest request) {
}
@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;
try { try {
List<Map<String, Object>> result = konsultasiService.getRiwayatKonsultasi(noCm, startDate, endDate);
result = konsultasiService.getRiwayatKonsultasi(noCm, startDate, endDate); mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return getJsonResponse(result, OK);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,
getMessage(MessageResource.LABEL_SUCCESS, request));
} catch (Exception e) { } 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; package com.jasamedika.medifirst2000.controller;
import com.jasamedika.medifirst2000.controller.base.LocaleController; import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.vo.MapProdukPaketToProdukVO;
import com.jasamedika.medifirst2000.exception.ServiceVOException; import com.jasamedika.medifirst2000.exception.ServiceVOException;
import com.jasamedika.medifirst2000.service.MapProdukPaketToProdukService; 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.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@ -18,6 +16,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonResponse;
import static org.springframework.http.HttpStatus.*; import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; 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.GET;
@ -31,6 +30,7 @@ import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController @RestController
@RequestMapping("/paket-tindakan") @RequestMapping("/paket-tindakan")
public class MapProdukPaketController extends LocaleController<MapProdukPaketToProdukVO> { public class MapProdukPaketController extends LocaleController<MapProdukPaketToProdukVO> {
@Autowired @Autowired
private MapProdukPaketToProdukService mapProdukPaketToProdukService; private MapProdukPaketToProdukService mapProdukPaketToProdukService;
@ -40,11 +40,11 @@ public class MapProdukPaketController extends LocaleController<MapProdukPaketToP
mapProdukPaketToProdukService.save(vo); mapProdukPaketToProdukService.save(vo);
Map<String, String> message = new HashMap<>(); Map<String, String> message = new HashMap<>();
message.put(CREATED.getReasonPhrase(), "Berhasil tersimpan"); message.put(CREATED.getReasonPhrase(), "Berhasil tersimpan");
return RestUtil.getJsonResponse(vo, CREATED, message); return getJsonResponse(vo, CREATED, message);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
Map<String, String> error = new HashMap<>(); Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage()); 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(); List<MapProdukPaketToProdukVO> data = mapProdukPaketToProdukService.get();
Map<String, String> message = new HashMap<>(); Map<String, String> message = new HashMap<>();
message.put(OK.getReasonPhrase(), "Berhasil"); message.put(OK.getReasonPhrase(), "Berhasil");
return RestUtil.getJsonResponse(data, OK, message); return getJsonResponse(data, OK, message);
} }
@RequestMapping(value = "/{paketId}", method = GET) @RequestMapping(value = "/{paketId}", method = GET)
@ -61,7 +61,7 @@ public class MapProdukPaketController extends LocaleController<MapProdukPaketToP
List<MapProdukPaketToProdukVO> data = mapProdukPaketToProdukService.get(paketId); List<MapProdukPaketToProdukVO> data = mapProdukPaketToProdukService.get(paketId);
Map<String, String> message = new HashMap<>(); Map<String, String> message = new HashMap<>();
message.put(OK.getReasonPhrase(), "Berhasil"); message.put(OK.getReasonPhrase(), "Berhasil");
return RestUtil.getJsonResponse(data, OK, message); return getJsonResponse(data, OK, message);
} }
@RequestMapping(value = "/{noRec}", method = GET) @RequestMapping(value = "/{noRec}", method = GET)
@ -69,7 +69,7 @@ public class MapProdukPaketController extends LocaleController<MapProdukPaketToP
MapProdukPaketToProdukVO data = mapProdukPaketToProdukService.get(noRec); MapProdukPaketToProdukVO data = mapProdukPaketToProdukService.get(noRec);
Map<String, String> message = new HashMap<>(); Map<String, String> message = new HashMap<>();
message.put(OK.getReasonPhrase(), "Berhasil"); 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) @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); boolean status = mapProdukPaketToProdukService.delete(noRec);
Map<String, String> message = new HashMap<>(); Map<String, String> message = new HashMap<>();
message.put(OK.getReasonPhrase(), "Berhasil"); 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; package com.jasamedika.medifirst2000.controller;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.constants.MessageResource; import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController; 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.BatalPaketProdukDto;
import com.jasamedika.medifirst2000.dto.TagihanPendaftaranDto; import com.jasamedika.medifirst2000.dto.TagihanPendaftaranDto;
import com.jasamedika.medifirst2000.exception.ServiceVOException; 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.MapProdukPaketVO;
import com.jasamedika.medifirst2000.vo.PelayananPasienVO; import com.jasamedika.medifirst2000.vo.PelayananPasienVO;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; 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.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException; import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -26,11 +21,20 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; 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 @RestController
@RequestMapping("/pelayanan") @RequestMapping("/pelayanan")
public class PelayananController extends LocaleController<PelayananPasienVO> { public class PelayananController extends LocaleController<PelayananPasienVO> {
private static final Logger LOGGER = LoggerFactory.getLogger(PelayananController.class); private static final Logger LOGGER = getLogger(PelayananController.class);
@Autowired @Autowired
private PelayananPasienService pelayananPasienService; private PelayananPasienService pelayananPasienService;
@ -50,275 +54,262 @@ public class PelayananController extends LocaleController<PelayananPasienVO> {
@Autowired @Autowired
private MapProdukPaketToProdukService mapProdukPaketToProdukService; 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, public ResponseEntity<List<Map<String, Object>>> calculateIndikatorPelayanan(HttpServletRequest request,
@RequestParam("tahun") String tahun) { @RequestParam("tahun") String tahun) {
try { try {
List<Map<String, Object>> result = pasienDaftarService.findIndikatorPelayanan(tahun); List<Map<String, Object>> result = pasienDaftarService.findIndikatorPelayanan(tahun);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException sve) { } catch (ServiceVOException sve) {
LOGGER.error("Got ServiceVOException {} when calculate indikator pelayanan", sve.getMessage()); LOGGER.error("Got ServiceVOException {} when findIndikatorPelayanan", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when calculate indikator pelayanan", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when findIndikatorPelayanan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<Map<String, Object>> validateNamaProduk(HttpServletRequest request,
@RequestParam(value = "idProduk", required = false) Integer idProduk, @RequestParam(value = "idProduk", required = false) Integer idProduk,
@RequestParam(value = "namaProduk") String namaProduk) { @RequestParam(value = "namaProduk") String namaProduk) {
try { try {
Map<String, Object> result = produkService.validateNamaProduk(idProduk, namaProduk); Map<String, Object> result = produkService.validateNamaProduk(idProduk, namaProduk);
return getJsonResponse(result, OK);
return RestUtil.getJsonResponse(result, HttpStatus.OK);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when validate nama produk", e.getMessage()); LOGGER.error("Got ServiceVOException {} when validateNamaProduk", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when validate nama produk", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when validateNamaProduk", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<Map<String, Object>> getMappingPaketToProduk(HttpServletRequest request,
@RequestParam(value = "idMapping") Integer idMapping) { @RequestParam(value = "idMapping") Integer idMapping) {
try { try {
Map<String, Object> result = produkService.getMappingPaketToProduk(idMapping); Map<String, Object> result = produkService.getMappingPaketToProduk(idMapping);
return RestUtil.getJsonResponse(result, HttpStatus.OK); return getJsonResponse(result, OK);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when get mapping paket to produk", e.getMessage()); LOGGER.error("Got ServiceVOException {} when getMappingPaketToProduk", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when get mapping paket to produk", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when getMappingPaketToProduk", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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) { public ResponseEntity<List<Map<String, Object>>> getAllPaketToProduk(HttpServletRequest request) {
try { try {
List<Map<String, Object>> result = produkService.getAllPaketToProduk(); List<Map<String, Object>> result = produkService.getAllPaketToProduk();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException sve) { } catch (ServiceVOException sve) {
LOGGER.error("Got ServiceVOException {} when get all data paket to produk", sve.getMessage()); LOGGER.error("Got ServiceVOException {} when getAllPaketToProduk", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when get all data paket to produk", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when getAllPaketToProduk", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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) { public ResponseEntity<List<Map<String, Object>>> getAllMasterSatuanStandar(HttpServletRequest request) {
try { try {
List<Map<String, Object>> result = satuanStandarService.getAll(); List<Map<String, Object>> result = satuanStandarService.getAll();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException sve) { } catch (ServiceVOException sve) {
LOGGER.error("Got ServiceVOException {} when get all master satuan standar distinct on", sve.getMessage()); LOGGER.error("Got ServiceVOException {} when satuanStandarService.getAll", sve.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); addHeaderMessage(ERROR_MESSAGE, sve.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when get all master satuan standar distinct on", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when satuanStandarService.getAll", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<List<String>> KlaimDiskon(HttpServletRequest request,
@RequestParam(value = "noRegistrasi") String noRegistrasi, @RequestParam(value = "noRegistrasi") String noRegistrasi,
@RequestParam(value = "totalKlaim") Double totalKlaim, @RequestParam(value = "totalKlaim") Double totalKlaim,
@RequestParam(value = "jenisDiskon") Integer jenisDiskon) { @RequestParam(value = "jenisDiskon") Integer jenisDiskon) {
try { try {
List<String> result = pelayananPasienService.updateKlaimDiskon(noRegistrasi, totalKlaim, jenisDiskon); List<String> result = pelayananPasienService.updateKlaimDiskon(noRegistrasi, totalKlaim, jenisDiskon);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when klaim diskon karyawan", e.getMessage()); LOGGER.error("Got ServiceVOException {} when updateKlaimDiskon", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when klaim diskon karyawan", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when updateKlaimDiskon", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<String> ResetKlaimDiskon(HttpServletRequest request,
@RequestParam(value = "noRegistrasi") String noRegistrasi) { @RequestParam(value = "noRegistrasi") String noRegistrasi) {
try { try {
String result = pelayananPasienService.resetKlaimDiskon(noRegistrasi); String result = pelayananPasienService.resetKlaimDiskon(noRegistrasi);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, return getJsonResponse(result, OK, mapHeaderMessage);
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when reset klaim diskon karyawan", e.getMessage()); LOGGER.error("Got ServiceVOException {} when resetKlaimDiskon", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when reset klaim diskon karyawan", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when resetKlaimDiskon", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<List<Map<String, Object>>> checkExistingHargaProdukKelas(HttpServletRequest request,
@RequestParam(value = "kelasId") Integer idKelas, @RequestParam(value = "produkId") Integer idProduk, @RequestParam(value = "kelasId") Integer idKelas, @RequestParam(value = "produkId") Integer idProduk,
@RequestParam(value = "mappingId", required = false) Integer idMapping) { @RequestParam(value = "mappingId", required = false) Integer idMapping) {
try { try {
List<Map<String, Object>> result = produkService.findExistingMapHargaKelas(idKelas, idProduk, idMapping); List<Map<String, Object>> result = produkService.findExistingMapHargaKelas(idKelas, idProduk, idMapping);
mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, return getJsonResponse(result, OK, mapHeaderMessage);
getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when check existing harga produk kelas", e.getMessage()); LOGGER.error("Got ServiceVOException {} when findExistingMapHargaKelas", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when check existing harga produk kelas", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when findExistingMapHargaKelas", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<List<TagihanPendaftaranDto>> daftarTagihan(HttpServletRequest request,
@PathVariable String noRegistrasi) { @PathVariable String noRegistrasi) {
try { try {
List<TagihanPendaftaranDto> result = pelayananPasienService.tagihan(noRegistrasi); List<TagihanPendaftaranDto> result = pelayananPasienService.tagihan(noRegistrasi);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(result, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got ServiceVOException {} when get daftar tagihan {}", e.getMessage(), noRegistrasi); LOGGER.error("Got ServiceVOException {} when pelayananPasienService.tagihan {}", e.getMessage(),
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); noRegistrasi);
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when get daftar tagihan {}", jse.getMessage(), noRegistrasi); LOGGER.error("Got JpaSystemException {} when pelayananPasienService.tagihan {}", jse.getMessage(),
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); noRegistrasi);
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<Object> simpanDiskonTagihan(HttpServletRequest request,
@RequestParam(value = "kode-voucher", required = false) String kodeVoucher, @RequestParam(value = "kode-voucher", required = false) String kodeVoucher,
@RequestBody List<TagihanPendaftaranDto> dtoList) { @RequestBody List<TagihanPendaftaranDto> dtoList) {
try { try {
pelayananPasienService.diskonTagihan(kodeVoucher, dtoList); pelayananPasienService.diskonTagihan(kodeVoucher, dtoList);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(dtoList, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(dtoList, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } 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<>(); Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage()); error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error); return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when simpan diskon tagihan", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when diskonTagihan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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) { public ResponseEntity<Object> batalPaket(HttpServletRequest request, @RequestBody BatalPaketProdukDto dto) {
try { try {
pelayananPasienService.batalPaketProduk(request, dto); pelayananPasienService.batalPaketProduk(request, dto);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(dto, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(dto, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } 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<>(); Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage()); error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error); return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when batal diskon paket", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when batalPaketProduk", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
} }
} }
@RequestMapping(value = "/vouchers/validity", method = RequestMethod.GET) @RequestMapping(value = "/vouchers/validity", method = GET)
public ResponseEntity<Object> isValidVoucher(HttpServletRequest request, public ResponseEntity<Object> isValidVoucher(HttpServletRequest request,
@RequestParam("kode-voucher") String kodeVoucher, @RequestParam("no-registrasi") String noRegistrasi) { @RequestParam("kode-voucher") String kodeVoucher, @RequestParam("no-registrasi") String noRegistrasi) {
try { try {
boolean validVoucher = pelayananPasienService.isValidVoucher(kodeVoucher, noRegistrasi); boolean validVoucher = pelayananPasienService.isValidVoucher(kodeVoucher, noRegistrasi);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(validVoucher, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(validVoucher, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } 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<>(); Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage()); error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(false, HttpStatus.BAD_REQUEST, error); return getJsonResponse(false, BAD_REQUEST, error);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when check voucher validity", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when isValidVoucher", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<Object> simpanMappingListProdukPaket(HttpServletRequest request,
@RequestBody List<MapProdukPaketVO> vos) { @RequestBody List<MapProdukPaketVO> vos) {
try { try {
mapProdukPaketService.saveAll(vos); mapProdukPaketService.saveAll(vos);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(vos, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(vos, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } 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<>(); Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage()); error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error); return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when simpan mapping list produk paket", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when mapProdukPaketService.saveAll", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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, public ResponseEntity<Object> simpanMappingEntriProdukPaket(HttpServletRequest request,
@RequestBody List<MapProdukPaketToProdukVO> vos) { @RequestBody List<MapProdukPaketToProdukVO> vos) {
try { try {
mapProdukPaketToProdukService.saveAll(vos); mapProdukPaketToProdukService.saveAll(vos);
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
getMessage(MessageResource.LABEL_SUCCESS, request)); return getJsonResponse(vos, OK, mapHeaderMessage);
return RestUtil.getJsonResponse(vos, HttpStatus.OK, mapHeaderMessage);
} catch (ServiceVOException e) { } 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<>(); Map<String, String> error = new HashMap<>();
error.put("bad_request", e.getMessage()); error.put("bad_request", e.getMessage());
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error); return getJsonResponse(null, BAD_REQUEST, error);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got JpaSystemException {} when simpan mapping entri produk paket", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when mapProdukPaketToProdukService.saveAll", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); return RestUtil.getJsonHttpStatus(CONFLICT, mapHeaderMessage);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,15 +1,11 @@
package com.jasamedika.medifirst2000.handler; package com.jasamedika.medifirst2000.handler;
import java.util.List; import com.jasamedika.medifirst2000.base.vo.validation.ValidationErrorVO;
import java.util.Locale;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError; import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException; 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.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseStatus;
import com.jasamedika.medifirst2000.base.vo.validation.ValidationErrorVO; import java.util.List;
import com.jasamedika.medifirst2000.constants.Constants;; 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 * Exception Handler Rest Controller class
* *
* @author Roberto * @author Roberto
*/ */
@ControllerAdvice @ControllerAdvice
@Order(1) // Pertama masuk @Order(1)
public class RestErrorHandler { 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 @Autowired
public RestErrorHandler(MessageSource validationNessageSource) { public RestErrorHandler(MessageSource validationNessageSource) {
@ -41,60 +40,42 @@ public class RestErrorHandler {
} }
@ExceptionHandler(MethodArgumentNotValidException.class) @ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseStatus(BAD_REQUEST)
@ResponseBody @ResponseBody
public ValidationErrorVO processValidationError(MethodArgumentNotValidException ex) { public ValidationErrorVO processValidationError(MethodArgumentNotValidException ex) {
LOGGER.warn("Handling data validation error"); LOGGER.warn("Handling data validation error");
BindingResult result = ex.getBindingResult(); BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors(); List<FieldError> fieldErrors = result.getFieldErrors();
return processFieldErrors(fieldErrors); return processFieldErrors(fieldErrors);
} }
private ValidationErrorVO processFieldErrors(List<FieldError> fieldErrors) { private ValidationErrorVO processFieldErrors(List<FieldError> fieldErrors) {
ValidationErrorVO dto = new ValidationErrorVO(); ValidationErrorVO dto = new ValidationErrorVO();
for (FieldError fieldError : fieldErrors) { for (FieldError fieldError : fieldErrors) {
dto.addFieldError(fieldError.getField(), fieldError.getDefaultMessage()); String localizedErrorMessage = resolveIndonesianErrorMessage(fieldError);
dto.addFieldError(fieldError.getField(), localizedErrorMessage);
} }
return dto; return dto;
} }
/* private String resolveCurrentLocalErrorMessage(FieldError fieldError) {
* resolve error message with parameter locale
*/
private String resolveLocalizedErrorMessage(FieldError fieldError, String locale) {
Locale currentLocale = LocaleContextHolder.getLocale(); Locale currentLocale = LocaleContextHolder.getLocale();
String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale); 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())) { if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes(); String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0]; localizedErrorMessage = fieldErrorCodes[0];
} }
return localizedErrorMessage; return localizedErrorMessage;
} }
/* private String resolveIndonesianErrorMessage(FieldError fieldError) {
* resolve error message with default locale String localizedErrorMessage = messageSource.getMessage(fieldError, new Locale(INA));
*/
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.
if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) { if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes(); String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0]; localizedErrorMessage = fieldErrorCodes[0];
} }
return localizedErrorMessage; return localizedErrorMessage;
} }
} }

View File

@ -1,6 +1,5 @@
package com.jasamedika.medifirst2000.interceptor; package com.jasamedika.medifirst2000.interceptor;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.dao.LoginUserDao; import com.jasamedika.medifirst2000.dao.LoginUserDao;
import com.jasamedika.medifirst2000.dao.RuanganDao; import com.jasamedika.medifirst2000.dao.RuanganDao;
import com.jasamedika.medifirst2000.entities.*; 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.model.AppPermission;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService; import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.service.*; import com.jasamedika.medifirst2000.service.*;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.vo.NotifMessagingSchedulerVO; import com.jasamedika.medifirst2000.vo.NotifMessagingSchedulerVO;
import com.jasamedika.medifirst2000.vo.NotifMessagingVO; import com.jasamedika.medifirst2000.vo.NotifMessagingVO;
import com.jasamedika.medifirst2000.vo.NotifikasiMessageObjekModulVO; import com.jasamedika.medifirst2000.vo.NotifikasiMessageObjekModulVO;
@ -29,6 +27,13 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; 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 * Interceptor class for All annotation method controller @AppPermission
* *
@ -80,7 +85,7 @@ public class AppInterceptor implements HandlerInterceptor {
String namaUser; String namaUser;
private boolean contains(String source, String[] matchers) { private boolean contains(String source, String[] matchers) {
if (CommonUtil.isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers)) if (isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers))
return false; return false;
for (String matcher : matchers) for (String matcher : matchers)
if (source.contains(matcher)) if (source.contains(matcher))
@ -100,10 +105,10 @@ public class AppInterceptor implements HandlerInterceptor {
Authentication authentication = tokenAuthenticationService.getAuthentication(request); Authentication authentication = tokenAuthenticationService.getAuthentication(request);
namaUser = authentication.getName(); namaUser = authentication.getName();
loginUser = loginUserDao.findByNamaUser(namaUser); loginUser = loginUserDao.findByNamaUser(namaUser);
if (CommonUtil.isNullOrEmpty(loginUser)) { if (isNullOrEmpty(loginUser)) {
response.setHeader("RequireSupervisor", "false"); response.setHeader("RequireSupervisor", "false");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Empty login user"); response.setHeader(ERROR_MESSAGE, "Empty login user");
response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setStatus(SC_FORBIDDEN);
return false; return false;
} }
return true; return true;
@ -173,19 +178,19 @@ public class AppInterceptor implements HandlerInterceptor {
int action) throws Exception { int action) throws Exception {
List<ObjekModulAplikasiVO> objekModulAplikasi = objekModulAplikasiService List<ObjekModulAplikasiVO> objekModulAplikasi = objekModulAplikasiService
.findByAlamatUrlForm(filterUrlForm(AlamatUrlForm)); .findByAlamatUrlForm(filterUrlForm(AlamatUrlForm));
if (CommonUtil.isNullOrEmpty(objekModulAplikasi)) if (isNullOrEmpty(objekModulAplikasi))
return true; return true;
if (!checkAuthSecure(request, response)) if (!checkAuthSecure(request, response))
return false; return false;
int resultUser = checkUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action); int resultUser = checkUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action);
if (resultUser == 0) { if (resultUser == 0) {
response.setHeader("RequireSupervisor", "true"); response.setHeader("RequireSupervisor", "true");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor"); response.setHeader(ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setStatus(SC_UNAUTHORIZED);
return false; return false;
} else if (resultUser == 1) { } else if (resultUser == 1) {
response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success"); response.setHeader(INFO_MESSAGE, "Supervise execution success");
response.setStatus(HttpServletResponse.SC_OK); response.setStatus(SC_OK);
return true; return true;
} }
int resultKelompokUser = checkKelompokUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action); int resultKelompokUser = checkKelompokUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action);
@ -195,12 +200,12 @@ public class AppInterceptor implements HandlerInterceptor {
return true; return true;
} else if (resultKelompokUser == 0) { } else if (resultKelompokUser == 0) {
response.setHeader("RequireSupervisor", "true"); response.setHeader("RequireSupervisor", "true");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor"); response.setHeader(ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setStatus(SC_UNAUTHORIZED);
return false; return false;
} else { } else {
response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success"); response.setHeader(INFO_MESSAGE, "Supervise execution success");
response.setStatus(HttpServletResponse.SC_OK); response.setStatus(SC_OK);
return true; return true;
} }
} }
@ -209,16 +214,14 @@ public class AppInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
HandlerMethod hm; HandlerMethod hm;
Method method; Method method;
response.setHeader("Access-Control-Expose-Headers", "RequireSupervisor" + "," response.setHeader("Access-Control-Expose-Headers",
+ Constants.MessageInfo.ERROR_MESSAGE + "," + Constants.MessageInfo.INFO_MESSAGE); "RequireSupervisor" + "," + ERROR_MESSAGE + "," + INFO_MESSAGE);
String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? "" String AlamatUrlForm = request.getHeader(URL_FORM) == null ? "" : request.getHeader(URL_FORM);
: request.getHeader(Constants.HttpHeader.URL_FORM); String KdRuangan = request.getHeader(KD_RUANGAN) == null ? "" : request.getHeader(KD_RUANGAN);
String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN);
int action = AppPermission.VIEW; int action = AppPermission.VIEW;
if (CommonUtil.isNullOrEmpty(AlamatUrlForm)) if (isNullOrEmpty(AlamatUrlForm))
return true; return true;
if (CommonUtil.isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan)) if (isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan))
return true; return true;
String URI = request.getRequestURI(); String URI = request.getRequestURI();
String methodHttp = request.getMethod(); String methodHttp = request.getMethod();
@ -264,9 +267,9 @@ public class AppInterceptor implements HandlerInterceptor {
return checkPermission(request, response, AlamatUrlForm, action); return checkPermission(request, response, AlamatUrlForm, action);
} }
} catch (Exception e) { } catch (Exception e) {
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Something wrong happened"); response.setHeader(ERROR_MESSAGE, "Something wrong happened");
response.setHeader("RequireSupervisor", "false"); response.setHeader("RequireSupervisor", "false");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(SC_INTERNAL_SERVER_ERROR);
return false; return false;
} }
return true; return true;
@ -279,46 +282,41 @@ public class AppInterceptor implements HandlerInterceptor {
@Override @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex)
throws Exception { throws Exception {
String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? "" String AlamatUrlForm = request.getHeader(URL_FORM) == null ? "" : request.getHeader(URL_FORM);
: request.getHeader(Constants.HttpHeader.URL_FORM); String KdRuangan = request.getHeader(KD_RUANGAN) == null ? "" : request.getHeader(KD_RUANGAN);
String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? "" String idRuanganTujuan = request.getHeader(KD_RUANGAN_T) == null ? "" : request.getHeader(KD_RUANGAN_T);
: request.getHeader(Constants.HttpHeader.KD_RUANGAN); String idRuanganTujuanA = request.getHeader(KD_RUANGAN_A) == null ? "" : request.getHeader(KD_RUANGAN_A);
String idRuanganTujuan = request.getHeader(Constants.HttpHeader.KD_RUANGAN_T) == null ? "" String tglKirim = request.getHeader(TGL_KIRIM) == null ? "" : request.getHeader(TGL_KIRIM);
: request.getHeader(Constants.HttpHeader.KD_RUANGAN_T); boolean notHttpOK = response.getStatus() >= SC_BAD_REQUEST;
String idRuanganTujuanA = request.getHeader(Constants.HttpHeader.KD_RUANGAN_A) == null ? "" boolean notLewatMenu = isNullOrEmpty(AlamatUrlForm) || isNullOrEmpty(KdRuangan);
: 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);
Integer ruanganAsalId; Integer ruanganAsalId;
try { try {
ruanganAsalId = Integer.parseInt(KdRuangan); ruanganAsalId = Integer.parseInt(KdRuangan);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
ruanganAsalId = 0; ruanganAsalId = 0;
} }
boolean adaError = CommonUtil.isNotNullOrEmpty(ex); boolean adaError = isNotNullOrEmpty(ex);
if (notHttpOK || notLewatMenu || adaError) if (notHttpOK || notLewatMenu || adaError)
return; return;
Authentication authentication = tokenAuthenticationService.getAuthentication(request); Authentication authentication = tokenAuthenticationService.getAuthentication(request);
if (CommonUtil.isNullOrEmpty(authentication)) if (isNullOrEmpty(authentication))
return; return;
namaUser = authentication.getName(); namaUser = authentication.getName();
loginUser = loginUserDao.findByNamaUser(namaUser); loginUser = loginUserDao.findByNamaUser(namaUser);
if (CommonUtil.isNullOrEmpty(loginUser)) if (isNullOrEmpty(loginUser))
return; return;
String potongan = filterUrlForm(AlamatUrlForm); String potongan = filterUrlForm(AlamatUrlForm);
List<ObjekModulAplikasiVO> objekModulAplikasiVOs = objekModulAplikasiService.findByAlamatUrlForm(potongan); List<ObjekModulAplikasiVO> objekModulAplikasiVOs = objekModulAplikasiService.findByAlamatUrlForm(potongan);
if (CommonUtil.isNullOrEmpty(objekModulAplikasiVOs)) if (isNullOrEmpty(objekModulAplikasiVOs))
return; return;
String URI = request.getRequestURI(); String URI = request.getRequestURI();
Integer objekModulAplikasId = objekModulAplikasiVOs.get(0).getId(); Integer objekModulAplikasId = objekModulAplikasiVOs.get(0).getId();
List<NotifMessagingVO> notifMessagingVOs = notifMessagingService List<NotifMessagingVO> notifMessagingVOs = notifMessagingService
.findByObjekModulAplikasiIdAndUrlBackEndOrUrlBackEndIsNull(objekModulAplikasId, URI); .findByObjekModulAplikasiIdAndUrlBackEndOrUrlBackEndIsNull(objekModulAplikasId, URI);
if (CommonUtil.isNullOrEmpty(notifMessagingVOs)) if (isNullOrEmpty(notifMessagingVOs))
return; return;
Integer notifMessagingId = notifMessagingVOs.get(0).getId(); Integer notifMessagingId = notifMessagingVOs.get(0).getId();
if (CommonUtil.isNullOrEmpty(tglKirim)) { if (isNullOrEmpty(tglKirim)) {
List<Integer> ruanganTujuansId = new ArrayList<>(); List<Integer> ruanganTujuansId = new ArrayList<>();
if (!"".equals(idRuanganTujuan)) { if (!"".equals(idRuanganTujuan)) {
JSONArray ruanganTujuanIds = new JSONArray(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; 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.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component; 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 * RestAuthenticationEntryPoint class set Unauthorized response from
* set Unauthorized response from "Unauthorized client" * "Unauthorized client"
* *
* @author Roberto * @author Roberto, Syamsu
*/ */
@Component("RestAuthenticationEntryPoint") @Component("RestAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class); private static final Logger LOGGER = getLogger(RestAuthenticationEntryPoint.class);
/// Alter Syamsu
@Override @Override
public void commence(HttpServletRequest request, public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae)
HttpServletResponse response, AuthenticationException ae)
throws IOException, ServletException { throws IOException, ServletException {
LOGGER.error("Mencoba akses tanpa login"); 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; 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.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.jasamedika.medifirst2000.constants.Constants; import static com.jasamedika.medifirst2000.constants.Constants.JASAMEDIKA;
import com.jasamedika.medifirst2000.filter.StatelessAuthenticationFilter;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.security.service.UserService;
/** /**
* SpringSecurityConfig class * SpringSecurityConfig class Di sini Kita tidak menggunakan XML Config untuk
* Di sini Kita tidak menggunakan XML Config untuk Spring Security * Spring Security
* *
* @author Roberto * @author Roberto
*/ */
@ -29,94 +28,35 @@ import com.jasamedika.medifirst2000.security.service.UserService;
@Order(2) @Order(2)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
@Autowired @Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint; private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
private final UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
public SpringSecurityConfig() { public SpringSecurityConfig() {
super(true); super(true);
this.userService = new UserService(); this.userService = new UserService();
tokenAuthenticationService = new TokenAuthenticationService( tokenAuthenticationService = new TokenAuthenticationService(JASAMEDIKA, userService);
Constants.JASAMEDIKA, userService);
} }
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling() http.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint).and().anonymous().and()
//restAuthenticationEntryPoint .servletApi().and().headers().cacheControl().and().authorizeRequests().antMatchers("/favicon.ico")
.authenticationEntryPoint(restAuthenticationEntryPoint) .permitAll().antMatchers("**/*.html").permitAll().antMatchers("**/*.css").permitAll()
.antMatchers("**/*.js").permitAll().antMatchers("/auth/**").permitAll()
.and() .antMatchers("/registrasi-pasien-sms/**").permitAll().antMatchers("/report/**").permitAll()
.anonymous() .antMatchers("/test-tanpa-auth/**").permitAll().antMatchers("/test/**").permitAll()
.and() .antMatchers("/api-docs.json").permitAll().antMatchers("/api-docs/**").permitAll().anyRequest()
.servletApi() .authenticated().and().addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
.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),
UsernamePasswordAuthenticationFilter.class); UsernamePasswordAuthenticationFilter.class);
} }
@Override @Override
protected void configure(AuthenticationManagerBuilder auth) protected void configure(AuthenticationManagerBuilder auth) throws Exception {
throws Exception { auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
auth.userDetailsService(userDetailsService()).passwordEncoder(
new BCryptPasswordEncoder());
} }
@Bean @Bean
@ -136,10 +76,4 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
return tokenAuthenticationService; return tokenAuthenticationService;
} }
// @Bean(name = "springSecurityFilterChain", autowire = Autowire.BY_NAME)
// public DelegatingFilterProxy springSecurityFilterChain(){
// return new DelegatingFilterProxy();
// }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
package com.jasamedika.medifirst2000.task.schedule; 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.KelompokPasien;
import com.jasamedika.medifirst2000.entities.Pegawai; import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.entities.RekapLogbookDokter; 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.service.RemunerasiService;
import com.jasamedika.medifirst2000.util.DateUtil; import com.jasamedika.medifirst2000.util.DateUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -23,6 +23,8 @@ import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import static org.slf4j.LoggerFactory.getLogger;
/** /**
* @author salmanoe * @author salmanoe
* @version 1.0.0 * @version 1.0.0
@ -30,7 +32,8 @@ import java.util.*;
*/ */
@Component @Component
public class LogbookTask { public class LogbookTask {
private static final Logger LOGGER = LoggerFactory.getLogger(LogbookTask.class);
private static final Logger LOGGER = getLogger(LogbookTask.class);
@Autowired @Autowired
private PelayananPasienPetugasDao pelayananPasienPetugasDao; private PelayananPasienPetugasDao pelayananPasienPetugasDao;
@ -59,8 +62,10 @@ public class LogbookTask {
Date tglAwal = DateUtil.startMonth(date); Date tglAwal = DateUtil.startMonth(date);
Date tglAkhir = DateUtil.endMonth(date); Date tglAkhir = DateUtil.endMonth(date);
{ {
// Delete untuk pembaharuan data rekapLogbookDokterService.deleteByPeriod(tglAwal, tglAkhir); // Delete
rekapLogbookDokterService.deleteByPeriod(tglAwal, tglAkhir); // untuk
// pembaharuan
// data
} }
Set<Integer> idPegawaiByTglPelayanan = pelayananPasienPetugasDao.findPegawaiByTglPelayanan(tglAwal, tglAkhir); Set<Integer> idPegawaiByTglPelayanan = pelayananPasienPetugasDao.findPegawaiByTglPelayanan(tglAwal, tglAkhir);
DateFormat df = new SimpleDateFormat("yyyy-MM"); 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.entities.Pasien;
import com.jasamedika.medifirst2000.util.CommonUtil; import com.jasamedika.medifirst2000.util.CommonUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -20,6 +19,7 @@ import java.time.LocalDateTime;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.http.HttpMethod.GET; import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpStatus.CREATED; import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
@ -31,7 +31,7 @@ import static org.springframework.http.HttpStatus.OK;
*/ */
@Component @Component
public class PasienTask { public class PasienTask {
private static final Logger LOGGER = LoggerFactory.getLogger(PasienTask.class); private static final Logger LOGGER = getLogger(PasienTask.class);
@Autowired @Autowired
private ObjectMapper objectMapper; private ObjectMapper objectMapper;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -28,7 +28,8 @@ public class JsonViewMessageConverter extends MappingJackson2HttpMessageConverte
} }
@Override @Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
super.writeInternal(object, outputMessage); super.writeInternal(object, outputMessage);
} }

View File

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

View File

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

View File

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

View File

@ -19,12 +19,14 @@
<mvc:annotation-driven> <mvc:annotation-driven>
<mvc:argument-resolvers> <mvc:argument-resolvers>
<bean class="org.springframework.data.web.PageableArgumentResolver" /> <bean class="org.springframework.data.web.PageableArgumentResolver" />
<bean class="net.kaczmarzyk.spring.data.jpa.web.SpecificationArgumentResolver"/> <bean
class="net.kaczmarzyk.spring.data.jpa.web.SpecificationArgumentResolver" />
<ref bean="customArgumentResolver" /> <ref bean="customArgumentResolver" />
</mvc:argument-resolvers> </mvc:argument-resolvers>
</mvc:annotation-driven> </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 /> <mvc:default-servlet-handler />
@ -39,8 +41,7 @@
<constructor-arg ref="mapper" /> <constructor-arg ref="mapper" />
</bean> </bean>
<!-- <bean id="jsonViewSupport" class="com.monitorjbl.json.JsonViewSupportFactoryBean"> <!-- <bean id="jsonViewSupport" class="com.monitorjbl.json.JsonViewSupportFactoryBean">
<constructor-arg ref="mapper" /> <constructor-arg ref="mapper" /> </bean> -->
</bean> -->
<bean id="mapper" class="com.fasterxml.jackson.databind.ObjectMapper" /> <bean id="mapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
@ -50,11 +51,12 @@
<bean id="xmlMessageConverter" <bean id="xmlMessageConverter"
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" /> 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"> <property name="messageConverters">
<list> <list>
<ref bean="jsonMessageConverter"/> <ref bean="jsonMessageConverter" />
<ref bean="xmlMessageConverter"/> <ref bean="xmlMessageConverter" />
</list> </list>
</property> </property>
</bean> </bean>
@ -65,9 +67,10 @@
<context:property-placeholder location="classpath:swagger.properties" /> <context:property-placeholder location="classpath:swagger.properties" />
<bean id="jasperViewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <bean id="jasperViewResolver"
<property name="basename" value="views"/> class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="order" value="0"/> <property name="basename" value="views" />
<property name="order" value="0" />
</bean> </bean>

View File

@ -274,11 +274,8 @@
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<!-- <dependency> <!-- <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId>
<groupId>org.codehaus.groovy</groupId> <version>1.8.4</version> </dependency> -->
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
</dependency> -->
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
@ -291,6 +288,14 @@
<version>${commons-collections.version}</version> <version>${commons-collections.version}</version>
</dependency> </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> </dependencies>
<build> <build>

View File

@ -9,70 +9,56 @@ import java.text.SimpleDateFormat;
* @author Roberto * @author Roberto
*/ */
public class Constants { public class Constants {
public static final String JASAMEDIKA = "SkFTQU1FRElLQQ=="; public static final String JASAMEDIKA = "SkFTQU1FRElLQQ==";
public static final String APP_VERSION = "APP_VERSION"; public static final String APP_VERSION = "APP_VERSION";
public static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN"; public static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN";
//for example
public static final String IDR = "IDR"; public static final String IDR = "IDR";
public static final String RP = "RP"; public static final String RP = "RP";
public static final String COMMA = ","; public static final String COMMA = ",";
public static final DecimalFormat ONE_COMA_FORMAT = new DecimalFormat("#.#"); 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 class DateFormat {
public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat( public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
"yyyyMMdd"); public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat("dd MMM yyyy");
public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat( public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
"dd MMM yyyy"); public static final SimpleDateFormat yyyy_MM_dd_T_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat( public static final SimpleDateFormat yyyyMMdd_HH_mm_ss = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
"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 class MessageInfo {
public static final String INFO_MESSAGE = "INFO_MESSAGE"; public static final String INFO_MESSAGE = "INFO_MESSAGE";
public static final String WARNING_MESSAGE = "WARNING_MESSAGE"; public static final String WARNING_MESSAGE = "WARNING_MESSAGE";
public static final String ERROR_MESSAGE = "ERROR_MESSAGE"; public static final String ERROR_MESSAGE = "ERROR_MESSAGE";
public static final String EXCEPTION_MESSAGE = "EXCEPTION_MESSAGE"; public static final String EXCEPTION_MESSAGE = "EXCEPTION_MESSAGE";
} }
/* locale id (indonesia / default) and en (english) */
public static final class Locale { public static final class Locale {
public static final String INA = "ina"; public static final String INA = "ina";
public static final String EN = "en"; 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 class HttpHeader {
public static final String SUPERVISING = "Supervising"; public static final String SUPERVISING = "Supervising";
public static final String MODULE = "Module"; public static final String MODULE = "Module";
public static final String FORM = "Form"; public static final String FORM = "Form";
public static final String ACTION = "Action"; public static final String ACTION = "Action";
public static final String URL_FORM = "AlamatUrlForm";
public static final String URL_FORM = "AlamatUrlForm"; // syamsu public static final String KD_RUANGAN = "KdRuangan";
public static final String KD_RUANGAN = "KdRuangan"; // syamsu public static final String KD_RUANGAN_T = "KdRuanganT";
public static final String KD_RUANGAN_T = "KdRuanganT"; // syamsu public static final String KD_RUANGAN_A = "KdRuanganA";
public static final String KD_RUANGAN_A = "KdRuanganA"; // syamsu public static final String TGL_KIRIM = "tglKirim";
public static final String TGL_KIRIM = "tglKirim"; // syamsu public static final String KD_USER = "KdUser";
// 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
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,143 +1,97 @@
package com.jasamedika.medifirst2000.controller; package com.jasamedika.medifirst2000.controller;
import java.util.Map; import com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import javax.servlet.http.HttpServletRequest; import com.jasamedika.medifirst2000.exception.ServiceVOException;
import javax.validation.Valid; import com.jasamedika.medifirst2000.service.PengukuranSuhuService;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; 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.http.ResponseEntity;
import org.springframework.orm.jpa.JpaSystemException; import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; 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.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import com.jasamedika.medifirst2000.constants.Constants; import javax.servlet.http.HttpServletRequest;
import com.jasamedika.medifirst2000.constants.MessageResource; import javax.validation.Valid;
import com.jasamedika.medifirst2000.controller.base.LocaleController; import java.util.Map;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.exception.ServiceVOException; import static com.jasamedika.medifirst2000.constants.Constants.MessageInfo.ERROR_MESSAGE;
import com.jasamedika.medifirst2000.service.PengukuranSuhuService; import static com.jasamedika.medifirst2000.core.web.WebConstants.HttpHeaderInfo.LABEL_SUCCESS;
import com.jasamedika.medifirst2000.util.rest.RestUtil; import static com.jasamedika.medifirst2000.util.rest.RestUtil.getJsonHttpStatus;
import com.jasamedika.medifirst2000.vo.PengukuranKebisinganVO; 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 @RestController
@RequestMapping("/pengukuran-suhu") @RequestMapping("/pengukuran-suhu")
public class PengukuranSuhuController extends LocaleController<PengukuranKebisinganVO>{ public class PengukuranSuhuController extends LocaleController<PengukuranKebisinganVO> {
private static final Logger LOGGER = getLogger(PengukuranSuhuController.class);
@Autowired @Autowired
private PengukuranSuhuService service; private PengukuranSuhuService service;
private static final Logger LOGGER = LoggerFactory.getLogger(PengukuranSuhuController.class); @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,
@RequestMapping(value = "/get-unit-ruangan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) HttpServletRequest request) {
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) {
try { try {
vo.setMenutype("suhu"); vo.setMenutype("suhu");
Map<String,Object> result = service.savePengukuranSuhu(vo); Map<String, Object> result = service.savePengukuranSuhu(vo);
if (null != result) if (null != result)
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request)); mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage); return getJsonResponse(result, CREATED, mapHeaderMessage);
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePengukuranPencahayaan", e.getMessage()); LOGGER.error("Got ServiceVOException {} when savePengukuranPencahayaan", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePengukuranPencahayaan", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when savePengukuranPencahayaan", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); 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) { public ResponseEntity<Map<String, Object>> getPengukuranKelembaban(HttpServletRequest request) {
try { try {
Map<String,Object> result = service.getPengukuranSuhu(); Map<String, Object> result = service.getPengukuranSuhu();
if (null != result){ if (null != result) {
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request)); mapHeaderMessage.put(LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.OK,mapHeaderMessage); return getJsonResponse(result, OK, mapHeaderMessage);
} else{ } else {
return RestUtil.getJsonResponse(result, HttpStatus.NOT_FOUND,mapHeaderMessage); return getJsonResponse(null, NOT_FOUND, mapHeaderMessage);
} }
} catch (ServiceVOException e) { } catch (ServiceVOException e) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", e.getMessage()); LOGGER.error("Got ServiceVOException {} when getPengukuranSuhu", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); addHeaderMessage(ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); return getJsonHttpStatus(INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) { } catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when getPengukuranKebisingan", jse.getMessage()); LOGGER.error("Got JpaSystemException {} when getPengukuranSuhu", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); addHeaderMessage(ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); return getJsonHttpStatus(CONFLICT, mapHeaderMessage);
} }
} }
@RequestMapping("/lapPengukuranSuhu") @RequestMapping("/lapPengukuranSuhu")
public ModelAndView lapPengukuranSuhu(ModelAndView m, public ModelAndView lapPengukuranSuhu(ModelAndView m,
@RequestParam(value = "format", required = false) String format, @RequestParam(value = "format", required = false) String format,
@RequestParam(value = "startDate", required = true) String startDate, @RequestParam(value = "startDate") String startDate, @RequestParam(value = "endDate") String endDate) {
@RequestParam(value = "endDate", required = true) String endDate) {
Map<String, Object> result = this.service.getRepotingPengukurangSuhu(startDate, endDate); Map<String, Object> result = this.service.getRepotingPengukurangSuhu(startDate, endDate);
Map<String, Object> header = (Map<String, Object>) result.get("header"); Map<String, Object> header = (Map<String, Object>) result.get("header");
String periode = header.get("startDate") == null ? "" : (String) header.get("startDate"); 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("dataSource", result.get("listData"));
m.addObject("periode", periode); m.addObject("periode", periode);
m.addObject("format", "pdf"); m.addObject("format", "pdf");
if (format != null && !format.isEmpty()) { if (format != null && !format.isEmpty())
m.addObject("format", format); m.addObject("format", format);
}
return m; 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; package com.jasamedika.medifirst2000.controller.base;
import java.io.BufferedReader; import com.google.gson.Gson;
import java.io.IOException; import com.google.gson.GsonBuilder;
import java.io.InputStreamReader; import com.google.gson.JsonDeserializer;
import java.lang.reflect.Type; import com.jasamedika.medifirst2000.base.vo.BaseModelVO;
import java.net.URISyntaxException; import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import java.text.DateFormat; import com.jasamedika.medifirst2000.entities.Pegawai;
import java.text.SimpleDateFormat; import com.jasamedika.medifirst2000.exception.ServiceVOException;
import java.util.ArrayList; import com.jasamedika.medifirst2000.service.ActivityPegawaiService;
import java.util.Arrays; import com.jasamedika.medifirst2000.service.LoginUserService;
import java.util.Collection; import com.jasamedika.medifirst2000.service.ModelService;
import java.util.Date; import com.jasamedika.medifirst2000.vo.ModelVO;
import java.util.HashMap; import com.jasamedika.medifirst2000.vo.PegawaiVO;
import java.util.List; import io.socket.client.IO;
import java.util.Locale; import io.socket.client.Socket;
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 org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.gson.Gson; import javax.servlet.http.Cookie;
import com.google.gson.GsonBuilder; import javax.servlet.http.HttpServletRequest;
import com.google.gson.JsonDeserializationContext; import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonDeserializer; import java.io.BufferedReader;
import com.google.gson.JsonElement; import java.io.IOException;
import com.google.gson.JsonParseException; import java.io.InputStreamReader;
import com.jasamedika.medifirst2000.base.vo.BaseModelVO; import java.net.URISyntaxException;
import com.jasamedika.medifirst2000.constants.Constants; import java.util.*;
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 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 messaga resource for internationalization
@ -63,15 +49,10 @@ import io.socket.client.IO;
* @author Roberto * @author Roberto
*/ */
public abstract class LocaleController<V extends BaseModelVO> { public abstract class LocaleController<V extends BaseModelVO> {
/*
* messageSource bean injected for each controller for accessing message
* source
*/
@Autowired @Autowired
private ActivityPegawaiService activityPegawaiServiceImpl; private ActivityPegawaiService activityPegawaiServiceImpl;
@Autowired @Autowired
private BaseConverterImpl<PegawaiVO, Pegawai> pegawaiConverter; private BaseConverterImpl<PegawaiVO, Pegawai> pegawaiConverter;
@ -82,85 +63,61 @@ public abstract class LocaleController<V extends BaseModelVO> {
private MessageSource messageSource; private MessageSource messageSource;
@Autowired @Autowired
private ModelService modelService; private ModelService<ModelVO> modelService;
protected Map<String, String> mapHeaderMessage = new HashMap<>();
@Autowired
private AgamaService agamaService;
protected Map<String, String> mapHeaderMessage = new HashMap<String, String>();
/*
* code locale
*/
protected String getMessage(String code, HttpServletRequest request) { protected String getMessage(String code, HttpServletRequest request) {
return messageSource.getMessage(code, null, new Locale(getCoociesLanguage(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); activityPegawaiServiceImpl.record(
pegawaiConverter.transferModelToVO(loginUserService.getLoginUser().getPegawai(), new PegawaiVO()),
new Date(), keterangan, group);
} }
protected Object getItem(HttpServletRequest request,Object vo)
{ protected Object getItem(HttpServletRequest request, Object vo) {
BufferedReader reader;
String read = null;
String resultData = "";
Gson gson = new Gson();
try { try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder resultData = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String read;
while ((read = reader.readLine()) != null)
while ((read = reader.readLine()) != null) { resultData.append(read);
resultData += read; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
System.out.println(read); return gson.fromJson(resultData.toString(), vo.getClass());
}
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")//.excludeFieldsWithoutExposeAnnotation()
.create();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); throw new ServiceVOException(e.getMessage());
} }
return vo= gson.fromJson(resultData, vo.getClass());
} }
protected Object getItem2(HttpServletRequest request,Object vo) protected Object getItem2(HttpServletRequest request, Object vo) {
{
BufferedReader reader;
String read = null;
String resultData = "";
Gson gson = new Gson();
try { try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream())); String read;
StringBuilder resultData = new StringBuilder();
while ((read = reader.readLine()) != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
resultData += read; while ((read = reader.readLine()) != null)
System.out.println(read); resultData.append(read);
}
GsonBuilder gsonBuilder = new GsonBuilder(); GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { gsonBuilder.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> {
@Override if (json.getAsString() != null) {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if(json.getAsString() instanceof String){
return new Date(); return new Date();
}else{ } else {
return new Date(json.getAsJsonPrimitive().getAsLong()); return new Date(json.getAsJsonPrimitive().getAsLong());
} }
}
}); });
gson = gsonBuilder.create(); Gson gson = gsonBuilder.create();
return gson.fromJson(resultData.toString(), vo.getClass());
} catch (IOException e) { } 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, public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
@PathVariable("lang") String lang) throws Exception { @PathVariable("lang") String lang) {
Cookie[] cookies = request.getCookies(); Cookie[] cookies = request.getCookies();
List<Cookie> cookieList = new ArrayList<Cookie>(); List<Cookie> cookieList;
if (cookies != null) { if (cookies != null) {
cookieList = Arrays.asList(cookies); cookieList = Arrays.asList(cookies);
for (Cookie cookie : cookieList) { for (Cookie cookie : cookieList) {
@ -172,7 +129,6 @@ public abstract class LocaleController<V extends BaseModelVO> {
} }
} }
} }
if (lang.equalsIgnoreCase("en")) { if (lang.equalsIgnoreCase("en")) {
Cookie c = new Cookie("lang", "en"); Cookie c = new Cookie("lang", "en");
c.setPath("/"); c.setPath("/");
@ -189,156 +145,117 @@ public abstract class LocaleController<V extends BaseModelVO> {
c.setDomain("localhost"); c.setDomain("localhost");
response.addCookie(c); response.addCookie(c);
} }
return true; return true;
} }
/*
* default locale ID
*/
protected String getMessage(String code) { 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) { protected void addHeaderMessage(String key, String message) {
this.mapHeaderMessage.put(key, 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) { public ResponseEntity<ModelVO> serializeEntity(@PathVariable("entity") String entity, HttpServletRequest request) {
ModelVO modelDTO = modelService.getModelSerializeEntity(entity, getCoociesLanguage(request)); ModelVO modelDTO = modelService.getModelSerializeEntity(entity, getCoociesLanguage(request));
return RestUtil.getJsonResponse(modelDTO, HttpStatus.OK); return getJsonResponse(modelDTO, OK);
} }
public String getCoociesLanguage(HttpServletRequest request) { public String getCoociesLanguage(HttpServletRequest request) {
Cookie cookie[] = request.getCookies(); Cookie[] cookie = request.getCookies();
Cookie cook; Cookie cook;
String lang = Constants.Locale.INA; String lang = INA;
if (cookie != null) { if (cookie != null) {
for (int i = 0; i < cookie.length; i++) { for (Cookie value : cookie) {
cook = cookie[i]; cook = value;
if (cook.getName().equalsIgnoreCase("lang")) if (cook.getName().equalsIgnoreCase("lang"))
lang = cook.getValue(); lang = cook.getValue();
} }
} }
return lang; return lang;
} }
@SuppressWarnings("rawtypes") protected ResponseEntity<Collection<V>> constructListPageResult(Map<String, Object> map) {
protected ResponseEntity constructListPageResult(Map<String, Object> map) {
if (map == null) { if (map == null) {
Map<String, String> mapHeaderMessage = new HashMap<String, String>(); Map<String, String> mapHeaderMessage = new HashMap<>();
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER, "0"); mapHeaderMessage.put(TOTAL_PAGE_HEADER, "0");
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER, "0"); mapHeaderMessage.put(TOTAL_COUNT_HEADER, "0");
mapHeaderMessage.put(Constants.MessageInfo.ERROR_MESSAGE, "Data not found."); mapHeaderMessage.put(ERROR_MESSAGE, "Data not found.");
return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, mapHeaderMessage); return getJsonResponse(null, BAD_REQUEST, mapHeaderMessage);
} else { } else {
@SuppressWarnings("unchecked") Collection<V> vos = (Collection<V>) map.get(LIST_DATA);
Collection<PasienVO> vos = (Collection<PasienVO>) map.get(WebConstants.PageParameter.LIST_DATA); Map<String, String> mapHeaderMessage = new HashMap<>();
mapHeaderMessage.put(TOTAL_PAGE_HEADER, String.valueOf(map.get(TOTAL_PAGES)));
Map<String, String> mapHeaderMessage = new HashMap<String, String>(); mapHeaderMessage.put(TOTAL_COUNT_HEADER, String.valueOf(map.get(TOTAL_ELEMENTS)));
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER, return getJsonResponse(vos, OK, mapHeaderMessage);
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);
} }
} }
// @PersistenceContext
// protected EntityManager em;
public String GetSettingDataFixed(String prefix) { public String GetSettingDataFixed(String prefix) {
return activityPegawaiServiceImpl.GetSettingDataFixed(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();
}
} }
}); protected void BroadcastMessage(final Object data) {
socket.connect(); final Socket socket;
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
protected void BroadcastMessage(final String to, final String data) {
final io.socket.client.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 { try {
String url = GetSettingDataFixed("UrlSocketMessaging"); String url = GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url); socket = IO.socket(url);
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) {
throw new ServiceVOException(e.getMessage());
}
}
socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() { 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());
}
}
@Override protected void BroadcastMessageOther(final Object data) {
public void call(Object... args) { final Socket socket;
try {
String url = GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url);
socket.on(Socket.EVENT_CONNECT, args -> {
try { try {
Map<String, Object> result = new HashMap<>(); Map<String, Object> result = new HashMap<>();
result.put("message", data); result.put("message", data);
result.put("to", to); result.put("to", "PermintaanPerbaikan");
Gson gson = new Gson(); Gson gson = new Gson();
JSONObject item = new JSONObject(gson.toJson(result)); JSONObject item = new JSONObject(gson.toJson(result));
socket.emit("subscribe", item); socket.emit("subscribe", item);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); throw new ServiceVOException(e.getMessage());
}
} }
}); });
socket.connect(); socket.connect();
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
e.printStackTrace(); throw new ServiceVOException(e.getMessage());
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,5 @@
package com.jasamedika.medifirst2000.interceptor; package com.jasamedika.medifirst2000.interceptor;
import com.jasamedika.medifirst2000.constants.Constants;
import com.jasamedika.medifirst2000.dao.LoginUserDao; import com.jasamedika.medifirst2000.dao.LoginUserDao;
import com.jasamedika.medifirst2000.dao.RuanganDao; import com.jasamedika.medifirst2000.dao.RuanganDao;
import com.jasamedika.medifirst2000.entities.*; 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.model.AppPermission;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService; import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.service.*; import com.jasamedika.medifirst2000.service.*;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.vo.NotifMessagingSchedulerVO; import com.jasamedika.medifirst2000.vo.NotifMessagingSchedulerVO;
import com.jasamedika.medifirst2000.vo.NotifMessagingVO; import com.jasamedika.medifirst2000.vo.NotifMessagingVO;
import com.jasamedika.medifirst2000.vo.NotifikasiMessageObjekModulVO; import com.jasamedika.medifirst2000.vo.NotifikasiMessageObjekModulVO;
@ -29,6 +27,13 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; 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 * Interceptor class for All annotation method controller @AppPermission
* *
@ -80,7 +85,7 @@ public class AppInterceptor implements HandlerInterceptor {
String namaUser; String namaUser;
private boolean contains(String source, String[] matchers) { private boolean contains(String source, String[] matchers) {
if (CommonUtil.isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers)) if (isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers))
return false; return false;
for (String matcher : matchers) for (String matcher : matchers)
if (source.contains(matcher)) if (source.contains(matcher))
@ -100,10 +105,10 @@ public class AppInterceptor implements HandlerInterceptor {
Authentication authentication = tokenAuthenticationService.getAuthentication(request); Authentication authentication = tokenAuthenticationService.getAuthentication(request);
namaUser = authentication.getName(); namaUser = authentication.getName();
loginUser = loginUserDao.findByNamaUser(namaUser); loginUser = loginUserDao.findByNamaUser(namaUser);
if (CommonUtil.isNullOrEmpty(loginUser)) { if (isNullOrEmpty(loginUser)) {
response.setHeader("RequireSupervisor", "false"); response.setHeader("RequireSupervisor", "false");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Empty login user"); response.setHeader(ERROR_MESSAGE, "Empty login user");
response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setStatus(SC_FORBIDDEN);
return false; return false;
} }
return true; return true;
@ -173,19 +178,19 @@ public class AppInterceptor implements HandlerInterceptor {
int action) throws Exception { int action) throws Exception {
List<ObjekModulAplikasiVO> objekModulAplikasi = objekModulAplikasiService List<ObjekModulAplikasiVO> objekModulAplikasi = objekModulAplikasiService
.findByAlamatUrlForm(filterUrlForm(AlamatUrlForm)); .findByAlamatUrlForm(filterUrlForm(AlamatUrlForm));
if (CommonUtil.isNullOrEmpty(objekModulAplikasi)) if (isNullOrEmpty(objekModulAplikasi))
return true; return true;
if (!checkAuthSecure(request, response)) if (!checkAuthSecure(request, response))
return false; return false;
int resultUser = checkUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action); int resultUser = checkUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action);
if (resultUser == 0) { if (resultUser == 0) {
response.setHeader("RequireSupervisor", "true"); response.setHeader("RequireSupervisor", "true");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor"); response.setHeader(ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setStatus(SC_UNAUTHORIZED);
return false; return false;
} else if (resultUser == 1) { } else if (resultUser == 1) {
response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success"); response.setHeader(INFO_MESSAGE, "Supervise execution success");
response.setStatus(HttpServletResponse.SC_OK); response.setStatus(SC_OK);
return true; return true;
} }
int resultKelompokUser = checkKelompokUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action); int resultKelompokUser = checkKelompokUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action);
@ -195,12 +200,12 @@ public class AppInterceptor implements HandlerInterceptor {
return true; return true;
} else if (resultKelompokUser == 0) { } else if (resultKelompokUser == 0) {
response.setHeader("RequireSupervisor", "true"); response.setHeader("RequireSupervisor", "true");
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor"); response.setHeader(ERROR_MESSAGE, "Action requires supervisor");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setStatus(SC_UNAUTHORIZED);
return false; return false;
} else { } else {
response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success"); response.setHeader(INFO_MESSAGE, "Supervise execution success");
response.setStatus(HttpServletResponse.SC_OK); response.setStatus(SC_OK);
return true; return true;
} }
} }
@ -209,21 +214,19 @@ public class AppInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
HandlerMethod hm; HandlerMethod hm;
Method method; Method method;
response.setHeader("Access-Control-Expose-Headers", "RequireSupervisor" + "," response.setHeader("Access-Control-Expose-Headers",
+ Constants.MessageInfo.ERROR_MESSAGE + "," + Constants.MessageInfo.INFO_MESSAGE); "RequireSupervisor" + "," + ERROR_MESSAGE + "," + INFO_MESSAGE);
String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? "" String AlamatUrlForm = request.getHeader(URL_FORM) == null ? "" : request.getHeader(URL_FORM);
: request.getHeader(Constants.HttpHeader.URL_FORM); String KdRuangan = request.getHeader(KD_RUANGAN) == null ? "" : request.getHeader(KD_RUANGAN);
String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? ""
: request.getHeader(Constants.HttpHeader.KD_RUANGAN);
int action = AppPermission.VIEW; int action = AppPermission.VIEW;
if (CommonUtil.isNullOrEmpty(AlamatUrlForm)) if (isNullOrEmpty(AlamatUrlForm))
return true; return true;
if (CommonUtil.isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan)) if (isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan))
return true; return true;
String URI = request.getRequestURI(); String URI = request.getRequestURI();
String methodHttp = request.getMethod(); String methodHttp = request.getMethod();
try { try {
if (handler instanceof org.springframework.web.method.HandlerMethod) { if (handler instanceof HandlerMethod) {
hm = (HandlerMethod) handler; hm = (HandlerMethod) handler;
method = hm.getMethod(); method = hm.getMethod();
} else { } else {
@ -264,9 +267,9 @@ public class AppInterceptor implements HandlerInterceptor {
return checkPermission(request, response, AlamatUrlForm, action); return checkPermission(request, response, AlamatUrlForm, action);
} }
} catch (Exception e) { } catch (Exception e) {
response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Something wrong happened"); response.setHeader(ERROR_MESSAGE, "Something wrong happened");
response.setHeader("RequireSupervisor", "false"); response.setHeader("RequireSupervisor", "false");
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(SC_INTERNAL_SERVER_ERROR);
return false; return false;
} }
return true; return true;
@ -279,46 +282,41 @@ public class AppInterceptor implements HandlerInterceptor {
@Override @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex)
throws Exception { throws Exception {
String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? "" String AlamatUrlForm = request.getHeader(URL_FORM) == null ? "" : request.getHeader(URL_FORM);
: request.getHeader(Constants.HttpHeader.URL_FORM); String KdRuangan = request.getHeader(KD_RUANGAN) == null ? "" : request.getHeader(KD_RUANGAN);
String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? "" String idRuanganTujuan = request.getHeader(KD_RUANGAN_T) == null ? "" : request.getHeader(KD_RUANGAN_T);
: request.getHeader(Constants.HttpHeader.KD_RUANGAN); String idRuanganTujuanA = request.getHeader(KD_RUANGAN_A) == null ? "" : request.getHeader(KD_RUANGAN_A);
String idRuanganTujuan = request.getHeader(Constants.HttpHeader.KD_RUANGAN_T) == null ? "" String tglKirim = request.getHeader(TGL_KIRIM) == null ? "" : request.getHeader(TGL_KIRIM);
: request.getHeader(Constants.HttpHeader.KD_RUANGAN_T); boolean notHttpOK = response.getStatus() >= SC_BAD_REQUEST;
String idRuanganTujuanA = request.getHeader(Constants.HttpHeader.KD_RUANGAN_A) == null ? "" boolean notLewatMenu = isNullOrEmpty(AlamatUrlForm) || isNullOrEmpty(KdRuangan);
: 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);
Integer ruanganAsalId; Integer ruanganAsalId;
try { try {
ruanganAsalId = Integer.parseInt(KdRuangan); ruanganAsalId = Integer.parseInt(KdRuangan);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
ruanganAsalId = 0; ruanganAsalId = 0;
} }
boolean adaError = CommonUtil.isNotNullOrEmpty(ex); boolean adaError = isNotNullOrEmpty(ex);
if (notHttpOK || notLewatMenu || adaError) if (notHttpOK || notLewatMenu || adaError)
return; return;
Authentication authentication = tokenAuthenticationService.getAuthentication(request); Authentication authentication = tokenAuthenticationService.getAuthentication(request);
if (CommonUtil.isNullOrEmpty(authentication)) if (isNullOrEmpty(authentication))
return; return;
namaUser = authentication.getName(); namaUser = authentication.getName();
loginUser = loginUserDao.findByNamaUser(namaUser); loginUser = loginUserDao.findByNamaUser(namaUser);
if (CommonUtil.isNullOrEmpty(loginUser)) if (isNullOrEmpty(loginUser))
return; return;
String potongan = filterUrlForm(AlamatUrlForm); String potongan = filterUrlForm(AlamatUrlForm);
List<ObjekModulAplikasiVO> objekModulAplikasiVOs = objekModulAplikasiService.findByAlamatUrlForm(potongan); List<ObjekModulAplikasiVO> objekModulAplikasiVOs = objekModulAplikasiService.findByAlamatUrlForm(potongan);
if (CommonUtil.isNullOrEmpty(objekModulAplikasiVOs)) if (isNullOrEmpty(objekModulAplikasiVOs))
return; return;
String URI = request.getRequestURI(); String URI = request.getRequestURI();
Integer objekModulAplikasId = objekModulAplikasiVOs.get(0).getId(); Integer objekModulAplikasId = objekModulAplikasiVOs.get(0).getId();
List<NotifMessagingVO> notifMessagingVOs = notifMessagingService List<NotifMessagingVO> notifMessagingVOs = notifMessagingService
.findByObjekModulAplikasiIdAndUrlBackEndOrUrlBackEndIsNull(objekModulAplikasId, URI); .findByObjekModulAplikasiIdAndUrlBackEndOrUrlBackEndIsNull(objekModulAplikasId, URI);
if (CommonUtil.isNullOrEmpty(notifMessagingVOs)) if (isNullOrEmpty(notifMessagingVOs))
return; return;
Integer notifMessagingId = notifMessagingVOs.get(0).getId(); Integer notifMessagingId = notifMessagingVOs.get(0).getId();
if (CommonUtil.isNullOrEmpty(tglKirim)) { if (isNullOrEmpty(tglKirim)) {
List<Integer> ruanganTujuansId = new ArrayList<>(); List<Integer> ruanganTujuansId = new ArrayList<>();
if (!"".equals(idRuanganTujuan)) { if (!"".equals(idRuanganTujuan)) {
JSONArray ruanganTujuanIds = new JSONArray(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; 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.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component; 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 * RestAuthenticationEntryPoint class set Unauthorized response from
* set Unauthorized response from "Unauthorized client" * "Unauthorized client"
* *
* @author Roberto * @author Roberto, Syamsu
*/ */
@Component("RestAuthenticationEntryPoint") @Component("RestAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class); private static final Logger LOGGER = getLogger(RestAuthenticationEntryPoint.class);
/// Alter Syamsu
@Override @Override
public void commence(HttpServletRequest request, public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae)
HttpServletResponse response, AuthenticationException ae)
throws IOException, ServletException { throws IOException, ServletException {
LOGGER.error("Mencoba akses tanpa login"); 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; 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.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.jasamedika.medifirst2000.constants.Constants; import static com.jasamedika.medifirst2000.constants.Constants.JASAMEDIKA;
import com.jasamedika.medifirst2000.filter.StatelessAuthenticationFilter;
import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService;
import com.jasamedika.medifirst2000.security.service.UserService;
/** /**
* SpringSecurityConfig class * SpringSecurityConfig class Di sini Kita tidak menggunakan XML Config untuk
* Di sini Kita tidak menggunakan XML Config untuk Spring Security * Spring Security
* *
* @author Roberto * @author Roberto
*/ */
@ -29,94 +28,35 @@ import com.jasamedika.medifirst2000.security.service.UserService;
@Order(2) @Order(2)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
@Autowired @Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint; private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
private final UserService userService;
private final TokenAuthenticationService tokenAuthenticationService;
public SpringSecurityConfig() { public SpringSecurityConfig() {
super(true); super(true);
this.userService = new UserService(); this.userService = new UserService();
tokenAuthenticationService = new TokenAuthenticationService( tokenAuthenticationService = new TokenAuthenticationService(JASAMEDIKA, userService);
Constants.JASAMEDIKA, userService);
} }
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling() http.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint).and().anonymous().and()
//restAuthenticationEntryPoint .servletApi().and().headers().cacheControl().and().authorizeRequests().antMatchers("/favicon.ico")
.authenticationEntryPoint(restAuthenticationEntryPoint) .permitAll().antMatchers("**/*.html").permitAll().antMatchers("**/*.css").permitAll()
.antMatchers("**/*.js").permitAll().antMatchers("/auth/**").permitAll()
.and() .antMatchers("/registrasi-pasien-sms/**").permitAll().antMatchers("/report/**").permitAll()
.anonymous() .antMatchers("/test-tanpa-auth/**").permitAll().antMatchers("/test/**").permitAll()
.and() .antMatchers("/api-docs.json").permitAll().antMatchers("/api-docs/**").permitAll().anyRequest()
.servletApi() .authenticated().and().addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService),
.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),
UsernamePasswordAuthenticationFilter.class); UsernamePasswordAuthenticationFilter.class);
} }
@Override @Override
protected void configure(AuthenticationManagerBuilder auth) protected void configure(AuthenticationManagerBuilder auth) throws Exception {
throws Exception { auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
auth.userDetailsService(userDetailsService()).passwordEncoder(
new BCryptPasswordEncoder());
} }
@Bean @Bean
@ -136,10 +76,4 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
return tokenAuthenticationService; return tokenAuthenticationService;
} }
// @Bean(name = "springSecurityFilterChain", autowire = Autowire.BY_NAME)
// public DelegatingFilterProxy springSecurityFilterChain(){
// return new DelegatingFilterProxy();
// }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -28,7 +28,8 @@ public class JsonViewMessageConverter extends MappingJackson2HttpMessageConverte
} }
@Override @Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
super.writeInternal(object, outputMessage); super.writeInternal(object, outputMessage);
} }

View File

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

View File

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

View File

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

View File

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

View File

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