From e6bc94e0b02a724be2e92714179070ac6020917c Mon Sep 17 00:00:00 2001 From: Salman Manoe Date: Wed, 26 Jul 2023 09:14:58 +0700 Subject: [PATCH] Create modul pelayanan --- Medifirst2000/pom.xml | 1 + .../WebContent/META-INF/MANIFEST.MF | 3 + jasamedika-pelayanan/pom.xml | 298 +++++++ .../medifirst2000/constants/Constants.java | 78 ++ .../constants/MessageResource.java | 18 + .../controller/AkomodasiController.java | 161 ++++ .../controller/GenericServiceController.java | 163 ++++ .../controller/KonsultasiController.java | 162 ++++ .../controller/PelayananController.java | 239 ++++++ .../controller/base/BaseRestController.java | 42 + .../controller/base/IBaseRestController.java | 42 + .../controller/base/IRestPageController.java | 41 + .../controller/base/LocaleController.java | 328 ++++++++ .../controller/base/ParamRestController.java | 78 ++ .../controller/base/RestPageController.java | 38 + .../medifirst2000/filter/CORSFilter.java | 188 +++++ .../filter/StatelessAuthenticationFilter.java | 67 ++ .../handler/RestErrorHandler.java | 100 +++ .../interceptor/AppInterceptor.java | 770 ++++++++++++++++++ .../RestAuthenticationEntryPoint.java | 43 + .../security/SpringSecurityConfig.java | 145 ++++ .../security/handler/TokenHandler.java | 40 + .../security/model/AppPermission.java | 25 + .../security/model/UserAuthentication.java | 60 ++ .../service/TokenAuthenticationService.java | 72 ++ .../security/service/UserService.java | 61 ++ .../task/schedule/ScheduleTask.java | 56 ++ .../schedule/config/ScheduleTaskConfig.java | 27 + .../util/rest/JacksonConfiguration.java | 29 + .../medifirst2000/util/rest/RestUtil.java | 245 ++++++ .../java/com/monitorjbl/json/JsonResult.java | 53 ++ .../monitorjbl/json/JsonResultRetriever.java | 18 + .../JsonViewHttpEntityMethodProcessor.java | 33 + .../json/JsonViewMessageConverter.java | 35 + .../json/JsonViewResponseProcessor.java | 12 + .../json/JsonViewReturnValueHandler.java | 40 + .../json/JsonViewSupportFactoryBean.java | 52 ++ .../src/main/resources/swagger.properties | 3 + .../main/webapp/WEB-INF/spring-security.xml | 10 + .../main/webapp/WEB-INF/springmvc-context.xml | 75 ++ .../MapRuanganToAkomodasiController.java | 5 - 41 files changed, 3951 insertions(+), 5 deletions(-) create mode 100644 jasamedika-pelayanan/WebContent/META-INF/MANIFEST.MF create mode 100644 jasamedika-pelayanan/pom.xml create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/constants/Constants.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/constants/MessageResource.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/AkomodasiController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/GenericServiceController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/KonsultasiController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/PelayananController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/BaseRestController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/IBaseRestController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/IRestPageController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/LocaleController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/ParamRestController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/RestPageController.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/filter/CORSFilter.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/filter/StatelessAuthenticationFilter.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/handler/RestErrorHandler.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/interceptor/AppInterceptor.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/RestAuthenticationEntryPoint.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/SpringSecurityConfig.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/handler/TokenHandler.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/model/AppPermission.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/model/UserAuthentication.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/service/TokenAuthenticationService.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/service/UserService.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/task/schedule/ScheduleTask.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/task/schedule/config/ScheduleTaskConfig.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/util/rest/JacksonConfiguration.java create mode 100644 jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/util/rest/RestUtil.java create mode 100644 jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonResult.java create mode 100644 jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonResultRetriever.java create mode 100644 jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewHttpEntityMethodProcessor.java create mode 100644 jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewMessageConverter.java create mode 100644 jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewResponseProcessor.java create mode 100644 jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewReturnValueHandler.java create mode 100644 jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java create mode 100644 jasamedika-pelayanan/src/main/resources/swagger.properties create mode 100644 jasamedika-pelayanan/src/main/webapp/WEB-INF/spring-security.xml create mode 100644 jasamedika-pelayanan/src/main/webapp/WEB-INF/springmvc-context.xml delete mode 100644 jasamedika-sdm/src/main/java/com/jasamedika/medifirst2000/controller/MapRuanganToAkomodasiController.java diff --git a/Medifirst2000/pom.xml b/Medifirst2000/pom.xml index 7a5d9f75..888c7aa9 100644 --- a/Medifirst2000/pom.xml +++ b/Medifirst2000/pom.xml @@ -22,6 +22,7 @@ ../jasamedika-reporting ../jasamedika-sdm ../jasamedika-web + ../jasamedika-pelayanan diff --git a/jasamedika-pelayanan/WebContent/META-INF/MANIFEST.MF b/jasamedika-pelayanan/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 00000000..254272e1 --- /dev/null +++ b/jasamedika-pelayanan/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/jasamedika-pelayanan/pom.xml b/jasamedika-pelayanan/pom.xml new file mode 100644 index 00000000..fcd502d9 --- /dev/null +++ b/jasamedika-pelayanan/pom.xml @@ -0,0 +1,298 @@ + + 4.0.0 + jasamedika-pelayanan + war + jasamedika-pelayanan + + com.jasamedika + Medifirst2000 + 1.0.0 + ../Medifirst2000/pom.xml + + + + commons-httpclient + commons-httpclient + 3.1 + + + io.socket + socket.io-client + 0.7.0 + + + + ${project.groupId} + jasamedika-config + ${project.version} + + + + ${project.groupId} + jasamedika-core + ${project.version} + + + + ${project.groupId} + jasamedika-domain + ${project.version} + + + + ${project.groupId} + jasamedika-business + ${project.version} + + + + junit + junit + 4.12 + test + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + + org.springframework + spring-web + ${org.springframework.version} + + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + + org.springframework + spring-aop + ${org.springframework.version} + + + + org.aspectj + aspectjtools + 1.7.4 + + + + + + javax.servlet + javax.servlet-api + ${servlet.version} + provided + + + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + + + commons-io + commons-io + ${commons-io.version} + runtime + + + + + com.jayway.restassured + rest-assured + ${rest-assured.version} + test + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson2.version} + + + + com.fasterxml.jackson.core + jackson-core + ${jackson2.version} + + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson2.version} + + + + + com.googlecode.json-simple + json-simple + ${json-simple.version} + + + org.codehaus.jackson + jackson-core-asl + ${jackson-core-asl.version} + + + org.codehaus.jackson + jackson-mapper-asl + ${jackson-mapper-asl.version} + + + + com.google.code.gson + gson + ${gson.version} + + + + com.monitorjbl + json-view + 0.10 + + + + io.jsonwebtoken + jjwt + 0.4 + + + + + com.mangofactory + swagger-springmvc + 0.6.5 + + + + + + + com.google.zxing + core + 2.2 + + + + + com.google.zxing + javase + 2.2 + + + + + com.google.zxing + zxing-parent + 3.2.0 + pom + + + + org.apache.poi + poi + 3.6 + jar + compile + + + + com.lowagie + itext + 2.1.7 + + + + + commons-digester + commons-digester + 2.1 + jar + compile + + + + org.springframework + spring-context-support + ${org.springframework.version} + + + + + net.sourceforge.barbecue + barbecue + 1.5-beta1 + + + + + net.sf.barcode4j + barcode4j + 2.1 + + + + + org.apache.xmlgraphics + batik-bridge + 1.7 + + + + + + commons-codec + commons-codec + ${commons-codec.version} + + + commons-collections + commons-collections + ${commons-collections.version} + + + + + + jasamedika-pelayanan + + + org.apache.maven.plugins + maven-compiler-plugin + 3.0 + + 1.8 + 1.8 + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.1 + + / + + + + + + Module Medifirst2000 untuk Web / Controller. Tempat API diexpose oleh REST Client. + + Jasa Medika + + diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/constants/Constants.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/constants/Constants.java new file mode 100644 index 00000000..568fc300 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/constants/Constants.java @@ -0,0 +1,78 @@ +package com.jasamedika.medifirst2000.constants; + +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; + +/** + * Constants value + * + * @author Roberto + */ +public class Constants { + public static final String JASAMEDIKA = "SkFTQU1FRElLQQ=="; + public static final String APP_VERSION = "APP_VERSION"; + + public static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN"; + + //for example + public static final String IDR = "IDR"; + public static final String RP = "RP"; + + public static final String COMMA = ","; + + public static final DecimalFormat ONE_COMA_FORMAT = new DecimalFormat("#.#"); + public static final DecimalFormat TWO_COMA_FORMAT = new DecimalFormat( + "#.##"); + + public static final DecimalFormat MONEY_FORMAT_WITHOUT_COMMA = new DecimalFormat( + "###,###"); + + public static final class DateFormat { + public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat( + "yyyyMMdd"); + public static final SimpleDateFormat dd_MMM_yyyy = new SimpleDateFormat( + "dd MMM yyyy"); + public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss"); + public static final SimpleDateFormat yyyy_MM_dd_T_HH_mm_ss = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss"); + public static final SimpleDateFormat yyyyMMdd_HH_mm_ss = new SimpleDateFormat( + "yyyyMMdd HH:mm:ss"); + } + + /* message */ + public static final class MessageInfo { + public static final String INFO_MESSAGE = "INFO_MESSAGE"; + public static final String WARNING_MESSAGE = "WARNING_MESSAGE"; + public static final String ERROR_MESSAGE = "ERROR_MESSAGE"; + public static final String EXCEPTION_MESSAGE = "EXCEPTION_MESSAGE"; + + } + + /* locale id (indonesia / default) and en (english) */ + public static final class Locale { + public static final String INA = "ina"; + public static final String EN = "en"; + + } + //Update perubahan di sini, harus disamakan dengan package yang ada di jasamedika-bussiness + //com.jasamedika.medifirst2000.logging.hibernate.async + public static final class HttpHeader { + public static final String SUPERVISING = "Supervising"; + public static final String MODULE = "Module"; + public static final String FORM = "Form"; + public static final String ACTION = "Action"; + + public static final String URL_FORM = "AlamatUrlForm"; // syamsu + public static final String KD_RUANGAN = "KdRuangan"; // syamsu + public static final String KD_RUANGAN_T = "KdRuanganT"; // syamsu + public static final String KD_RUANGAN_A = "KdRuanganA"; // syamsu + public static final String TGL_KIRIM = "tglKirim"; // syamsu +// public static final String RUANGAN_TUJUAN = "ruanganTujuan"; // syamsu +// public static final String ID_RUANGAN_TUJUAN_ALT = "ruanganTujuanAlt"; // syamsu + public static final String KD_USER = "KdUser"; // syamsu + + + } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/constants/MessageResource.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/constants/MessageResource.java new file mode 100644 index 00000000..d15ae2fc --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/constants/MessageResource.java @@ -0,0 +1,18 @@ +package com.jasamedika.medifirst2000.constants; + +/** + * MessageResource class is that consist of list key in message resource for + * internationalization + * + * @author Roberto + */ +public final class MessageResource { + + public static final String LABEL_SUCCESS = "label.success"; + public static final String LABEL_ERROR = "label.error"; + public static final String LABEL_TRY_AGAIN = "label.try_again"; + public static final String LABEL_SUCCESS_CREATED = "label.success.created"; + public static final String LABEL_SUCCESS_OK = "label.success.ok"; + public static final String LABEL_UPDATE_DATA_CUTI = "label.update.data.cuti"; + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/AkomodasiController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/AkomodasiController.java new file mode 100644 index 00000000..354dc220 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/AkomodasiController.java @@ -0,0 +1,161 @@ +package com.jasamedika.medifirst2000.controller; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.orm.jpa.JpaSystemException; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.jasamedika.medifirst2000.constants.Constants; +import com.jasamedika.medifirst2000.constants.MessageResource; +import com.jasamedika.medifirst2000.controller.base.LocaleController; +import com.jasamedika.medifirst2000.core.web.WebConstants; +import com.jasamedika.medifirst2000.exception.ServiceVOException; +import com.jasamedika.medifirst2000.service.MapRuanganToAkomodasiService; +import com.jasamedika.medifirst2000.service.RuanganService; +import com.jasamedika.medifirst2000.util.CommonUtil; +import com.jasamedika.medifirst2000.util.rest.RestUtil; +import com.jasamedika.medifirst2000.vo.MapRuanganToAkomodasiVO; + +@RestController +@RequestMapping("/akomodasi") +public class AkomodasiController extends LocaleController { + + private static final Logger LOGGER = LoggerFactory.getLogger(AkomodasiController.class); + + @Autowired + private MapRuanganToAkomodasiService mapRuanganToAkomodasiService; + + @Autowired + private RuanganService ruanganService; + + @RequestMapping(value = "/save-mapping", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> saveMappingAkomodasi(HttpServletRequest request, + @Valid @RequestBody MapRuanganToAkomodasiVO vo) { + Map result = new HashMap(); + try { + MapRuanganToAkomodasiVO resultVo = new MapRuanganToAkomodasiVO(); + if (CommonUtil.isNotNullOrEmpty(vo.getId())) { + resultVo = mapRuanganToAkomodasiService.update(vo); + } else { + resultVo = mapRuanganToAkomodasiService.add(vo); + } + result.put("data", resultVo); + if (CommonUtil.isNotNullOrEmpty(result)) { + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage); + } else { + return RestUtil.getJsonHttptatus(HttpStatus.NOT_ACCEPTABLE); + } + } catch (ServiceVOException sve) { + LOGGER.error("Got exception {} when add mapping akomodasi", sve.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when add mapping akomodasi", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/delete-mapping", method = RequestMethod.DELETE) + public ResponseEntity deleteMappingAkomodasi(HttpServletRequest request, @RequestParam("id") Integer id) { + try { + Boolean result = mapRuanganToAkomodasiService.delete(id); + if (result) { + return RestUtil.getJsonResponse("Mapping is deleted successsfully", HttpStatus.OK); + } else { + return RestUtil.getJsonHttptatus(HttpStatus.NOT_ACCEPTABLE); + } + } catch (ServiceVOException sve) { + LOGGER.error("Got exception {} when delete mapping akomodasi", sve.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when delete mapping akomodasi", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/get-all-mapping", method = RequestMethod.GET) + public ResponseEntity> getAllMappingAkomodasi(HttpServletRequest request) { + try { + List result = mapRuanganToAkomodasiService.getAllActiveAkomodasi(); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException sve) { + LOGGER.error("Got exception {} when get all mapping akomodasi", sve.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when get all mapping akomodasi", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/get-mapping", method = RequestMethod.GET) + public ResponseEntity getMappingAkomodasi(HttpServletRequest request, + @RequestParam("id") Integer id) { + try { + MapRuanganToAkomodasiVO result = mapRuanganToAkomodasiService.findById(id); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException sve) { + LOGGER.error("Got exception {} when get all mapping akomodasi", sve.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when get all mapping akomodasi", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/get-kamar-by-ruangan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity>> getKamarByRuangan(HttpServletRequest request, + @RequestParam(value = "idRuangan", required = true) Integer idRuangan) { + List> result = null; + try { + result = ruanganService.findKamarByRuangan(idRuangan); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + } catch (Exception e) { + e.printStackTrace(); + } + return RestUtil.getJsonResponse(result, HttpStatus.OK); + } + + @RequestMapping(value = "/get-akomodasi-ruangan-by-mapping-produk", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity>> getAkomodasiRuanganByMappingProduk(HttpServletRequest request, + @RequestParam(value = "idRuangan", required = true) Integer idRuangan) { + List> result = null; + try { + result = mapRuanganToAkomodasiService.getAkomodasiRuanganByMapProduk(idRuangan); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + } catch (Exception e) { + e.printStackTrace(); + } + return RestUtil.getJsonResponse(result, HttpStatus.OK); + } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/GenericServiceController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/GenericServiceController.java new file mode 100644 index 00000000..c2e3b5d9 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/GenericServiceController.java @@ -0,0 +1,163 @@ +package com.jasamedika.medifirst2000.controller; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Field; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.persistence.Column; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.servlet.http.HttpServletRequest; + +import org.json.JSONException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.jasamedika.medifirst2000.base.vo.BaseMasterVO; +import com.jasamedika.medifirst2000.base.vo.BaseModelVO; +import com.jasamedika.medifirst2000.base.vo.BaseTransactionVO; +import com.jasamedika.medifirst2000.controller.base.LocaleController; +import com.jasamedika.medifirst2000.service.ModelService; +import com.jasamedika.medifirst2000.util.JsonUtil; +import com.jasamedika.medifirst2000.util.rest.RestUtil; +import com.jasamedika.medifirst2000.vo.AntrianPasienRegistrasiVO; + +@RestController +@RequestMapping("/service") +public class GenericServiceController extends LocaleController { + + @Autowired + private ModelService modelService; + private static final String CONTENT_TYPE = "Content-Type"; + + @SuppressWarnings("rawtypes") + public static List GetFields(Class data) { + List items = new ArrayList(); + 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 getData(@RequestParam(value = "prefix", required = false) String prefix) { + + return RestUtil.getJsonResponse(GetSettingDataFixed(prefix), HttpStatus.CREATED, mapHeaderMessage); + } + + @RequestMapping(value = "/list-generic/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity>> listGeneric( + @RequestParam(value = "view", required = false) String entity, + @RequestParam(value = "select", required = false) String field, + @RequestParam(value = "take", required = false) Integer take, + @RequestParam(value = "skip", required = false) Integer skip, + @RequestParam(value = "page", required = false) Integer page, + @RequestParam(value = "pageSize", required = false) Integer pageSize, + @RequestParam(value = "filter[logic]", required = false) String logic, + @RequestParam(value = "filter[filters][0][value]", required = false) String value, + @RequestParam(value = "filter[filters][0][field]", required = false) String fieldS, + @RequestParam(value = "filter[filters][0][operator]", required = false) String operator, + @RequestParam(value = "filter[filters][0][ignoreCase]", required = false) String ignorecase, + @RequestParam(value = "criteria", required = false) String criteria, + @RequestParam(value = "values", required = false) String values, HttpServletRequest request) + throws SecurityException, ClassNotFoundException, JSONException, UnsupportedEncodingException { + + String data = request.getQueryString(); + data = URLDecoder.decode(data, "UTF-8"); + String[] arrQueries = data.split("&"); + for (String query : arrQueries) { + if (query.indexOf("filter[filters][0][filter][field]") >= 0) { + if (criteria == null) + criteria = query.replace("filter[filters][0][filter][field]=", ""); + else + criteria += "," + query.replace("filter[filters][0][filter][field]=", ""); + + } else if (query.indexOf("filter[filters][0][filter][value]") >= 0) { + if (values == null) + values = query.replace("filter[filters][0][filter][value]=", ""); + else + values += "," + query.replace("filter[filters][0][filter][value]=", ""); + } + } + + if (field.equals("*")) { + field = ""; + + for (Field fieldItem : GetFields(Class.forName("com.jasamedika.medifirst2000.entities." + entity))) { + { + String name = fieldItem.getName(); + if (name.equals("serialVersionsUID")) + continue; + Boolean valid = false; + for (java.lang.annotation.Annotation annotation : fieldItem.getDeclaredAnnotations()) { + if (annotation instanceof JoinColumn) { + valid = true; + } else if (annotation instanceof Column) { + Column column = (Column) annotation; + if (column.name().endsWith("Fk")) + if (fieldItem.getName().endsWith("Id") == false) + valid = true; + } else if (annotation instanceof OneToMany) { + + valid = true; + } + + } + if (valid == false) + if (field.equals("")) + field += fieldItem.getName(); + else + field += "," + fieldItem.getName(); + } + } + } else if (field.equals("**")) { + field = "*"; + } + + // for dateformat using [date] + List> modelGenericVO = modelService.getAllData(entity, field, take, skip, page, pageSize, + logic, value, fieldS, operator, ignorecase, criteria, values); + HttpHeaders headers = new HttpHeaders(); + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + try { + return new ResponseEntity>>(JsonUtil.ToMaps(modelGenericVO), headers, + HttpStatus.OK); + } catch (IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + } + + return null; + } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/KonsultasiController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/KonsultasiController.java new file mode 100644 index 00000000..b0d5405d --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/KonsultasiController.java @@ -0,0 +1,162 @@ +package com.jasamedika.medifirst2000.controller; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.orm.jpa.JpaSystemException; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.jasamedika.medifirst2000.constants.Constants; +import com.jasamedika.medifirst2000.constants.MessageResource; +import com.jasamedika.medifirst2000.controller.base.IBaseRestController; +import com.jasamedika.medifirst2000.controller.base.LocaleController; +import com.jasamedika.medifirst2000.core.web.WebConstants; +import com.jasamedika.medifirst2000.exception.ServiceVOException; +import com.jasamedika.medifirst2000.service.KonsultasiService; +import com.jasamedika.medifirst2000.service.RegistrasiPelayananService; +import com.jasamedika.medifirst2000.util.rest.RestUtil; +import com.jasamedika.medifirst2000.vo.GridAntrianPasienDiPeriksaVO; +import com.jasamedika.medifirst2000.vo.KonsultasiVO; + +/** + * Controller class for KonsultasiController + * + * @author Askur + */ +@RestController +@RequestMapping("/konsultasi") +@JsonIgnoreProperties(ignoreUnknown = true) +public class KonsultasiController extends LocaleController implements + IBaseRestController { + + private static final Logger LOGGER = LoggerFactory.getLogger(KonsultasiController.class); + + @Autowired + private KonsultasiService konsultasiService; + + @Autowired + private RegistrasiPelayananService registrasiPelayananService; + + @RequestMapping(value = "/save-konsultasi", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> save(@Valid @RequestBody KonsultasiVO vo,HttpServletRequest request) { + try { + Map result = konsultasiService.addKonsultasi2(vo); + if (null != result){ + mapHeaderMessage.clear(); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS,getMessage(MessageResource.LABEL_SUCCESS,request )); + }else{ + mapHeaderMessage.clear(); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_ERROR,getMessage(MessageResource.LABEL_ERROR,request )); + } + SaveLog("Konsultasi", "Dokter",request); + return RestUtil.getJsonResponse(result, HttpStatus.CREATED,mapHeaderMessage); + + } catch (ServiceVOException e) { + LOGGER.error("Got exception {} when add kebutuhan dasar", e.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when add kebutuhan dasar", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + + } + + @RequestMapping(value = "/antrian-pasien-list-konsul/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> getAllVOWithQueryString( + @RequestParam(value = "page", required = false, defaultValue = "1") Integer page, + @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit, + @RequestParam(value = "sort", required = false, defaultValue = "noRec") String sort, + @RequestParam(value = "dir", required = false, defaultValue = "asc") String dir, + @RequestParam(value = "ruanganId", required = false) Integer ruanganId, + @RequestParam(value = "dateStart", required = false) String dateStart, + @RequestParam(value = "dateEnd", required = false) String dateEnd, + @RequestParam(value = "noCm", required = false) String noCm, + @RequestParam(value = "pegawaiId", required = false) Integer pegawaiId) { + Map resultPageMap = registrasiPelayananService.findAllAntrianPagingKonsultasi(page, limit, sort, dir, + ruanganId, dateStart, dateEnd, noCm, pegawaiId); + + return constructListPageResult(resultPageMap); + } + + @Override + public ResponseEntity> getAllVOWithQueryString(HttpServletRequest request, + Integer page, Integer limit, String sort, String dir) { + return null; + } + + @Override + public ResponseEntity getVO(Integer id) { + return null; + } + + @Override + public ResponseEntity addVO(KonsultasiVO vo) { + return null; + } + + @Override + public ResponseEntity editVO(KonsultasiVO vo) { + return null; + } + + @Override + public ResponseEntity deleteVO(Integer id) { + return null; + } + + @Override + public ResponseEntity> getAllVO() { + return null; + } + + @RequestMapping(value = "/get-riwayat-konsultasi/{noCm}/{startDate}/{endDate}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity>> getRiwayatKonsultasi(@PathVariable("noCm") String noCm,@PathVariable("startDate") String startDate, + @PathVariable("endDate") String endDate,HttpServletRequest request) { + List> result = null; + try { + + result = konsultasiService.getRiwayatKonsultasi(noCm, startDate, endDate); + + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + } catch (Exception e) { + e.printStackTrace(); + } + return RestUtil.getJsonResponse(result, HttpStatus.OK); + } + + @RequestMapping(value = "/get-konsultasi-kosong", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity>> getKonsultasiKosong(HttpServletRequest request, + @RequestParam(value = "tglAwal", required = true) String strTglAwal, + @RequestParam(value = "tglAkhir", required = true) String strTglAkhir) { + List> 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); + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/PelayananController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/PelayananController.java new file mode 100644 index 00000000..0599abfd --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/PelayananController.java @@ -0,0 +1,239 @@ +package com.jasamedika.medifirst2000.controller; + +import com.jasamedika.medifirst2000.constants.Constants; +import com.jasamedika.medifirst2000.constants.MessageResource; +import com.jasamedika.medifirst2000.controller.base.LocaleController; +import com.jasamedika.medifirst2000.core.web.WebConstants; +import com.jasamedika.medifirst2000.dto.TagihanPendaftaranDto; +import com.jasamedika.medifirst2000.exception.ServiceVOException; +import com.jasamedika.medifirst2000.service.PasienDaftarService; +import com.jasamedika.medifirst2000.service.PelayananPasienService; +import com.jasamedika.medifirst2000.service.ProdukService; +import com.jasamedika.medifirst2000.service.SatuanStandarService; +import com.jasamedika.medifirst2000.util.rest.RestUtil; +import com.jasamedika.medifirst2000.vo.PelayananPasienVO; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.orm.jpa.JpaSystemException; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/pelayanan") +public class PelayananController extends LocaleController { + + private static final Logger LOGGER = LoggerFactory.getLogger(PelayananController.class); + + @Autowired + private PelayananPasienService pelayananPasienService; + + @Autowired + private PasienDaftarService pasienDaftarService; + + @Autowired + private ProdukService produkService; + + @Autowired + private SatuanStandarService satuanStandarService; + + @RequestMapping(value = "/calculate-indikator-pelayanan", method = RequestMethod.GET) + public ResponseEntity>> calculateIndikatorPelayanan(HttpServletRequest request, + @RequestParam("tahun") String tahun) { + try { + List> result = pasienDaftarService.findIndikatorPelayanan(tahun); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException sve) { + LOGGER.error("Got exception {} when calculate indikator pelayanan", sve.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when calculate indikator pelayanan", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/validate-nama-produk", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> validateNamaProduk(HttpServletRequest request, + @RequestParam(value = "idProduk", required = false) Integer idProduk, + @RequestParam(value = "namaProduk") String namaProduk) { + try { + Map result = produkService.validateNamaProduk(idProduk, namaProduk); + + return RestUtil.getJsonResponse(result, HttpStatus.OK); + } catch (ServiceVOException e) { + LOGGER.error("Got exception {} when validate nama produk", 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 validate nama produk", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/paket-to-produk", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> getMappingPaketToProduk(HttpServletRequest request, + @RequestParam(value = "idMapping") Integer idMapping) { + try { + Map result = produkService.getMappingPaketToProduk(idMapping); + return RestUtil.getJsonResponse(result, HttpStatus.OK); + } catch (ServiceVOException e) { + LOGGER.error("Got exception {} when get mapping paket to produk", 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 get mapping paket to produk", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/all-paket-produk", method = RequestMethod.GET) + public ResponseEntity>> getAllPaketToProduk(HttpServletRequest request) { + try { + List> result = produkService.getAllPaketToProduk(); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException sve) { + LOGGER.error("Got exception {} when get all data paket to produk", sve.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when get all data paket to produk", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/master-satuan-standar", method = RequestMethod.GET) + public ResponseEntity>> getAllMasterSatuanStandar(HttpServletRequest request) { + try { + List> result = satuanStandarService.getAll(); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException sve) { + LOGGER.error("Got exception {} when get all master satuan standar distinct on", sve.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, sve.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when get all master satuan standar distinct on", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/klaim-diskon", method = RequestMethod.GET) + public ResponseEntity> KlaimDiskon(HttpServletRequest request, + @RequestParam(value = "noRegistrasi") String noRegistrasi, + @RequestParam(value = "totalKlaim") Double totalKlaim, + @RequestParam(value = "jenisDiskon") Integer jenisDiskon) { + try { + List result = pelayananPasienService.updateKlaimDiskon(noRegistrasi, totalKlaim, jenisDiskon); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException e) { + LOGGER.error("Got exception {} when klaim diskon karyawan", 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 klaim diskon karyawan", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/reset-klaim-diskon", method = RequestMethod.GET) + public ResponseEntity ResetKlaimDiskon(HttpServletRequest request, + @RequestParam(value = "noRegistrasi") String noRegistrasi) { + try { + String result = pelayananPasienService.resetKlaimDiskon(noRegistrasi); + + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException e) { + LOGGER.error("Got exception {} when klaim diskon karyawan", 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 klaim diskon karyawan", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/check-existing-harga-produk-kelas", method = RequestMethod.GET) + public ResponseEntity>> checkExistingHargaProdukKelas(HttpServletRequest request, + @RequestParam(value = "kelasId") Integer idKelas, @RequestParam(value = "produkId") Integer idProduk, + @RequestParam(value = "mappingId", required = false) Integer idMapping) { + try { + List> result = produkService.findExistingMapHargaKelas(idKelas, idProduk, idMapping); + + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException e) { + LOGGER.error("Got exception {} when check existing harga produk kelas", 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 check existing harga produk kelas", jse.getMessage()); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/tagihan/daftar/{noRegistrasi}", method = RequestMethod.GET) + public ResponseEntity> daftarTagihan(HttpServletRequest request, + @PathVariable String noRegistrasi) { + try { + List result = pelayananPasienService.tagihan(noRegistrasi); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(result, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException e) { + LOGGER.error("Got exception {} when get daftar tagihan {}", e.getMessage(), noRegistrasi); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when get daftar tagihan {}", jse.getMessage(), noRegistrasi); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } + + @RequestMapping(value = "/tagihan/diskon/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity simpanDiskonTagihan(HttpServletRequest request, + @RequestBody List dtoList) { + try { + pelayananPasienService.diskonTagihan(dtoList); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, + getMessage(MessageResource.LABEL_SUCCESS, request)); + return RestUtil.getJsonResponse(dtoList, HttpStatus.OK, mapHeaderMessage); + } catch (ServiceVOException e) { + LOGGER.error("Got exception {} when simpan diskon tagihan {}", e.getMessage(), null); + Map error = new HashMap(); + error.put("bad-request", e.getMessage()); + return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, error); + } catch (JpaSystemException jse) { + LOGGER.error("Got exception {} when simpan diskon tagihan {}", jse.getMessage(), null); + addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage()); + return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage); + } + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/BaseRestController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/BaseRestController.java new file mode 100644 index 00000000..0e73c735 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/BaseRestController.java @@ -0,0 +1,42 @@ +package com.jasamedika.medifirst2000.controller.base; + +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.BaseVO; + +/** + * Base Rest Operation for Controller Class + * + * @author Roberto + */ +public interface BaseRestController extends + RestPageController { + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity getVO(@PathVariable("id") String id); + + @RequestMapping(value = "/", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity addVO(@RequestBody V vo); + + @RequestMapping(value = "/", method = RequestMethod.POST, consumes = { "application/json" }) + @ResponseBody + public ResponseEntity editVO(@RequestBody V vo); + + // @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) + // @ResponseBody + // public ResponseEntity deleteVO(@PathVariable("id") Integer id); + + // @RequestMapping(value = "/", method = RequestMethod.GET) + // @ResponseBody + // public ResponseEntity> getAllVO(); + + + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/IBaseRestController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/IBaseRestController.java new file mode 100644 index 00000000..4a59c5b4 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/IBaseRestController.java @@ -0,0 +1,42 @@ +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 extends + IRestPageController { + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity getVO(@PathVariable("id") Integer id); + + @RequestMapping(value = "/", method = RequestMethod.PUT, consumes = { "application/json" }) + @ResponseBody + public ResponseEntity addVO(@RequestBody V vo); + + @RequestMapping(value = "/", method = RequestMethod.POST, consumes = { "application/json" }) + @ResponseBody + public ResponseEntity editVO(@RequestBody V vo); + + @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) + @ResponseBody + public ResponseEntity deleteVO(@PathVariable("id") Integer id); + + @RequestMapping(value = "/", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> getAllVO(); + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/IRestPageController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/IRestPageController.java new file mode 100644 index 00000000..f9f7f890 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/IRestPageController.java @@ -0,0 +1,41 @@ +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 { + /** + * + * @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> 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); +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/LocaleController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/LocaleController.java new file mode 100644 index 00000000..943235fa --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/LocaleController.java @@ -0,0 +1,328 @@ +package com.jasamedika.medifirst2000.controller.base; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Type; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.jasamedika.medifirst2000.base.vo.BaseModelVO; +import com.jasamedika.medifirst2000.constants.Constants; +import com.jasamedika.medifirst2000.converter.BaseConverterImpl; +import com.jasamedika.medifirst2000.core.web.WebConstants; +import com.jasamedika.medifirst2000.entities.Pegawai; +import com.jasamedika.medifirst2000.service.ActivityPegawaiService; +import com.jasamedika.medifirst2000.service.LoginUserService; +import com.jasamedika.medifirst2000.service.ModelService; +import com.jasamedika.medifirst2000.util.rest.RestUtil; +import com.jasamedika.medifirst2000.vo.ModelVO; +import com.jasamedika.medifirst2000.vo.PasienVO; +import com.jasamedika.medifirst2000.vo.PegawaiVO; + +import io.socket.client.IO; + +/** + * Base Controller Class for handling messaga resource for internationalization + * & locale + * + * @author Roberto + */ +public abstract class LocaleController { + + /* + * messageSource bean injected for each controller for accessing message + * source + */ + @Autowired + private ActivityPegawaiService activityPegawaiServiceImpl; + + @Autowired + private BaseConverterImpl pegawaiConverter; + + @Autowired + private LoginUserService loginUserService; + + @Autowired + private MessageSource messageSource; + + @SuppressWarnings("rawtypes") + @Autowired + private ModelService modelService; + + protected Map mapHeaderMessage = new HashMap(); + + /* + * code locale + */ + protected String getMessage(String code, HttpServletRequest request) { + return messageSource.getMessage(code, null, new Locale(getCoociesLanguage(request))); + } + + protected void SaveLog(String keterangan, String group, HttpServletRequest request) { + activityPegawaiServiceImpl.record( + pegawaiConverter.transferModelToVO(loginUserService.getLoginUser().getPegawai(), new PegawaiVO()), + new Date(), keterangan, group); + } + + protected Object getItem(HttpServletRequest request, Object vo) { + BufferedReader reader; + String read = null; + String resultData = ""; + Gson gson = new Gson(); + try { + reader = new BufferedReader(new InputStreamReader(request.getInputStream())); + + while ((read = reader.readLine()) != null) { + resultData += read; + System.out.println(read); + } + + gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); + } catch (IOException e) { + e.printStackTrace(); + } + return vo = gson.fromJson(resultData, vo.getClass()); + } + + protected Object getItem2(HttpServletRequest request, Object vo) { + BufferedReader reader; + String read = null; + String resultData = ""; + Gson gson = new Gson(); + try { + reader = new BufferedReader(new InputStreamReader(request.getInputStream())); + + while ((read = reader.readLine()) != null) { + resultData += read; + System.out.println(read); + } + GsonBuilder gsonBuilder = new GsonBuilder(); + gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() { + @Override + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + if (json.getAsString() instanceof String) { + return new Date(); + } else { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + } + }); + gson = gsonBuilder.create(); + } catch (IOException e) { + e.printStackTrace(); + } + return vo = gson.fromJson(resultData, vo.getClass()); + } + + @RequestMapping(value = "/lang/{lang}", method = RequestMethod.GET) + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, + @PathVariable("lang") String lang) throws Exception { + + Cookie[] cookies = request.getCookies(); + List cookieList = new ArrayList(); + if (cookies != null) { + cookieList = Arrays.asList(cookies); + for (Cookie cookie : cookieList) { + if (cookie.getName().equals("lang")) { + cookie.setValue(null); + cookie.setMaxAge(0); + cookie.setPath("/"); + response.addCookie(cookie); + } + } + } + + if (lang.equalsIgnoreCase("en")) { + Cookie c = new Cookie("lang", "en"); + c.setPath("/"); + c.setDomain("localhost"); + response.addCookie(c); + } else if (lang.equalsIgnoreCase("cn")) { + Cookie c = new Cookie("lang", "cn"); + c.setPath("/"); + c.setDomain("localhost"); + response.addCookie(c); + } else if (lang.equalsIgnoreCase("ina")) { + Cookie c = new Cookie("lang", "ina"); + c.setPath("/"); + c.setDomain("localhost"); + response.addCookie(c); + } + + return true; + } + + /* + * default locale ID + */ + protected String getMessage(String code) { + return messageSource.getMessage(code, null, new Locale(Constants.Locale.INA)); + } + + protected void addHeaderMessage(String key, String message) { + this.mapHeaderMessage.put(key, message); + } + + @RequestMapping(value = "/entity-serelize/{entity}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity serializeEntity(@PathVariable("entity") String entity, HttpServletRequest request) { + ModelVO modelDTO = modelService.getModelSerializeEntity(entity, getCoociesLanguage(request)); + return RestUtil.getJsonResponse(modelDTO, HttpStatus.OK); + } + + public String getCoociesLanguage(HttpServletRequest request) { + Cookie cookie[] = request.getCookies(); + Cookie cook; + String lang = Constants.Locale.INA; + if (cookie != null) { + for (int i = 0; i < cookie.length; i++) { + cook = cookie[i]; + if (cook.getName().equalsIgnoreCase("lang")) + lang = cook.getValue(); + } + } + + return lang; + + } + + @SuppressWarnings("rawtypes") + protected ResponseEntity constructListPageResult(Map map) { + + if (map == null) { + Map mapHeaderMessage = new HashMap(); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER, "0"); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER, "0"); + mapHeaderMessage.put(Constants.MessageInfo.ERROR_MESSAGE, "Data not found."); + return RestUtil.getJsonResponse(null, HttpStatus.BAD_REQUEST, mapHeaderMessage); + } else { + @SuppressWarnings("unchecked") + Collection vos = (Collection) map.get(WebConstants.PageParameter.LIST_DATA); + + Map mapHeaderMessage = new HashMap(); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_PAGE_HEADER, + String.valueOf(map.get(WebConstants.PageParameter.TOTAL_PAGES))); + mapHeaderMessage.put(WebConstants.HttpHeaderInfo.TOTAL_COUNT_HEADER, + String.valueOf(map.get(WebConstants.PageParameter.TOTAL_ELEMENTS))); + + return RestUtil.getJsonResponse(vos, HttpStatus.OK, mapHeaderMessage); + } + } + + public String GetSettingDataFixed(String prefix) { + return activityPegawaiServiceImpl.GetSettingDataFixed(prefix); + } + + protected void BroadcastMessage(final String to, final Object data) { + final io.socket.client.Socket socket; + try { + String url = GetSettingDataFixed("UrlSocketMessaging"); + socket = IO.socket(url); + + socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() { + + @Override + public void call(Object... args) { + + try { + Gson gson = new Gson(); + String json = gson.toJson(data); + JSONObject item = new JSONObject( + "{\"to\":\"" + to + "\",\"message\":\"" + json.replace("\"", "'") + "\"}"); + socket.emit("subscribe", item); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + }); + socket.connect(); + } catch (URISyntaxException e) { + e.printStackTrace(); + } + } + + protected void BroadcastMessage(final String to, final String data) { + final io.socket.client.Socket socket; + try { + socket = IO.socket(GetSettingDataFixed("UrlSocketMessaging")); + + socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() { + + @Override + public void call(Object... args) { + + try { + JSONObject item = new JSONObject("{\"to\":\"" + to + "\",\"message\":\"" + data + "\"}"); + socket.emit("subscribe", item); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + }); + socket.connect(); + } catch (URISyntaxException e) { + e.printStackTrace(); + } + } + + protected void BroadcastMessageOther(final String to, final Object data) { + final io.socket.client.Socket socket; + try { + String url = GetSettingDataFixed("UrlSocketMessaging"); + socket = IO.socket(url); + + socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() { + + @Override + public void call(Object... args) { + try { + Map result = new HashMap<>(); + result.put("message", data); + result.put("to", to); + + Gson gson = new Gson(); + JSONObject item = new JSONObject(gson.toJson(result)); + socket.emit("subscribe", item); + } catch (JSONException e) { + e.printStackTrace(); + } + } + }); + socket.connect(); + } catch (URISyntaxException e) { + e.printStackTrace(); + } + } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/ParamRestController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/ParamRestController.java new file mode 100644 index 00000000..30a686df --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/ParamRestController.java @@ -0,0 +1,78 @@ +package com.jasamedika.medifirst2000.controller.base; + +import java.util.List; + +import org.springframework.core.GenericTypeResolver; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +import com.jasamedika.medifirst2000.base.vo.BaseModelVO; +import com.jasamedika.medifirst2000.constants.Constants; +import com.jasamedika.medifirst2000.util.rest.RestUtil; +import com.monitorjbl.json.JsonResult; +import com.monitorjbl.json.JsonView; +import com.monitorjbl.json.Match; + +/** + * Base Controller Class for handling "include" parameter to controller + * @see https://github.com/monitorjbl/json-view + * + * @author Roberto + */ +public abstract class ParamRestController { + private JsonResult jsonResult = JsonResult.instance(); + + /* + * Belum selesai, baru di parameter includes. Untuk field object juga belom. + * example : + * http://localhost:8080/jasamedika-web/{typeVOClass}/list-using-param + * ?includes =id,nama + */ + @RequestMapping(value = "/list-using-param", method = RequestMethod.GET) + public ResponseEntity> listUsingParam( + @RequestParam(value = "includes", required = false) String includes, + @RequestParam(value = "excludes", required = false) String excludes) { + List listVO = getAllVOFromService(); + String[] arrExcludes = null; + String[] arrIncludes = null; + if (excludes != null) + arrExcludes = excludes.split(Constants.COMMA); + if (includes != null) + arrIncludes = includes.split(Constants.COMMA); + if (arrExcludes != null && arrIncludes != null) { + listVO = jsonResult.use( + JsonView.with(listVO).onClass( + getClazz(), + Match.match().exclude(arrExcludes) + .include(arrIncludes))).returnValue(); + } + if (arrExcludes != null && arrIncludes == null) { + listVO = jsonResult.use( + JsonView.with(listVO).onClass(getClazz(), + Match.match().include("*").exclude(arrExcludes))) + .returnValue(); + } + if (arrExcludes == null && arrIncludes != null) { + listVO = jsonResult.use( + JsonView.with(listVO).onClass(getClazz(), + Match.match().exclude("*").include(arrIncludes))) + .returnValue(); + } + + return RestUtil.getJsonResponse(listVO, HttpStatus.OK); + } + + @SuppressWarnings("unchecked") + protected Class getClazz() { + return (Class) GenericTypeResolver.resolveTypeArgument(getClass(), + ParamRestController.class); + } + + /* + * method untuk mendapatkan all VO from service + * */ + protected abstract List getAllVOFromService(); +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/RestPageController.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/RestPageController.java new file mode 100644 index 00000000..2cdcfbf0 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/controller/base/RestPageController.java @@ -0,0 +1,38 @@ +package com.jasamedika.medifirst2000.controller.base; + +import java.util.Collection; + +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.BaseVO; + +/** + * Base Rest Operation for 'pagination' Controller Class + * + * @author Roberto + */ +public interface RestPageController { + /** + * + * @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> getAllVOWithQueryString( + @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); +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/filter/CORSFilter.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/filter/CORSFilter.java new file mode 100644 index 00000000..dc983afb --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/filter/CORSFilter.java @@ -0,0 +1,188 @@ +package com.jasamedika.medifirst2000.filter; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Iterator; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import com.jasamedika.medifirst2000.constants.Constants; + +/** + * CORSFilter class + * + * @author Roberto + */ +@Component +public class CORSFilter implements Filter { + + // Start Syamsu + private static class RequestWrapper extends HttpServletRequestWrapper { + final String body; + + public RequestWrapper(ServletRequest req) throws IOException { + super((HttpServletRequest) req); + + HttpServletRequest request = (HttpServletRequest) req; + + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader reader = null; + try { + InputStream inputStream = request.getInputStream(); + if (inputStream != null) { + reader = new BufferedReader(new InputStreamReader(inputStream)); + String hasil; + while ( (hasil = reader.readLine()) != null) { + stringBuilder.append(hasil); + } + } else { + stringBuilder.append(""); + } + } catch (IOException ex) { + throw ex; + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ex) { + throw ex; + } + } + } + body = stringBuilder.toString(); + + String idRuanganTujuan = request.getHeader(Constants.HttpHeader.KD_RUANGAN_T) == null ? "" + : request.getHeader(Constants.HttpHeader.KD_RUANGAN_T); + + if ("".equals(idRuanganTujuan.trim())){ + try{ + JSONObject jObject = new JSONObject(body); + ExtractObjectJson(jObject, false); + }catch(Exception e){ + + } + } + } + + public String getHeader(String key){ + if (key.equals(Constants.HttpHeader.KD_RUANGAN_A)) { + if (autoIdTujuan.length() > 0){ + return autoIdTujuan.toString(); + } + } + + return super.getHeader(key); + } + + JSONArray autoIdTujuan = new JSONArray(); + + void ExtractObjectJson(JSONObject jObject, boolean ruangan) throws Exception{ + Iterator iterator = jObject.keys(); + while (iterator.hasNext()){ + String key = String.valueOf(iterator.next()); + Object o = jObject.get(key); + + if (key.toLowerCase().contains("ruangan")){ + if (o instanceof Integer){ + autoIdTujuan.put(o); + } else if (o instanceof JSONObject){ + ExtractObjectJson((JSONObject) o, true); + } + } else if (ruangan && "id".equals(key)){ + if (o instanceof Integer){ + autoIdTujuan.put(o); + return; + } + } else if (o instanceof JSONObject && !ruangan) { + ExtractObjectJson((JSONObject) o, false); + } + } + } + + @Override + public ServletInputStream getInputStream() throws IOException { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); + ServletInputStream servletInputStream = new ServletInputStream() { + public int read() throws IOException { + return byteArrayInputStream.read(); + } + }; + return servletInputStream; + } + + @Override + public BufferedReader getReader() throws IOException { + return new BufferedReader(new InputStreamReader(getInputStream())); + } + + public String getBody() { + return this.body; + } + } + // End Syamsu + + + private final Logger log = LoggerFactory.getLogger(CORSFilter.class); + + public CORSFilter() { + log.info("CORSFilter JasaMedika Web init"); + } + + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException { + + // Start Syamsu + RequestWrapper myReq = new RequestWrapper((HttpServletRequest) req); + // End Syamsu + HttpServletRequest request = (HttpServletRequest) myReq; + HttpServletResponse response = (HttpServletResponse) res; + + response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); + response.setHeader("Access-Control-Allow-Credentials", "true"); + + response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "3600"); + response.setHeader("Access-Control-Allow-Headers", + "Content-Type, Accept, X-Requested-With, remember-me, X-AUTH-TOKEN, " + + "Supervising, RequestSupervisor, Module, Form, Action, AlamatUrlForm, KdRuangan, KdUser, " + + "MandatoriData, idRuanganTujuan, ruanganTujuan"); + response.setHeader("Content-Type", "application/json;application/octet-stream"); + + +// String body = myReq.getBody(); +// if (!"".equals(body.trim())){ +// log.info("\n\n" + myReq.getBody() + "\n"); +// } + + chain.doFilter(myReq, res); + } + + @Override + public void init(FilterConfig filterConfig) { + + } + + @Override + public void destroy() { + } + +} \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/filter/StatelessAuthenticationFilter.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/filter/StatelessAuthenticationFilter.java new file mode 100644 index 00000000..cc1c7452 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/filter/StatelessAuthenticationFilter.java @@ -0,0 +1,67 @@ +package com.jasamedika.medifirst2000.filter; + +import io.jsonwebtoken.MalformedJwtException; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; + +import com.fasterxml.jackson.core.JsonParseException; +import com.jasamedika.medifirst2000.constants.Constants; +import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService; + +/** + * StatelessAuthenticationFilter class + * + * @author Roberto + */ +public class StatelessAuthenticationFilter extends GenericFilterBean { + private final TokenAuthenticationService authenticationService; + + public StatelessAuthenticationFilter( + TokenAuthenticationService authenticationService) { + this.authenticationService = authenticationService; + } + + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse res = (HttpServletResponse) response; + + res.setHeader("Access-Control-Allow-Origin", + req.getHeader("Origin")); + res.setHeader("Access-Control-Allow-Credentials", "true"); + + res.setHeader("Access-Control-Allow-Methods", + "POST, GET, OPTIONS, DELETE"); + res.setHeader("Access-Control-Max-Age", "3600"); + res.setHeader("Access-Control-Allow-Headers", + "Content-Type, Accept, X-Requested-With, remember-me, X-AUTH-TOKEN, Supervising, " + + "RequestSupervisor, Module, Form, Action, AlamatUrlForm, KdRuangan, KdUser, " + + "MandatoriData"); + + Authentication authentication = null; + try { + + authentication = authenticationService.getAuthentication(httpRequest); + } catch (JsonParseException | MalformedJwtException e) { + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.addHeader(Constants.MessageInfo.ERROR_MESSAGE, + "Error Token (Not Valid Token)"); + filterChain.doFilter(request, response); + } + SecurityContextHolder.getContext().setAuthentication(authentication); + filterChain.doFilter(request, response); + SecurityContextHolder.getContext().setAuthentication(null); + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/handler/RestErrorHandler.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/handler/RestErrorHandler.java new file mode 100644 index 00000000..156f2099 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/handler/RestErrorHandler.java @@ -0,0 +1,100 @@ +package com.jasamedika.medifirst2000.handler; + +import java.util.List; +import java.util.Locale; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; +import org.springframework.validation.BindingResult; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import com.jasamedika.medifirst2000.base.vo.validation.ValidationErrorVO; +import com.jasamedika.medifirst2000.constants.Constants;; + +/** + * Exception Handler Rest Controller class + * + * @author Roberto + */ + +@ControllerAdvice +@Order(1) // Pertama masuk +public class RestErrorHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(RestErrorHandler.class); + + private MessageSource messageSource; + + @Autowired + public RestErrorHandler(MessageSource validationNessageSource) { + this.messageSource = validationNessageSource; + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ResponseBody + public ValidationErrorVO processValidationError(MethodArgumentNotValidException ex) { + LOGGER.warn("Handling data validation error"); + BindingResult result = ex.getBindingResult(); + List fieldErrors = result.getFieldErrors(); + + return processFieldErrors(fieldErrors); + } + + private ValidationErrorVO processFieldErrors(List fieldErrors) { + ValidationErrorVO dto = new ValidationErrorVO(); + + for (FieldError fieldError : fieldErrors) { + dto.addFieldError(fieldError.getField(), fieldError.getDefaultMessage()); + } + + return dto; + } + + /* + * resolve error message with parameter locale + */ + private String resolveLocalizedErrorMessage(FieldError fieldError, String locale) { + Locale currentLocale = LocaleContextHolder.getLocale(); + String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale); + + // If the message was not found, return the most accurate field error + // code instead. + // You can remove this check if you prefer to get the default error + // message. + if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) { + String[] fieldErrorCodes = fieldError.getCodes(); + localizedErrorMessage = fieldErrorCodes[0]; + } + + return localizedErrorMessage; + } + + /* + * resolve error message with default locale + */ + private String resolveLocalizedErrorMessage(FieldError fieldError) { + String localizedErrorMessage = messageSource.getMessage(fieldError, new Locale(Constants.Locale.INA)); + + // If the message was not found, return the most accurate field error + // code instead. + // You can remove this check if you prefer to get the default error + // message. + if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) { + String[] fieldErrorCodes = fieldError.getCodes(); + localizedErrorMessage = fieldErrorCodes[0]; + } + + return localizedErrorMessage; + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/interceptor/AppInterceptor.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/interceptor/AppInterceptor.java new file mode 100644 index 00000000..bb5fd62f --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/interceptor/AppInterceptor.java @@ -0,0 +1,770 @@ +package com.jasamedika.medifirst2000.interceptor; + +import java.lang.reflect.Method; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.ArrayUtils; +import org.json.JSONArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import com.jasamedika.medifirst2000.constants.Constants; +import com.jasamedika.medifirst2000.dao.LoginUserDao; +import com.jasamedika.medifirst2000.dao.NotifikasiMessageObjekModulDao; +import com.jasamedika.medifirst2000.dao.RuanganDao; +import com.jasamedika.medifirst2000.entities.KelompokUser; +import com.jasamedika.medifirst2000.entities.LoginUser; +import com.jasamedika.medifirst2000.entities.MapObjekModulToKelompokUser; +import com.jasamedika.medifirst2000.entities.MapObjekModulToLoginUser; +import com.jasamedika.medifirst2000.entities.Pegawai; +import com.jasamedika.medifirst2000.entities.Ruangan; +import com.jasamedika.medifirst2000.notification.MessagePublisher; +import com.jasamedika.medifirst2000.notification.MessageSubscriber; +import com.jasamedika.medifirst2000.security.model.AppPermission; +import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService; +import com.jasamedika.medifirst2000.service.MapObjekModulToKelompokUserService; +import com.jasamedika.medifirst2000.service.MapObjekModulToLoginUserService; +import com.jasamedika.medifirst2000.service.NotifMessagingSchedulerService; +import com.jasamedika.medifirst2000.service.NotifMessagingService; +import com.jasamedika.medifirst2000.service.NotifikasiMessageObjekModulService; +import com.jasamedika.medifirst2000.service.ObjekModulAplikasiService; +import com.jasamedika.medifirst2000.util.CommonUtil; +import com.jasamedika.medifirst2000.util.DateUtil; +import com.jasamedika.medifirst2000.vo.NotifMessagingSchedulerVO; +import com.jasamedika.medifirst2000.vo.NotifMessagingVO; +import com.jasamedika.medifirst2000.vo.NotifikasiMessageObjekModulVO; +import com.jasamedika.medifirst2000.vo.ObjekModulAplikasiVO; + +/** + * Interceptor class for All annotation method controller @AppPermission + * + * @author Roberto + * + * direka ulang oleh Syamsu + */ + +public class AppInterceptor implements HandlerInterceptor { + + private static final String[] PRINT_PATTERN = {"/lap_", "/lap-", "/lap", "/cetak_", "/cetak-", "/print_", "/print-" }; + + private static final String[] ADD_PATTERN = {"/save_", "/save-", "/add_", "/add-", "/simpan_", "/simpan-"}; + + private static final String[] UPDATE_PATTERN = {"/update_", "/update-", "/edit_", "/edit-", "/ubah_", "/ubah-"}; + + private static final String[] DELETE_PATTERN = {"/delete_", "/delete-", "/hapus_", "/hapus-"}; + + private final Logger LOG = LoggerFactory.getLogger(AppInterceptor.class); + + @Autowired + private TokenAuthenticationService tokenAuthenticationService; + + @Autowired + private LoginUserDao loginUserDao; + + @Autowired + private MapObjekModulToKelompokUserService mapObjekModulToKelompokUserService; + + @Autowired + private MapObjekModulToLoginUserService mapObjekModulToLoginUserService; + + @Autowired + private ObjekModulAplikasiService objekModulAplikasiService; + + @Autowired + MessagePublisher messagePublisher; + + @Autowired + MessageSubscriber messageSubscriber; + + @Autowired + NotifMessagingService notifMessagingService; + + @Autowired + NotifikasiMessageObjekModulService notifikasiMessageObjekModulService; + + @Autowired + NotifMessagingSchedulerService notifMessagingSchedulerService; + + @Autowired + NotifikasiMessageObjekModulDao notifikasiModulMessageDao; + + @Autowired + RuanganDao ruanganDao; + + List loginUser; + + String namaUser; + +// private int headerActionToAction(String action){ +// if ("save".equals(action)){ +// return AppPermission.ADD; +// } else if ("edit".equals(action)){ +// return AppPermission.UPDATE; +// } else if ("delete".equals(action)){ +// return AppPermission.DELETE; +// } else if ("print".equals(action)){ +// return AppPermission.PRINT; +// } else { +// return AppPermission.VIEW; +// } +// } + + + private boolean contains(String source, String[] matchers){ + + + if (CommonUtil.isNullOrEmpty(source) || ArrayUtils.isEmpty(matchers)){ + return false; + } + + for (int i=0;i 0){ +// cpos = pos; +// }else{ +// break; +// } +// } +// String oye = urlForm.substring(0, cpos); + return potongan.toString(); + } + + private boolean checkAuthSecure(HttpServletRequest request, HttpServletResponse response, String AlamatUrlForm, boolean supervisi) throws Exception { + + Authentication authentication = tokenAuthenticationService.getAuthentication(request); + + namaUser = authentication.getName(); + loginUser = loginUserDao.findByNamaUser(namaUser); + + if (CommonUtil.isNullOrEmpty(loginUser)) { + LOG.info("Empty login user"); + response.setHeader("RequireSupervisor", "false"); + response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Empty login user"); + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + return false; + } + return true; + } + + private int checkUserPermision(LoginUser user, ObjekModulAplikasiVO objekModulAplikasiVO, int action){ + + int result = -1; + + MapObjekModulToLoginUser modul = mapObjekModulToLoginUserService.findByObjekModulAplikasi(objekModulAplikasiVO.getId(), user.getId()); + + if (modul != null) { + LOG.info("Module security match"); + result = 0; + switch (action) { + case AppPermission.ADD: + if (modul.getSimpan()){ + result = 1; + } + break; + case AppPermission.UPDATE: + if (modul.getEdit()){ + result = 1; + } + break; + case AppPermission.DELETE: + if (modul.getHapus()){ + result = 1; + } + break; + case AppPermission.PRINT: + if (modul.getCetak()){ + result = 1; + } + break; + } + } + + return result; + } + + private int checkKelompokUserPermision(LoginUser user, ObjekModulAplikasiVO objekModulAplikasiVO, int action){ + + KelompokUser role = user.getKelompokUser(); + int result = -2; + + if (role != null) { + MapObjekModulToKelompokUser modul = mapObjekModulToKelompokUserService.findByObjekModulAplikasi(objekModulAplikasiVO.getId(), role.getId()); + result = -1; + if (modul != null) { + LOG.info("Module security match"); + result = 0; + switch (action) { + case AppPermission.ADD: + if (modul.getSimpan()){ + result = 1; + } + break; + case AppPermission.UPDATE: + if (modul.getEdit()){ + result = 1; + } + break; + case AppPermission.DELETE: + if (modul.getHapus()){ + result = 1; + } + break; + case AppPermission.PRINT: + if (modul.getCetak()){ + result = 1; + } + break; + } + } + } + + return result; + } + + private boolean checkPermission(HttpServletRequest request, HttpServletResponse response, String AlamatUrlForm, int action) throws Exception { + // Alter modified Syamsu + List objekModulAplikasi = objekModulAplikasiService.findByAlamatUrlForm(filterUrlForm(AlamatUrlForm)); + + + if (CommonUtil.isNullOrEmpty(objekModulAplikasi)){ + LOG.warn(AlamatUrlForm + " : Sementara defaultnya diloloskan semuanya di AppInterceptor jika tidak ada di dalam daftar objek modul aplikasi.."); + return true; // Defaultnya diloloskan semuanya... + } + + if (!checkAuthSecure(request, response, AlamatUrlForm, false)) { + return false; + } + + int resultUser = checkUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action); + + if (resultUser == 0){ + LOG.info("User {} has need superVisor for action in {} module application", namaUser, action); + response.setHeader("RequireSupervisor", "true"); + response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + return false; + } else if (resultUser == 1){ + response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success"); + response.setStatus(HttpServletResponse.SC_OK); + return true; + } + + int resultKelompokUser = checkKelompokUserPermision(loginUser.get(0), objekModulAplikasi.get(0), action); + + if (resultKelompokUser == -2){ + LOG.warn("Sementara defaultnya diloloskan semuanya di AppInterceptor jika tidak ada di dalam daftar kelompok user.."); + return true; // Defaultnya diloloskan semuanya... +// LOG.info("User {} has no role to gain access restricted area", namaUser); +// response.setHeader("RequireSupervisor", "false"); +// response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, +// "User " + namaUser + " has no role to gain access restricted area"); +// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); +// return false; + } else if (resultKelompokUser == -1){ + LOG.warn("Sementara defaultnya diloloskan semuanya di AppInterceptor jika tidak ada di dalam daftar Map objek modul to kelompok user.."); + return true; // Defaultnya diloloskan semuanya... +// LOG.info("User {} has no access to module application", namaUser); +// response.setHeader("RequireSupervisor", "false"); +// response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, +// "User " + namaUser + " has no access to module application"); +// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); +// return false; + } else if (resultKelompokUser == 0) { + LOG.info("User {} has need superVisor for action in {} module application", namaUser, action); + response.setHeader("RequireSupervisor", "true"); + response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Action requires supervisor"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + return false; + } else { + response.setHeader(Constants.MessageInfo.INFO_MESSAGE, "Supervise execution success"); + response.setStatus(HttpServletResponse.SC_OK); + return true; + } + } + + /* + * return true untuk valid permission request ke controller method + */ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + ////// Syamsu ///// + + // TUTUP DULU PENGGUNAANNYA... + + HandlerMethod hm; + Method method = null; +// int methodApp = AppPermission.VIEW; + + response.setHeader("Access-Control-Expose-Headers", "RequireSupervisor" + "," + + Constants.MessageInfo.ERROR_MESSAGE + "," + Constants.MessageInfo.INFO_MESSAGE); + + ////// Syamsu ///// + + String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? "": request.getHeader(Constants.HttpHeader.URL_FORM); + + // Buat Om, Kang, Aa Reza terkait Security Role + //String KdRuangan = null; + String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? "": request.getHeader(Constants.HttpHeader.KD_RUANGAN); + + int action = AppPermission.VIEW; + + if (CommonUtil.isNullOrEmpty(AlamatUrlForm)){ + //LOG.warn("Sementara defaultnya di loloskan semuanya di AppInterceptor jika tidak ada header 'AlamatUrlForm' .."); + return true; // Lewatin dulu sementara; + } + + if (CommonUtil.isNullOrEmpty(KdRuangan) || "0".equals(KdRuangan)){ + LOG.warn("Sementara defaultnya diloloskan semuanya di AppInterceptor jika tidak ada header 'KdRuangan' atau header 'KdRuangan'nya 0 .."); + return true; // Lewatin dulu sementara; + } + + //String headerAction = request.getHeader(Constants.HttpHeader.ACTION) == null ? "" : request.getHeader(Constants.HttpHeader.ACTION); + + String URI = request.getRequestURI(); + String methodHttp = request.getMethod(); + + try { + // Alter modified Syamsu + if (handler instanceof org.springframework.web.method.HandlerMethod) { + hm = (HandlerMethod) handler; + method = hm.getMethod(); + } else { + return checkAuthSecure(request, response, AlamatUrlForm, true); + } + + // AlamatUrlForm // Alter modified Syamsu + boolean usingAnno = method != null && method.isAnnotationPresent(AppPermission.class); + + boolean postM = "POST".equals(methodHttp); + boolean signInOut = !URI.contains("auth/sign-in") && !URI.contains("auth/sign-out"); + boolean getM = "GET".equals(methodHttp); + boolean cetak = contains (URI, PRINT_PATTERN); + + /*(URI.contains("/lap_") || URI.contains("/lap-") || URI.contains("/lap") + || URI.contains("/cetak_") || URI.contains("/print_") || URI.contains("/cetak-") + || URI.contains("/print-"));*/ + + boolean simpan = contains (URI, ADD_PATTERN); + + /*(URI.contains("/save_") || URI.contains("/add_") || URI.contains("/simpan_") + || URI.contains("/save-") || URI.contains("/add-") || URI.contains("/simpan-"));*/ + + boolean ubah = contains (URI, UPDATE_PATTERN); + + /*(URI.contains("/update_") || URI.contains("/edit_") || URI.contains("/ubah_") + || URI.contains("/update-") || URI.contains("/edit-") || URI.contains("/ubah-"));*/ + + boolean hapus = contains (URI, DELETE_PATTERN); + + /*(URI.contains("/delete_") || URI.contains("/hapus_") || URI.contains("/delete-") + || URI.contains("/hapus-")); */ + + if (usingAnno) { + if (method.getAnnotation(AppPermission.class) != null) { + action = method.getAnnotation(AppPermission.class).value(); + } + + if (AppPermission.SPECIALS == action /* && "#/home".equals(AlamatUrlForm) */) { + return true; + } + } + + if (getM && cetak) { + + action = AppPermission.PRINT; + +// if (headerAction != null && !"".equals(headerAction)) { +// action = headerActionToAction(headerAction); +// } + + if (method.getAnnotation(AppPermission.class) != null) { + action = method.getAnnotation(AppPermission.class).value(); + } + + return checkPermission(request, response, AlamatUrlForm, action); + } + + if ((usingAnno || postM) && signInOut) { + + if (simpan) { + action = AppPermission.ADD; + } else if (ubah) { + action = AppPermission.UPDATE; + } else if (hapus) { + action = AppPermission.DELETE; + } else if (cetak) { + action = AppPermission.PRINT; + } + +// if (headerAction != null && !"".equals(headerAction)) { +// action = headerActionToAction(headerAction); +// } + + if (method.getAnnotation(AppPermission.class) != null) { + action = method.getAnnotation(AppPermission.class).value(); + } + + return checkPermission(request, response, AlamatUrlForm, action); + + } + + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Not Found " + request.getRequestURL()); + + LOG.info("Error accured unauthorized"); + response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Something wrong happened"); + response.setHeader("RequireSupervisor", "false"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return false; + } + + // TUTUP DULU PENGGUNAANNYA... + + return true; + } + + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav) throws Exception {} + + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) throws Exception { + + String AlamatUrlForm = request.getHeader(Constants.HttpHeader.URL_FORM) == null ? "" + : request.getHeader(Constants.HttpHeader.URL_FORM); + String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) == null ? "" + : request.getHeader(Constants.HttpHeader.KD_RUANGAN); + + String idRuanganTujuan = request.getHeader(Constants.HttpHeader.KD_RUANGAN_T) == null ? "" + : request.getHeader(Constants.HttpHeader.KD_RUANGAN_T); + + String idRuanganTujuanA = request.getHeader(Constants.HttpHeader.KD_RUANGAN_A) == null ? "" + : request.getHeader(Constants.HttpHeader.KD_RUANGAN_A); + + String tglKirim = request.getHeader(Constants.HttpHeader.TGL_KIRIM) == null ? "" + : request.getHeader(Constants.HttpHeader.TGL_KIRIM); + + boolean notHttpOK = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; + boolean notLewatMenu = CommonUtil.isNullOrEmpty(AlamatUrlForm) || CommonUtil.isNullOrEmpty(KdRuangan); + + Integer ruanganAsalId = 0; + + try { + ruanganAsalId = Integer.parseInt(KdRuangan); + }catch(Exception e){ + ex = e; + } + + + boolean adaError = CommonUtil.isNotNullOrEmpty(ex); + if (notHttpOK || notLewatMenu || adaError){ + return; + } + + Authentication authentication = tokenAuthenticationService.getAuthentication(request); + + if (CommonUtil.isNullOrEmpty(authentication)){ + return; + } + + namaUser = authentication.getName(); + loginUser = loginUserDao.findByNamaUser(namaUser); + + if (CommonUtil.isNullOrEmpty(loginUser)) { + return; + } + + String potongan = filterUrlForm(AlamatUrlForm); + List objekModulAplikasiVOs = objekModulAplikasiService.findByAlamatUrlForm(potongan); + + if (CommonUtil.isNullOrEmpty(objekModulAplikasiVOs)){ + return; + } + + String URI = request.getRequestURI(); + + Integer objekModulAplikasId = objekModulAplikasiVOs.get(0).getId(); + + List notifMessagingVOs = notifMessagingService.findByObjekModulAplikasiIdAndUrlBackEndOrUrlBackEndIsNull(objekModulAplikasId, URI); + + if (CommonUtil.isNullOrEmpty(notifMessagingVOs)) { + return; + } + + Integer notifMessagingId = notifMessagingVOs.get(0).getId(); + + if (CommonUtil.isNullOrEmpty(tglKirim)) { + + + List ruanganTujuansId = new ArrayList<>(); + System.out.println("--"); + + if (!"".equals(idRuanganTujuan)){ + JSONArray ruanganTujuanIds = new JSONArray(idRuanganTujuan); + for (int i=0; i 0){ + try{ + rabbitHole.sendNotif(rabbitHole, ruanganAsal, pegawai, notifikasiMessageObjekModulService, notifMessagingId, ruanganTujuansId); + }catch(Exception e){ + e.printStackTrace(); + LOG.info(DateUtil.now()+" send notif dari Ruangan {} dengan ruanganId {} pada notifMessageId {} ada masalah {}", + ruanganAsal.getNamaRuangan(), ruanganAsalId, notifMessagingId, e.getMessage()); + } + } + + } else { + JSONArray tglKirims = new JSONArray(tglKirim); + JSONArray ruanganTujuanIds = new JSONArray(idRuanganTujuan); + SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd"); + + for (int i=0; i T convertToVO(T t, Object o){ +// BeanUtils.copyProperties(t, o); +// return t; +// } + + // try{ + // + // + // String AlamatUrlForm = + // request.getHeader(Constants.HttpHeader.URL_FORM) == null ? "" : + // request.getHeader(Constants.HttpHeader.URL_FORM); + // String KdRuangan = request.getHeader(Constants.HttpHeader.KD_RUANGAN) + // == null ? "" : request.getHeader(Constants.HttpHeader.KD_RUANGAN); + // + // Authentication authentication = + // tokenAuthenticationService.getAuthentication(request); + // + // namaUser = authentication.getName(); + // loginUser = loginUserDao.findByNamaUser(namaUser); + // + // + // if (loginUser.isEmpty()) { + // publisher.BroadcastMessage(KdRuangan, namaUser, AlamatUrlForm); + // } + // + // + // + // + //// String routingKeyAndQueueName = "ruanganId." + KdRuangan; + //// + //// publisher.sendRabbitMQNotification("127.0.0.1", "ruanganId." + + // KdRuangan, "Kd Ruangan : " + KdRuangan + ", AlamatUrlForm : " + + // AlamatUrlForm); + //// + //// subscriber.startRabbitMQNotification("127.0.0.1", + // routingKeyAndQueueName); + //// subscriber.listenRabbitMQNotification(routingKeyAndQueueName, + // subscriber.getDefaultConsumer(), false); + //// subscriber.stopRabbitMQNotification(); + // + // }catch(Exception e){ + // //e.printStackTrace(); + // } + + + +// //String urlSocket = messagePublisher.GetSettingDataFixed("UrlRabbitMQMessaging"); sementara kunci dulu. +// +// String urlSocket = "127.0.0.1"; +// +// List notifikasiMessageObjekModulVOs = notifikasiMessageObjekModulService.findByNotifMessagingIdAndRuanganId(notifMessagingId, ruanganTujuansId); +// +// if (CommonUtil.isNullOrEmpty(notifikasiMessageObjekModulVOs)) { +// return; +// } +// +// Integer ruanganIdtemp = 0; +// boolean connect = false; +// +// for (NotifikasiMessageObjekModulVO vo : notifikasiMessageObjekModulVOs){ +// Ruangan ruangan = vo.getRuangan(); +// ModulAplikasi modulAplikasi = vo.getModulAplikasi(); +// ObjekModulAplikasi objekModulAplikasi = vo.getObjekModulAplikasi(); +// String customURLObjekModul = vo.getCustomURLObjekModul(); +// String titleNotifikasi = vo.getTitleNotifikasi(); +// String pesanNotifikasi = vo.getPesanNotifikasi(); +// String namaFungsiFrontEnd = vo.getNamaFungsiFrontEnd(); +// +// if (ruangan.getId() == ruanganId){ +// continue; +// } +// +// RuanganVO dariRuangan = ruanganService.findById(ruanganId); +// +// if (ruanganIdtemp != ruangan.getId()){ +// if (connect){ +// rabbitHole.close(); +// } +// rabbitHole.connect(urlSocket, String.valueOf(ruangan.getId())); +// connect = true; +// ruanganIdtemp = ruangan.getId(); +// } +// +// Map map = new HashMap<>(); +// map.put("title", titleNotifikasi); +// map.put("dariRuangan", dariRuangan); +// map.put("ruanganId", ruangan.getId()); +// map.put("ruangan", convertToVO(new RuanganVO(), ruangan)); +// map.put("modulAplikasi", convertToVO(new ModulAplikasiVO(), modulAplikasi)); +// map.put("objekModulAplikasi", convertToVO(new ObjekModulAplikasiVO(), objekModulAplikasi)); +// map.put("titleNotifikasi", titleNotifikasi); +// map.put("pesanNotifikasi", pesanNotifikasi); +// map.put("namaFungsiFrontEnd", namaFungsiFrontEnd); +// map.put("fromPegawai", loginUser.get(0).getPegawai()); +// map.put("urlForm",CommonUtil.isNullOrEmpty(customURLObjekModul)? objekModulAplikasi.getAlamatUrlForm() : customURLObjekModul); +// +// rabbitHole.sendRabbitMQNotification(gson.toJson(map)); +// +// //messagePublisher.BroadcastMessage(map); +// } +// if (connect){ +// rabbitHole.close(); +// } + + +// private static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { +// @Override +// @SuppressWarnings("unchecked") +// public TypeAdapter create(Gson gson, TypeToken type) { +// return (HibernateProxy.class.isAssignableFrom(type.getRawType()) +// ? (TypeAdapter) new HibernateProxyTypeAdapter((TypeAdapter)gson.getAdapter(TypeToken.get(type.getRawType().getSuperclass()))) +// : null); +// } +// }; +// +// +// private static final class HibernateProxyTypeAdapter extends TypeAdapter { +// +// private final TypeAdapter delegate; +// +// private HibernateProxyTypeAdapter(TypeAdapter delegate) { +// this.delegate = delegate; +// } +// +// @Override +// public HibernateProxy read(JsonReader r) throws IOException { +// throw new UnsupportedOperationException("Not supported"); +// } +// +// @SuppressWarnings({"rawtypes", "unchecked"}) +// @Override +// public void write(JsonWriter out, HibernateProxy value) throws IOException { +// if (value == null) { +// out.nullValue(); +// return; +// } +// +// +// +// delegate.write(out, ((HibernateProxy) value).getHibernateLazyInitializer().getImplementation()); +// } +// } +} + + + +/* + * else if (method.isAnnotationPresent(AppMenuPermision.class)){ + * + * Authentication authentication = + * tokenAuthenticationService.getAuthentication(request); + * + * String namaUser = authentication.getName(); + * + * List loginUser = + * loginUserDao.findByNamaUser(namaUser); + * + * if (loginUser.isEmpty()) { // untuk testing false + * response.addHeader("Access-Control-Expose-Headers", + * "content-type"); + * response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "User " + + * namaUser + " can not access current menu "); + * response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return + * false; } + * + * // get user login if (!loginUser.isEmpty()) { LoginUser user = + * loginUser.get(0); }else{ LOG.info("User {} is unauthorized", + * namaUser); + * response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, + * "User is unauthorized"); + * response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return + * false; } } + */ \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/RestAuthenticationEntryPoint.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/RestAuthenticationEntryPoint.java new file mode 100644 index 00000000..6fa5cc34 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,43 @@ +package com.jasamedika.medifirst2000.security; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import com.jasamedika.medifirst2000.constants.Constants; + +/** + * RestAuthenticationEntryPoint class + * set Unauthorized response from "Unauthorized client" + * + * @author Roberto + */ +@Component("RestAuthenticationEntryPoint") +public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + + private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class); + + + /// Alter Syamsu + @Override + public void commence(HttpServletRequest request, + HttpServletResponse response, AuthenticationException ae) + throws IOException, ServletException { + + LOGGER.error("Mencoba akses tanpa login"); + response.getWriter().write("{" + Constants.MessageInfo.ERROR_MESSAGE + ":'Please login to get access'}"); + response.setHeader(Constants.MessageInfo.ERROR_MESSAGE, "Please login to get access"); + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + + //response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + } + +} \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/SpringSecurityConfig.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/SpringSecurityConfig.java new file mode 100644 index 00000000..8553b91e --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/SpringSecurityConfig.java @@ -0,0 +1,145 @@ +package com.jasamedika.medifirst2000.security; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +import com.jasamedika.medifirst2000.constants.Constants; +import com.jasamedika.medifirst2000.filter.StatelessAuthenticationFilter; +import com.jasamedika.medifirst2000.security.service.TokenAuthenticationService; +import com.jasamedika.medifirst2000.security.service.UserService; + +/** + * SpringSecurityConfig class + * Di sini Kita tidak menggunakan XML Config untuk Spring Security + * + * @author Roberto + */ +@Configuration +@EnableWebSecurity +@Order(2) +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private RestAuthenticationEntryPoint restAuthenticationEntryPoint; + + private final UserService userService; + private final TokenAuthenticationService tokenAuthenticationService; + + public SpringSecurityConfig() { + super(true); + this.userService = new UserService(); + tokenAuthenticationService = new TokenAuthenticationService( + Constants.JASAMEDIKA, userService); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.exceptionHandling() + //restAuthenticationEntryPoint + .authenticationEntryPoint(restAuthenticationEntryPoint) + + .and() + .anonymous() + .and() + .servletApi() + .and() + .headers() + .cacheControl() + .and() + .authorizeRequests() + + + // Allow anonymous resource requests + .antMatchers("/favicon.ico") + .permitAll() + .antMatchers("**/*.html") + .permitAll() + .antMatchers("**/*.css") + .permitAll() + .antMatchers("**/*.js") + .permitAll() + + // Allow anonymous logins + .antMatchers("/auth/**") + .permitAll() + + // Allow SMS gateway + .antMatchers("/registrasi-pasien-sms/**") + .permitAll() + + // Allow SMS gateway + .antMatchers("/report/**") + .permitAll() + + // URL tanpa auth deklarasikan di sini + .antMatchers("/test-tanpa-auth/**") + .permitAll() + .antMatchers("/test/**") + .permitAll() + + .antMatchers("/api-docs.json") + .permitAll() + + .antMatchers("/api-docs/**") + .permitAll() + + /*//Allow Download File Surat Masuk + .antMatchers("/surat-masuk/download-dokumen-template/**") + .permitAll() + .antMatchers("/surat-masuk/get-draft-surat/**") + .permitAll()*/ + + // All other request need to be authenticated + .anyRequest() + .authenticated() + .and() + + // Custom Token based authentication based on the header + // previously given to the client + .addFilterBefore( + new StatelessAuthenticationFilter( + tokenAuthenticationService), + UsernamePasswordAuthenticationFilter.class); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) + throws Exception { + auth.userDetailsService(userDetailsService()).passwordEncoder( + new BCryptPasswordEncoder()); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean + @Override + public UserService userDetailsService() { + return userService; + } + + @Bean + public TokenAuthenticationService tokenAuthenticationService() { + return tokenAuthenticationService; + } + + +// @Bean(name = "springSecurityFilterChain", autowire = Autowire.BY_NAME) +// public DelegatingFilterProxy springSecurityFilterChain(){ +// return new DelegatingFilterProxy(); +// } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/handler/TokenHandler.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/handler/TokenHandler.java new file mode 100644 index 00000000..1252d6f3 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/handler/TokenHandler.java @@ -0,0 +1,40 @@ +package com.jasamedika.medifirst2000.security.handler; + +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; + +import org.springframework.security.core.userdetails.User; + +import com.jasamedika.medifirst2000.security.service.UserService; + +/** + * TokenHandler class + * using jjwt https://github.com/jwtk/jjwt + * + * @author Roberto + */ +public class TokenHandler { + private final String secret; + private final UserService userService; + + public TokenHandler(String secret, UserService userService) { + this.secret = secret; + this.userService = userService; + } + + public User parseUserFromToken(String token) { + String username = Jwts.parser() + .setSigningKey(secret) + .parseClaimsJws(token) + .getBody() + .getSubject(); + return userService.loadUserByUsername(username); + } + + public String createTokenForUser(User user) { + return Jwts.builder().setHeaderParam("typ", "JWT") + .setSubject(user.getUsername()) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/model/AppPermission.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/model/AppPermission.java new file mode 100644 index 00000000..4025f543 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/model/AppPermission.java @@ -0,0 +1,25 @@ +package com.jasamedika.medifirst2000.security.model; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * AppPermission annotation, digunakan untuk method yang butuh authorized dari database + * can use in method only. + * @author Roberto + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface AppPermission { + public static final int ADD = 100; + public static final int UPDATE = 200; + public static final int DELETE = 300; + public static final int PRINT = 400; + public static final int VIEW = 500; + + public static final int SPECIALS = 600; + + int value(); +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/model/UserAuthentication.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/model/UserAuthentication.java new file mode 100644 index 00000000..6e3add0f --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/model/UserAuthentication.java @@ -0,0 +1,60 @@ +package com.jasamedika.medifirst2000.security.model; + +import java.util.Collection; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; + +/** + * UserAuthentication class + * + * @author Roberto + */ +public class UserAuthentication implements Authentication { + /** + * serialVersionUID + */ + private static final long serialVersionUID = -7410905698525654537L; + private final User user; + private boolean authenticated = true; + + public UserAuthentication(User user) { + this.user = user; + } + + @Override + public String getName() { + return user.getUsername(); + } + + @Override + public Collection getAuthorities() { + return user.getAuthorities(); + } + + @Override + public Object getCredentials() { + return user.getPassword(); + } + + @Override + public User getDetails() { + return user; + } + + @Override + public Object getPrincipal() { + return user.getUsername(); + } + + @Override + public boolean isAuthenticated() { + return authenticated; + } + + @Override + public void setAuthenticated(boolean authenticated) { + this.authenticated = authenticated; + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/service/TokenAuthenticationService.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/service/TokenAuthenticationService.java new file mode 100644 index 00000000..0ed2b075 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/service/TokenAuthenticationService.java @@ -0,0 +1,72 @@ +package com.jasamedika.medifirst2000.security.service; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.User; +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.core.JsonParseException; +import com.jasamedika.medifirst2000.core.web.WebConstants; +import com.jasamedika.medifirst2000.security.handler.TokenHandler; +import com.jasamedika.medifirst2000.security.model.UserAuthentication; + +/** + * TokenAuthenticationService class + * + * @author Roberto + */ +@Component +public class TokenAuthenticationService { + + public static TokenHandler tokenHandler; + + public TokenAuthenticationService() { + } + + public TokenAuthenticationService(String secret, UserService userService) { + tokenHandler = new TokenHandler(secret, userService); + } + + public String addAuthentication(HttpServletResponse response, + UserAuthentication authentication) { + final User user = authentication.getDetails(); + return tokenHandler.createTokenForUser(user); + } + + public Authentication getAuthentication(HttpServletRequest request) + throws JsonParseException { + + String token = request.getHeader(WebConstants.AUTH_HEADER_NAME); + if (token != null) { + final User user = tokenHandler.parseUserFromToken(token); + if (user != null) { + return new UserAuthentication(user); + } + } + else{ + try + { + if(request.getQueryString()=="")return null; + final String[] tokens= request.getQueryString().split("&"); + for (String tokenTemp : tokens) { + if(tokenTemp.toLowerCase().indexOf(WebConstants.AUTH_HEADER_NAME.toLowerCase())>=0) + { + token =tokenTemp.split("=")[1]; + final User user = tokenHandler.parseUserFromToken(token); + if (user != null) { + return new UserAuthentication(user); + } + } + } + } + catch(Exception e) + { + + } + + } + return null; + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/service/UserService.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/service/UserService.java new file mode 100644 index 00000000..b883d19e --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/security/service/UserService.java @@ -0,0 +1,61 @@ +package com.jasamedika.medifirst2000.security.service; + +import java.util.Arrays; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AccountStatusUserDetailsChecker; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Component; + +import com.jasamedika.medifirst2000.dao.LoginUserDao; +import com.jasamedika.medifirst2000.entities.LoginUser; + +/** + * UserService implements + org.springframework.security.core.userdetails.UserDetailsService + * + * @author Roberto + */ +@Component +public class UserService implements + org.springframework.security.core.userdetails.UserDetailsService { + + @Autowired + private LoginUserDao loginUserDao; + + private final AccountStatusUserDetailsChecker detailsChecker = new AccountStatusUserDetailsChecker(); + + public UserService() { + super(); + } + + /** + * this method is called for rest authentication from client + * + * @author Roberto + */ + @Override + public final User loadUserByUsername(String username) + throws UsernameNotFoundException { + List loginUsers = loginUserDao.findByNamaUser(username); + if (loginUsers.isEmpty()) { + throw new UsernameNotFoundException("user not found"); + } + LoginUser loginUser = loginUsers.get(0); + //validasi tambahan lakukan di sini + +// GrantedAuthority authority = new SimpleGrantedAuthority(loginUser +// .getKelompokUser().getKelompokUser()); + GrantedAuthority authority = new SimpleGrantedAuthority("USER"); + UserDetails userDetails = (UserDetails) new User( + loginUser.getNamaUser(), loginUser.getKataSandi(), + Arrays.asList(authority)); + detailsChecker.check(userDetails); + return (User) userDetails; + } +} \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/task/schedule/ScheduleTask.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/task/schedule/ScheduleTask.java new file mode 100644 index 00000000..3c807944 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/task/schedule/ScheduleTask.java @@ -0,0 +1,56 @@ +package com.jasamedika.medifirst2000.task.schedule; + +import com.jasamedika.medifirst2000.service.KalenderService; +import com.jasamedika.medifirst2000.service.PegawaiJadwalKerjaService; +import com.jasamedika.medifirst2000.service.SlipGajiService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +/** + * @author Salman + * @since 12 Jul 2023 + */ +@Component +public class ScheduleTask { + + private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTask.class); + + @Autowired + private KalenderService kalenderService; + + @Autowired + private PegawaiJadwalKerjaService pegawaiJadwalKerjaService; + + @Autowired + private SlipGajiService slipGajiService; + + @Scheduled(cron = "0 0 23 30 6 ?") + public void generateKalender() { + LOGGER.info("Generate kalender tahun {}", + LocalDate.now().plusYears(1).format(DateTimeFormatter.ofPattern("yyyy"))); + + kalenderService.generateAndSaveKalender(); + } + + @Scheduled(cron = "0 0 0 1 * ?") + public void genarateJadwalPegawaiNonShift() { + LOGGER.info("Generate jadwal pegawai bulan {}", LocalDate.now().format(DateTimeFormatter.ofPattern("MM-yyyy"))); + + pegawaiJadwalKerjaService.autoSaveJadwalKerjaNonShift(); + } + + @Scheduled(cron = "0 0 0 1 * ?") + public void initiateSlipGaji() { + LOGGER.info("Initiate template slip gaji bulan {}", + LocalDate.now().format(DateTimeFormatter.ofPattern("MM-yyyy"))); + + slipGajiService.init(); + } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/task/schedule/config/ScheduleTaskConfig.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/task/schedule/config/ScheduleTaskConfig.java new file mode 100644 index 00000000..c96cd166 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/task/schedule/config/ScheduleTaskConfig.java @@ -0,0 +1,27 @@ +package com.jasamedika.medifirst2000.task.schedule.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; + +/** + * @author Salman + * @since 12 Jul 2023 + */ +@Configuration +@EnableScheduling +@ComponentScan("com.jasamedika.medifirst2000.task") +public class ScheduleTaskConfig { + + @Bean + public TaskScheduler taskScheduler() { + ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); + threadPoolTaskScheduler.setPoolSize(5); + threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler"); + return threadPoolTaskScheduler; + } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/util/rest/JacksonConfiguration.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/util/rest/JacksonConfiguration.java new file mode 100644 index 00000000..5a5cf6bd --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/util/rest/JacksonConfiguration.java @@ -0,0 +1,29 @@ +package com.jasamedika.medifirst2000.util.rest; + +import org.springframework.stereotype.Component; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +@Component +public class JacksonConfiguration { + private ObjectMapper mapper; + + public JacksonConfiguration() { + } + + public JacksonConfiguration(ObjectMapper mapper) { + this.mapper = mapper; + configureJackson(mapper); + } + + public static ObjectMapper configureJackson(ObjectMapper mapper) { + mapper.enable(SerializationFeature.INDENT_OUTPUT); + mapper.setSerializationInclusion(Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, + false); + return mapper; + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/util/rest/RestUtil.java b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/util/rest/RestUtil.java new file mode 100644 index 00000000..43cb5a0a --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/jasamedika/medifirst2000/util/rest/RestUtil.java @@ -0,0 +1,245 @@ +package com.jasamedika.medifirst2000.util.rest; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +import com.google.gson.Gson; + +/** + * Rest Util Class + * + * @author Roberto + */ +public class RestUtil { + + private static final String CONTENT_TYPE = "Content-Type"; + + /** + * get JSON response from Object + * + * @param src + * @param + * source class + * @return @ResponseEntity + */ + public static ResponseEntity getJsonResponse(T src) { + + HttpHeaders headers = new HttpHeaders(); + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + return new ResponseEntity(src, headers, HttpStatus.OK); + } + + /** + * get JSON response from Object with HTTP status + * + * @param src + * @param status + * @param + * source class + * @return @ResponseEntity + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static ResponseEntity getJsonResponse(T src, HttpStatus status) { + + HttpHeaders headers = new HttpHeaders(); + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + Map map = new HashMap(); + map.put("data", src); + return new ResponseEntity(map, headers, status); + } + + /** + * + * @param src + * @param status + * @param mapHeaderMessage + * @param + * @return + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static ResponseEntity getJsonResponse(T src, HttpStatus status, + Map mapHeaderMessage) { + + HttpHeaders headers = new HttpHeaders(); + + if (null != mapHeaderMessage) { + for (String key : mapHeaderMessage.keySet()) { + headers.add(key, mapHeaderMessage.get(key)); + } + } + + Map map = new HashMap(); + map.put("messages", mapHeaderMessage); + map.put("data", src); + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + return new ResponseEntity(map, headers, status); + } + + /** + * + * @param status + * @param mapHeaderMessage + * @return + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static ResponseEntity getJsonResponse(HttpStatus status, Map mapHeaderMessage) { + HttpHeaders headers = new HttpHeaders(); + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + + Map map = new HashMap(); + map.put("messages", mapHeaderMessage); + + return new ResponseEntity(map, headers, status); + } + + /** + * get JSON response from HTTP status only + * + * @param + * source class + * @return @ResponseEntity + */ + public static ResponseEntity getJsonHttptatus(HttpStatus status) { + + return new ResponseEntity(status); + + } + + public static ResponseEntity getJsonHttptatus(HttpStatus status, Map mapHeaderMessage) { + + HttpHeaders headers = new HttpHeaders(); + + if (null != mapHeaderMessage) { + for (String key : mapHeaderMessage.keySet()) { + headers.add(key, mapHeaderMessage.get(key)); + } + } + + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + return new ResponseEntity(headers, status); + + } + + /** + * get JSON response from Set Object + * + * @param src + * @param + * source class + * @return @ResponseEntity + */ + public static ResponseEntity> defaultJsonResponse(Set src) { + + HttpHeaders headers = new HttpHeaders(); + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + return new ResponseEntity>(src, headers, HttpStatus.OK); + } + + /** + * get JSON response from Set Object with custom header + * + * @param src + * @param mapHeaderMessage + * @param + * source class + * @return @ResponseEntity + */ + public static ResponseEntity> defaultJsonResponse(Set src, Map mapHeaderMessage) { + + HttpHeaders headers = new HttpHeaders(); + + if (null != mapHeaderMessage) { + for (String key : mapHeaderMessage.keySet()) { + headers.add(key, mapHeaderMessage.get(key)); + } + } + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + return new ResponseEntity>(src, headers, HttpStatus.OK); + } + + /** + * get JSON response from List Object with custom header + * + * @param src + * @param mapHeaderMessage + * @param + * source class + * @return @ResponseEntity + */ + public static ResponseEntity> defaultJsonResponse(List src, Map mapHeaderMessage) { + HttpHeaders headers = new HttpHeaders(); + + if (null != mapHeaderMessage) { + for (String key : mapHeaderMessage.keySet()) { + headers.add(key, mapHeaderMessage.get(key)); + } + } + + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + return new ResponseEntity>(src, headers, HttpStatus.OK); + } + + /** + * get JSON response from List Object + * + * @param src + * @param + * source class + * @return @ResponseEntity + */ + public static ResponseEntity> defaultJsonResponse(List src) { + + HttpHeaders headers = new HttpHeaders(); + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + return new ResponseEntity>(src, headers, HttpStatus.OK); + } + + /** + * get default JSON response from Object + * + * @param src + * @return @ResponseEntity + */ + public static ResponseEntity defaultJsonResponse(Object src) { + + Gson gson = new Gson(); + + HttpHeaders headers = new HttpHeaders(); + headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + return new ResponseEntity(gson.toJson(src), headers, HttpStatus.OK); + } + + /** + * convert JSON to Object + * + * @param strJson + * string source JSON + * @param type + * class type result + * @param + * @return + */ + public static T jsonToObject(String strJson, Class type) { + Gson gson = new Gson(); + return gson.fromJson(strJson, type); + } + + /** + * convert object to json + * + * @param object + * @return + */ + public static String toJson(Object object) { + Gson gson = new Gson(); + return gson.toJson(object); + } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonResult.java b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonResult.java new file mode 100644 index 00000000..faa7ed20 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonResult.java @@ -0,0 +1,53 @@ +package com.monitorjbl.json; + +public class JsonResult { + private static final JsonResult instance = new JsonResult(); + private static final ThreadLocal current = new ThreadLocal<>(); + + private JsonResult() { + } + + /** + * Use the provided {@code JsonView} object to serialize the return value. + * + * @param view + * JsonView used to render JSON + * @param + * Type of object being rendered + * @return ResultWrapper to provide return value + */ + @SuppressWarnings("unchecked") + public ResultWrapper use(JsonView view) { + current.set(view); + return new ResultWrapper<>(view); + } + + public static JsonResult instance() { + return instance; + } + + static JsonView get() { + return current.get(); + } + + static void unset() { + current.remove(); + } + + public static class ResultWrapper { + private JsonView obj; + + private ResultWrapper(JsonView obj) { + this.obj = obj; + } + + /** + * Returns the object being serialized + * + * @return the object + */ + public T returnValue() { + return obj.getValue(); + } + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonResultRetriever.java b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonResultRetriever.java new file mode 100644 index 00000000..48bf0992 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonResultRetriever.java @@ -0,0 +1,18 @@ +package com.monitorjbl.json; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JsonResultRetriever { + private static final Logger log = LoggerFactory.getLogger(JsonResultRetriever.class); + + static boolean hasValue() { + return JsonResult.get() != null; + } + + static JsonView retrieve() { + JsonView val = JsonResult.get(); + JsonResult.unset(); + return val; + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewHttpEntityMethodProcessor.java b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewHttpEntityMethodProcessor.java new file mode 100644 index 00000000..4fe78048 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewHttpEntityMethodProcessor.java @@ -0,0 +1,33 @@ +package com.monitorjbl.json; + +import org.springframework.core.MethodParameter; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.ModelAndViewContainer; +import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor; + +import java.util.List; + +public class JsonViewHttpEntityMethodProcessor extends HttpEntityMethodProcessor { + + public JsonViewHttpEntityMethodProcessor(List> converters) { + super(converters); + } + + @Override + public void handleReturnValue(Object returnValue, MethodParameter returnType, + + ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { + if(returnValue instanceof ResponseEntity && JsonResultRetriever.hasValue()) { + JsonView json = JsonResultRetriever.retrieve(); + ResponseEntity re = (ResponseEntity) returnValue; + returnValue = ResponseEntity.status(re.getStatusCode()) + .headers(re.getHeaders()) + .body(json); + } + + super.handleReturnValue(returnValue, returnType, mavContainer, webRequest); + } + +} diff --git a/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewMessageConverter.java b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewMessageConverter.java new file mode 100644 index 00000000..b7dc45bd --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewMessageConverter.java @@ -0,0 +1,35 @@ +package com.monitorjbl.json; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.converter.HttpMessageNotWritableException; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; + +import java.io.IOException; + +public class JsonViewMessageConverter extends MappingJackson2HttpMessageConverter { + + public JsonViewMessageConverter() { + super(); + ObjectMapper defaultMapper = new ObjectMapper(); + SimpleModule module = new SimpleModule(); + module.addSerializer(JsonView.class, new JsonViewSerializer()); + defaultMapper.registerModule(module); + setObjectMapper(defaultMapper); + } + + public JsonViewMessageConverter(ObjectMapper mapper) { + super(); + SimpleModule module = new SimpleModule(); + module.addSerializer(JsonView.class, new JsonViewSerializer()); + mapper.registerModule(module); + setObjectMapper(mapper); + } + + @Override + protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { + super.writeInternal(object, outputMessage); + } + +} \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewResponseProcessor.java b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewResponseProcessor.java new file mode 100644 index 00000000..2d7d97e8 --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewResponseProcessor.java @@ -0,0 +1,12 @@ +package com.monitorjbl.json; + +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor; + +import java.util.List; + +public class JsonViewResponseProcessor extends RequestResponseBodyMethodProcessor { + public JsonViewResponseProcessor(List> messageConverters) { + super(messageConverters); + } +} diff --git a/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewReturnValueHandler.java b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewReturnValueHandler.java new file mode 100644 index 00000000..aeb728ce --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewReturnValueHandler.java @@ -0,0 +1,40 @@ +package com.monitorjbl.json; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.MethodParameter; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodReturnValueHandler; +import org.springframework.web.method.support.ModelAndViewContainer; + +import java.util.List; + +public class JsonViewReturnValueHandler implements HandlerMethodReturnValueHandler { + private static final Logger log = LoggerFactory.getLogger(JsonViewReturnValueHandler.class); + + private final HandlerMethodReturnValueHandler delegate; + + public JsonViewReturnValueHandler(List> converters) { + this.delegate = new JsonViewResponseProcessor(converters); + } + + @Override + public boolean supportsReturnType(MethodParameter returnType) { + return delegate.supportsReturnType(returnType); + } + + @Override + public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { + Object val = returnValue; + if(JsonResultRetriever.hasValue()) { + val = JsonResultRetriever.retrieve(); + log.debug("Found [" + ((JsonView) val).getValue().getClass() + "] to serialize"); + } else { + log.debug("No JsonView found for thread, using returned value"); + } + + delegate.handleReturnValue(val, returnType, mavContainer, webRequest); + } + +} \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java new file mode 100644 index 00000000..6eb9b92e --- /dev/null +++ b/jasamedika-pelayanan/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java @@ -0,0 +1,52 @@ +package com.monitorjbl.json; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.method.support.HandlerMethodReturnValueHandler; +import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; +import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class JsonViewSupportFactoryBean implements InitializingBean { + + @Autowired + private RequestMappingHandlerAdapter adapter; + private final JsonViewMessageConverter converter; + + public JsonViewSupportFactoryBean() { + this(new ObjectMapper()); + } + + public JsonViewSupportFactoryBean(ObjectMapper mapper) { + this.converter = new JsonViewMessageConverter(mapper.copy()); + } + + @Override + public void afterPropertiesSet() throws Exception { + List handlers = new ArrayList<>(adapter.getReturnValueHandlers()); + adapter.setMessageConverters(Collections.>singletonList(converter)); + decorateHandlers(handlers); + adapter.setReturnValueHandlers(handlers); + } + + private void decorateHandlers(List handlers) { + List> converters = new ArrayList<>(adapter.getMessageConverters()); + converters.add(converter); + for(HandlerMethodReturnValueHandler handler : handlers) { + int index = handlers.indexOf(handler); + if(handler instanceof HttpEntityMethodProcessor) { + handlers.set(index, new JsonViewHttpEntityMethodProcessor(converters)); + } else if(handler instanceof RequestResponseBodyMethodProcessor) { + handlers.set(index, new JsonViewReturnValueHandler(converters)); + break; + } + } + } + +} \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/resources/swagger.properties b/jasamedika-pelayanan/src/main/resources/swagger.properties new file mode 100644 index 00000000..acd7cae6 --- /dev/null +++ b/jasamedika-pelayanan/src/main/resources/swagger.properties @@ -0,0 +1,3 @@ +documentation.services.version=1.0 + +documentation.services.basePath=http://localhost:9999/jasamedika-web/ \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/webapp/WEB-INF/spring-security.xml b/jasamedika-pelayanan/src/main/webapp/WEB-INF/spring-security.xml new file mode 100644 index 00000000..98f7c8f1 --- /dev/null +++ b/jasamedika-pelayanan/src/main/webapp/WEB-INF/spring-security.xml @@ -0,0 +1,10 @@ + + + + + \ No newline at end of file diff --git a/jasamedika-pelayanan/src/main/webapp/WEB-INF/springmvc-context.xml b/jasamedika-pelayanan/src/main/webapp/WEB-INF/springmvc-context.xml new file mode 100644 index 00000000..59aecb3b --- /dev/null +++ b/jasamedika-pelayanan/src/main/webapp/WEB-INF/springmvc-context.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jasamedika-sdm/src/main/java/com/jasamedika/medifirst2000/controller/MapRuanganToAkomodasiController.java b/jasamedika-sdm/src/main/java/com/jasamedika/medifirst2000/controller/MapRuanganToAkomodasiController.java deleted file mode 100644 index 2ea24847..00000000 --- a/jasamedika-sdm/src/main/java/com/jasamedika/medifirst2000/controller/MapRuanganToAkomodasiController.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jasamedika.medifirst2000.controller; - -public class MapRuanganToAkomodasiController { - -}