Update service generic

Penerapan clean code untuk ModelService, BaseModel, GenericServiceController, dan LocaleController
This commit is contained in:
Salman Manoe 2022-01-17 11:39:38 +07:00
parent 86c4cb9295
commit d766e1ba0c
5 changed files with 209 additions and 247 deletions

View File

@ -3,11 +3,7 @@ package com.jasamedika.medifirst2000.service;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.jasamedika.medifirst2000.entities.Pasien;
import com.jasamedika.medifirst2000.vo.ModelVO; import com.jasamedika.medifirst2000.vo.ModelVO;
import com.jasamedika.medifirst2000.vo.ModelVO;
import com.jasamedika.medifirst2000.vo.PasienVO;
/** /**
* Pasien Service * Pasien Service

View File

@ -9,7 +9,6 @@ import java.util.Map;
import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -34,18 +33,22 @@ import com.jasamedika.medifirst2000.vo.ModelVO;
*/ */
@Service @Service
public class ModelServiceImpl<T> implements ModelService<T> { public class ModelServiceImpl<T> implements ModelService<T> {
@Autowired @Autowired
private GenericServDao<T> genericServDao; private GenericServDao<T> genericServDao;
@Autowired /**
private MessageSource messageSource; * get /convert string name from org.hibernate.validator.constraints.Length
* to length
// get /convert string name from org.hibernate.validator.constraints.Length *
// to length * @param value
* @return
*/
public String getName(String value) { public String getName(String value) {
return value.substring(value.lastIndexOf('.') + 1).trim(); return value.substring(value.lastIndexOf('.') + 1).trim();
} }
@SuppressWarnings("rawtypes")
public Object converToObject(String value) { public Object converToObject(String value) {
String name = "com.jasamedika.medifirst2000.vo." + value; String name = "com.jasamedika.medifirst2000.vo." + value;
Class cl = null; Class cl = null;
@ -64,13 +67,10 @@ public class ModelServiceImpl<T> implements ModelService<T> {
return o; return o;
} }
@SuppressWarnings("rawtypes")
public static List<Field> GetFields(Class data) { public static List<Field> GetFields(Class data) {
List<Field> items = new ArrayList<Field>(); List<Field> items = new ArrayList<Field>();
String name = data.getName();
Class parent = data.getSuperclass(); Class parent = data.getSuperclass();
if (parent instanceof Class) {
name = ((Class) parent).getName();
}
Class tmpClass = null; Class tmpClass = null;
if (BaseModelVO.class.isAssignableFrom(data.getClass())) { if (BaseModelVO.class.isAssignableFrom(data.getClass())) {
@ -98,7 +98,7 @@ public class ModelServiceImpl<T> implements ModelService<T> {
return items; return items;
} }
@SuppressWarnings("unchecked") @SuppressWarnings({ "serial" })
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
@Override @Override
public ModelVO getModelSerializeEntity(String name, String language) { public ModelVO getModelSerializeEntity(String name, String language) {
@ -110,7 +110,8 @@ public class ModelServiceImpl<T> implements ModelService<T> {
for (Object field : GetFields(o.getClass()).toArray()) { for (Object field : GetFields(o.getClass()).toArray()) {
if (field instanceof Field) { if (field instanceof Field) {
String[] fieldsToInclude = { "String", "Integer", "int","byte","short","Boolean","Byte","Date","Double","double","long","Long","Float","float"}; String[] fieldsToInclude = { "String", "Integer", "int", "byte", "short", "Boolean", "Byte", "Date",
"Double", "double", "long", "Long", "Float", "float" };
boolean found = false; boolean found = false;
for (String element : fieldsToInclude) { for (String element : fieldsToInclude) {
if (getName(((Field) field).getType().toString()).equals(element)) { if (getName(((Field) field).getType().toString()).equals(element)) {
@ -137,7 +138,9 @@ public class ModelServiceImpl<T> implements ModelService<T> {
for (Annotation a : as) { for (Annotation a : as) {
if (a instanceof javax.persistence.ManyToOne) { if (a instanceof javax.persistence.ManyToOne) {
Map<String, Object> modelChild = new HashMap<String, Object>(); Map<String, Object> modelChild = new HashMap<String, Object>();
for (Object fieldChild : GetFields(converToObject(getName(((Field) field).getType().toString())).getClass()).toArray()) { for (Object fieldChild : GetFields(
converToObject(getName(((Field) field).getType().toString())).getClass())
.toArray()) {
boolean foundChild = false; boolean foundChild = false;
for (String element : fieldsToInclude) { for (String element : fieldsToInclude) {
if (getName(((Field) fieldChild).getType().toString()).equals(element)) { if (getName(((Field) fieldChild).getType().toString()).equals(element)) {
@ -158,14 +161,13 @@ public class ModelServiceImpl<T> implements ModelService<T> {
modelChild.put(((Field) fieldChild).getName(), ""); modelChild.put(((Field) fieldChild).getName(), "");
} }
} }
List<Map<String,Object>> attribtues =listMapAttributes(converToObject(getName(((Field) field).getType().toString())),((Field) field).getName(),language); List<Map<String, Object>> attribtues = listMapAttributes(
for(Map<String,Object> map : attribtues) converToObject(getName(((Field) field).getType().toString())),
{ ((Field) field).getName(), language);
for (Map<String, Object> map : attribtues) {
allAttributes.add(map); allAttributes.add(map);
} }
//modelChild.put("attributes", listMapAttributes(converToObject(getName(((Field) field).getType().toString()))));
model.put(((Field) field).getName(), modelChild); model.put(((Field) field).getName(), modelChild);
} }
@ -176,8 +178,7 @@ public class ModelServiceImpl<T> implements ModelService<T> {
} }
modelDTO.setModel(model); modelDTO.setModel(model);
for(Map<String,Object> map : listMapAttributes(o,"",language)) for (Map<String, Object> map : listMapAttributes(o, "", language)) {
{
allAttributes.add(map); allAttributes.add(map);
} }
modelDTO.setAttributes(allAttributes); modelDTO.setAttributes(allAttributes);
@ -185,9 +186,6 @@ public class ModelServiceImpl<T> implements ModelService<T> {
} }
// generate attribute json // generate attribute json
public List<Map<String, Object>> listMapAttributes(Object object, String modelName, String language) { public List<Map<String, Object>> listMapAttributes(Object object, String modelName, String language) {
@ -238,15 +236,10 @@ public class ModelServiceImpl<T> implements ModelService<T> {
if (a instanceof com.jasamedika.medifirst2000.helper.Caption) { if (a instanceof com.jasamedika.medifirst2000.helper.Caption) {
com.jasamedika.medifirst2000.helper.Caption test = (Caption) a; com.jasamedika.medifirst2000.helper.Caption test = (Caption) a;
System.out.println(test.value()); System.out.println(test.value());
//attributeModel.put("caption", messageSource.getMessage(test.value(), null, new Locale(language)));
attributeModel.put("caption", test.value()); attributeModel.put("caption", test.value());
} }
return attributeModel; return attributeModel;
} }
public List<Map<String, Object>> getAllData(String entity, String field, Integer take, Integer skip, Integer page, public List<Map<String, Object>> getAllData(String entity, String field, Integer take, Integer skip, Integer page,
@ -275,13 +268,12 @@ public class ModelServiceImpl<T> implements ModelService<T> {
} }
List<Map<String, Object>> listEntity = null; List<Map<String, Object>> listEntity = null;
try { try {
listEntity = JsonUtil.ToMaps( genericServDao.getDatas(entity, field, Math.abs(rowStart), rowEnd, logic, value, fieldS, listEntity = JsonUtil.ToMaps(genericServDao.getDatas(entity, field, Math.abs(rowStart), rowEnd, logic,
operator,criteria,values)); value, fieldS, operator, criteria, values));
} catch (IllegalArgumentException | IllegalAccessException e) { } catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
return listEntity; return listEntity;
} }
} }

View File

@ -25,6 +25,7 @@ import com.jasamedika.medifirst2000.util.JsonUtil;
* *
* @author Adik * @author Adik
*/ */
@SuppressWarnings("serial")
@MappedSuperclass @MappedSuperclass
public abstract class BaseModel implements Serializable { public abstract class BaseModel implements Serializable {
@ -62,9 +63,11 @@ public abstract class BaseModel implements Serializable {
} }
return maps; return maps;
} }
public Map<String, Object> ToMap() throws IllegalArgumentException, IllegalAccessException { public Map<String, Object> ToMap() throws IllegalArgumentException, IllegalAccessException {
return ToMap(3); return ToMap(3);
} }
public Map<String, Object> ToMap(Integer index) throws IllegalArgumentException, IllegalAccessException { public Map<String, Object> ToMap(Integer index) throws IllegalArgumentException, IllegalAccessException {
Map<String, Object> maps = new HashMap<String, Object>(); Map<String, Object> maps = new HashMap<String, Object>();
for (Field field : BaseModel.GetFields(this.getClass())) { for (Field field : BaseModel.GetFields(this.getClass())) {
@ -126,15 +129,11 @@ public abstract class BaseModel implements Serializable {
if (valid == true) { if (valid == true) {
Object property = field.get(this); Object property = field.get(this);
if (property == null) if (property == null) {
{ // do when property is null
//maps.put(str, null); } else {
} if (property instanceof HibernateProxy) {
else {
if(property instanceof HibernateProxy)
{
property = JsonUtil.initializeAndUnproxy(property); property = JsonUtil.initializeAndUnproxy(property);
} }
if (property instanceof BaseModel) { if (property instanceof BaseModel) {
@ -180,6 +179,8 @@ public abstract class BaseModel implements Serializable {
return maps; return maps;
} }
@SuppressWarnings("rawtypes")
public static List<Field> GetFields(Class data) { public static List<Field> GetFields(Class data) {
List<Field> items = new ArrayList<Field>(); List<Field> items = new ArrayList<Field>();
Class parent = data.getSuperclass(); Class parent = data.getSuperclass();
@ -213,6 +214,8 @@ public abstract class BaseModel implements Serializable {
public String getName(String value) { public String getName(String value) {
return value.substring(value.lastIndexOf('.') + 1).trim(); return value.substring(value.lastIndexOf('.') + 1).trim();
} }
@SuppressWarnings("rawtypes")
public Map<String, Object> serialize(String[] fieldsToInclude, String className) throws Exception { public Map<String, Object> serialize(String[] fieldsToInclude, String className) throws Exception {
String name = "com.jasamedika.medifirst2000.entities." + getName(className); String name = "com.jasamedika.medifirst2000.entities." + getName(className);
Class cl = null; Class cl = null;
@ -248,9 +251,7 @@ public abstract class BaseModel implements Serializable {
} }
} }
return fields; return fields;
} }
} }

View File

@ -40,14 +40,10 @@ public class GenericServiceController extends LocaleController<AntrianPasienRegi
private ModelService<?> modelService; private ModelService<?> modelService;
private static final String CONTENT_TYPE = "Content-Type"; private static final String CONTENT_TYPE = "Content-Type";
@SuppressWarnings("rawtypes")
public static List<Field> GetFields(Class data) { public static List<Field> GetFields(Class data) {
List<Field> items = new ArrayList<Field>(); List<Field> items = new ArrayList<Field>();
// String name = data.getName();
Class parent = data.getSuperclass(); Class parent = data.getSuperclass();
// if (parent instanceof Class) {
// name = ((Class) parent).getName();
// }
Class tmpClass = null; Class tmpClass = null;
if (BaseModelVO.class.isAssignableFrom(data.getClass())) { if (BaseModelVO.class.isAssignableFrom(data.getClass())) {
tmpClass = BaseTransactionVO.class; tmpClass = BaseTransactionVO.class;
@ -80,14 +76,7 @@ public class GenericServiceController extends LocaleController<AntrianPasienRegi
return RestUtil.getJsonResponse(GetSettingDataFixed(prefix), HttpStatus.CREATED, mapHeaderMessage); return RestUtil.getJsonResponse(GetSettingDataFixed(prefix), HttpStatus.CREATED, mapHeaderMessage);
} }
@RequestMapping(value = "/list-generic/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) // &skip={skip}&page={page}&pageSize={pageSize}&filter[logic]={logic}&filter[filters][0][value]={value}&filter[filters][0][field]={fields}&filter[filters][0][operator]={operator}&filter[filters][0][ignoreCase]={ignorecase}", @RequestMapping(value = "/list-generic/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// method
// =
// RequestMethod.GET,
// produces
// =
// MediaType.APPLICATION_JSON_VALUE)
// @Cacheable ("default")
public ResponseEntity<List<Map<String, Object>>> listGeneric( public ResponseEntity<List<Map<String, Object>>> listGeneric(
@RequestParam(value = "view", required = false) String entity, @RequestParam(value = "view", required = false) String entity,
@RequestParam(value = "select", required = false) String field, @RequestParam(value = "select", required = false) String field,
@ -103,7 +92,6 @@ public class GenericServiceController extends LocaleController<AntrianPasienRegi
@RequestParam(value = "criteria", required = false) String criteria, @RequestParam(value = "criteria", required = false) String criteria,
@RequestParam(value = "values", required = false) String values, HttpServletRequest request) @RequestParam(value = "values", required = false) String values, HttpServletRequest request)
throws SecurityException, ClassNotFoundException, JSONException, UnsupportedEncodingException { throws SecurityException, ClassNotFoundException, JSONException, UnsupportedEncodingException {
// for numeric or integer using {numeric}
String data = request.getQueryString(); String data = request.getQueryString();
data = URLDecoder.decode(data, "UTF-8"); data = URLDecoder.decode(data, "UTF-8");
@ -122,7 +110,7 @@ public class GenericServiceController extends LocaleController<AntrianPasienRegi
values += "," + query.replace("filter[filters][0][filter][value]=", ""); values += "," + query.replace("filter[filters][0][filter][value]=", "");
} }
} }
// map.put("data", src);
if (field.equals("*")) { if (field.equals("*")) {
field = ""; field = "";
@ -152,7 +140,6 @@ public class GenericServiceController extends LocaleController<AntrianPasienRegi
else else
field += "," + fieldItem.getName(); field += "," + fieldItem.getName();
} }
// field+=",id";
} }
} else if (field.equals("**")) { } else if (field.equals("**")) {
field = "*"; field = "*";
@ -162,16 +149,14 @@ public class GenericServiceController extends LocaleController<AntrianPasienRegi
List<Map<String, Object>> modelGenericVO = modelService.getAllData(entity, field, take, skip, page, pageSize, List<Map<String, Object>> modelGenericVO = modelService.getAllData(entity, field, take, skip, page, pageSize,
logic, value, fieldS, operator, ignorecase, criteria, values); logic, value, fieldS, operator, ignorecase, criteria, values);
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
// headers.add(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); headers.set(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// Map<String, Object> map = new HashMap<String, Object>();
try { try {
return new ResponseEntity(JsonUtil.ToMaps(modelGenericVO), headers, HttpStatus.OK); return new ResponseEntity<List<Map<String, Object>>>(JsonUtil.ToMaps(modelGenericVO), headers,
HttpStatus.OK);
} catch (IllegalArgumentException | IllegalAccessException e) { } catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
// return RestUtil.getJsonResponse(modelGenericVO, HttpStatus.OK);
return null; return null;
} }

View File

@ -41,7 +41,6 @@ import com.jasamedika.medifirst2000.converter.BaseConverterImpl;
import com.jasamedika.medifirst2000.core.web.WebConstants; import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.entities.Pegawai; import com.jasamedika.medifirst2000.entities.Pegawai;
import com.jasamedika.medifirst2000.service.ActivityPegawaiService; import com.jasamedika.medifirst2000.service.ActivityPegawaiService;
import com.jasamedika.medifirst2000.service.AgamaService;
import com.jasamedika.medifirst2000.service.LoginUserService; import com.jasamedika.medifirst2000.service.LoginUserService;
import com.jasamedika.medifirst2000.service.ModelService; import com.jasamedika.medifirst2000.service.ModelService;
import com.jasamedika.medifirst2000.util.rest.RestUtil; import com.jasamedika.medifirst2000.util.rest.RestUtil;
@ -58,15 +57,14 @@ import io.socket.client.IO;
* @author Roberto * @author Roberto
*/ */
public abstract class LocaleController<V extends BaseModelVO> { public abstract class LocaleController<V extends BaseModelVO> {
/* /*
* messageSource bean injected for each controller for accessing message * messageSource bean injected for each controller for accessing message
* source * source
*/ */
@Autowired @Autowired
private ActivityPegawaiService activityPegawaiServiceImpl; private ActivityPegawaiService activityPegawaiServiceImpl;
@Autowired @Autowired
private BaseConverterImpl<PegawaiVO, Pegawai> pegawaiConverter; private BaseConverterImpl<PegawaiVO, Pegawai> pegawaiConverter;
@ -76,12 +74,10 @@ public abstract class LocaleController<V extends BaseModelVO> {
@Autowired @Autowired
private MessageSource messageSource; private MessageSource messageSource;
@SuppressWarnings("rawtypes")
@Autowired @Autowired
private ModelService modelService; private ModelService modelService;
@Autowired
private AgamaService agamaService;
protected Map<String, String> mapHeaderMessage = new HashMap<String, String>(); protected Map<String, String> mapHeaderMessage = new HashMap<String, String>();
/* /*
@ -92,10 +88,12 @@ public abstract class LocaleController<V extends BaseModelVO> {
} }
protected void SaveLog(String keterangan, String group, HttpServletRequest request) { protected void SaveLog(String keterangan, String group, HttpServletRequest request) {
activityPegawaiServiceImpl.record(pegawaiConverter.transferModelToVO(loginUserService.getLoginUser().getPegawai(), new PegawaiVO()) , new Date(), keterangan,group); activityPegawaiServiceImpl.record(
pegawaiConverter.transferModelToVO(loginUserService.getLoginUser().getPegawai(), new PegawaiVO()),
new Date(), keterangan, group);
} }
protected Object getItem(HttpServletRequest request,Object vo)
{ protected Object getItem(HttpServletRequest request, Object vo) {
BufferedReader reader; BufferedReader reader;
String read = null; String read = null;
String resultData = ""; String resultData = "";
@ -103,23 +101,19 @@ public abstract class LocaleController<V extends BaseModelVO> {
try { try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream())); reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
while ((read = reader.readLine()) != null) { while ((read = reader.readLine()) != null) {
resultData += read; resultData += read;
System.out.println(read); System.out.println(read);
} }
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")//.excludeFieldsWithoutExposeAnnotation() gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
.create();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return vo = gson.fromJson(resultData, vo.getClass()); return vo = gson.fromJson(resultData, vo.getClass());
} }
protected Object getItem2(HttpServletRequest request,Object vo) protected Object getItem2(HttpServletRequest request, Object vo) {
{
BufferedReader reader; BufferedReader reader;
String read = null; String read = null;
String resultData = ""; String resultData = "";
@ -244,18 +238,10 @@ public abstract class LocaleController<V extends BaseModelVO> {
} }
} }
// @PersistenceContext
// protected EntityManager em;
public String GetSettingDataFixed(String prefix) { public String GetSettingDataFixed(String prefix) {
return activityPegawaiServiceImpl.GetSettingDataFixed(prefix); return activityPegawaiServiceImpl.GetSettingDataFixed(prefix);
// StringBuffer buffer = new StringBuffer();
// buffer.append("select model.nilaiField from SettingDataFixed ")
// .append(" model where model.namaField ='" + prefix + "' ");
// Query query = em.createQuery(buffer.toString());
//
// return (String) query.getSingleResult();
} }
protected void BroadcastMessage(final String to, final Object data) { protected void BroadcastMessage(final String to, final Object data) {
final io.socket.client.Socket socket; final io.socket.client.Socket socket;
try { try {
@ -270,7 +256,8 @@ public abstract class LocaleController<V extends BaseModelVO> {
try { try {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(data); String json = gson.toJson(data);
JSONObject item= new JSONObject("{\"to\":\""+to+"\",\"message\":\""+json.replace("\"", "'")+"\"}"); JSONObject item = new JSONObject(
"{\"to\":\"" + to + "\",\"message\":\"" + json.replace("\"", "'") + "\"}");
socket.emit("subscribe", item); socket.emit("subscribe", item);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
@ -283,6 +270,7 @@ public abstract class LocaleController<V extends BaseModelVO> {
e.printStackTrace(); e.printStackTrace();
} }
} }
protected void BroadcastMessage(final String to, final String data) { protected void BroadcastMessage(final String to, final String data) {
final io.socket.client.Socket socket; final io.socket.client.Socket socket;
try { try {