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,86 +98,87 @@ 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) {
ModelVO modelDTO = new ModelVO(); ModelVO modelDTO = new ModelVO();
List<Map<String,Object>> allAttributes = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> allAttributes = new ArrayList<Map<String, Object>>();
Object o = converToObject(name); Object o = converToObject(name);
Map<String, Object> model = new HashMap<String, Object>(); Map<String, Object> model = new HashMap<String, Object>();
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)) {
found = true; found = true;
break; break;
} }
} }
if (!found) { if (!found) {
if (getName(((Field) field).getType().toString()).equals("Set")) { if (getName(((Field) field).getType().toString()).equals("Set")) {
model.put(((Field) field).getName(), new ArrayList<Object>()); model.put(((Field) field).getName(), new ArrayList<Object>());
}else{ } else {
model.put(((Field) field).getName(), new BaseModel() { model.put(((Field) field).getName(), new BaseModel() {
}); });
} }
}else{ } else {
model.put(((Field) field).getName(), ""); model.put(((Field) field).getName(), "");
} }
Annotation[] as = ((Field) field).getDeclaredAnnotations(); Annotation[] as = ((Field) field).getDeclaredAnnotations();
if(CommonUtil.isNotNullOrEmpty(as)){
for (Annotation a : as) {
if (a instanceof javax.persistence.ManyToOne) {
Map<String, Object> modelChild = new HashMap<String, Object>();
for (Object fieldChild : GetFields(converToObject(getName(((Field) field).getType().toString())).getClass()).toArray()) {
boolean foundChild = false;
for (String element : fieldsToInclude) {
if (getName(((Field) fieldChild).getType().toString()).equals(element)) {
foundChild = true;
break;
}
}
if (!foundChild) {
if (getName(((Field) fieldChild).getType().toString()).equals("Set")) {
modelChild.put(((Field) fieldChild).getName(), new ArrayList<Object>());
}else{
modelChild.put(((Field) fieldChild).getName(), new BaseModel() {
});
}
}else{
modelChild.put(((Field) fieldChild).getName(), "");
}
if (CommonUtil.isNotNullOrEmpty(as)) {
for (Annotation a : as) {
if (a instanceof javax.persistence.ManyToOne) {
Map<String, Object> modelChild = new HashMap<String, Object>();
for (Object fieldChild : GetFields(
converToObject(getName(((Field) field).getType().toString())).getClass())
.toArray()) {
boolean foundChild = false;
for (String element : fieldsToInclude) {
if (getName(((Field) fieldChild).getType().toString()).equals(element)) {
foundChild = true;
break;
}
}
if (!foundChild) {
if (getName(((Field) fieldChild).getType().toString()).equals("Set")) {
modelChild.put(((Field) fieldChild).getName(), new ArrayList<Object>());
} else {
modelChild.put(((Field) fieldChild).getName(), new BaseModel() {
});
}
} else {
modelChild.put(((Field) fieldChild).getName(), "");
}
}
List<Map<String, Object>> attribtues = listMapAttributes(
converToObject(getName(((Field) field).getType().toString())),
((Field) field).getName(), language);
for (Map<String, Object> map : attribtues) {
allAttributes.add(map);
}
model.put(((Field) field).getName(), modelChild);
} }
List<Map<String,Object>> attribtues =listMapAttributes(converToObject(getName(((Field) field).getType().toString())),((Field) field).getName(),language);
for(Map<String,Object> map : attribtues)
{
allAttributes.add(map);
}
//modelChild.put("attributes", listMapAttributes(converToObject(getName(((Field) field).getType().toString()))));
model.put(((Field) field).getName(), modelChild);
} }
} }
}
} }
} }
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,35 +186,32 @@ public class ModelServiceImpl<T> implements ModelService<T> {
} }
// generate attribute json
public List<Map<String, Object>> listMapAttributes(Object object, String modelName, String language) {
//generate attribute json
public List<Map<String, Object>>listMapAttributes(Object object,String modelName,String language){
List<Map<String, Object>> attributeModelList = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> attributeModelList = new ArrayList<Map<String, Object>>();
for (Object field : GetFields(object.getClass()).toArray()) { for (Object field : GetFields(object.getClass()).toArray()) {
if (field instanceof Field) { if (field instanceof Field) {
Map<String, Object> attributeModel = new HashMap<String, Object>(); Map<String, Object> attributeModel = new HashMap<String, Object>();
if(modelName != "") if (modelName != "")
attributeModel.put("name",modelName+"."+ ((Field) field).getName()); attributeModel.put("name", modelName + "." + ((Field) field).getName());
else else
attributeModel.put("name", ((Field) field).getName()); attributeModel.put("name", ((Field) field).getName());
attributeModel.put("type", getName(((Field) field).getType().getName())); attributeModel.put("type", getName(((Field) field).getType().getName()));
Annotation[] as = ((Field) field).getDeclaredAnnotations(); Annotation[] as = ((Field) field).getDeclaredAnnotations();
for (Annotation a : as) { for (Annotation a : as) {
checkObject(a, attributeModel,language); checkObject(a, attributeModel, language);
} }
attributeModelList.add(attributeModel); attributeModelList.add(attributeModel);
} }
} }
return attributeModelList; return attributeModelList;
} }
public Map<String, Object> checkObject(Annotation a,Map<String, Object> attributeModel, String language){ public Map<String, Object> checkObject(Annotation a, Map<String, Object> attributeModel, String language) {
if (a instanceof org.hibernate.validator.constraints.Length) { if (a instanceof org.hibernate.validator.constraints.Length) {
org.hibernate.validator.constraints.Length length = (Length) a; org.hibernate.validator.constraints.Length length = (Length) a;
attributeModel.put("maxlength", length.max()); attributeModel.put("maxlength", length.max());
@ -238,24 +236,19 @@ 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,
Integer pageSize, String logic, String value, String fieldS, String operator, String ignorecase, Integer pageSize, String logic, String value, String fieldS, String operator, String ignorecase,
String criteria, String values) { String criteria, String values) {
int rowStart = 0; int rowStart = 0;
int rowEnd = 0; int rowEnd = 0;
if(take!=null) if (take != null)
rowEnd=take; rowEnd = take;
if (take != null && skip != null && page != null && pageSize != null) { if (take != null && skip != null && page != null && pageSize != null) {
int totalRow = genericServDao.dataCount(entity, value, fieldS, criteria, values); int totalRow = genericServDao.dataCount(entity, value, fieldS, criteria, values);
int totalPages = 0; int totalPages = 0;
@ -273,15 +266,14 @@ public class ModelServiceImpl<T> implements ModelService<T> {
rowStart = (pageRequested * pageSize) - pageSize; rowStart = (pageRequested * pageSize) - pageSize;
rowEnd = take; rowEnd = take;
} }
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,9 +25,10 @@ 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 {
public Map<String, Object> ToSingleMap() throws IllegalArgumentException, IllegalAccessException { public Map<String, Object> ToSingleMap() 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())) {
@ -38,9 +39,9 @@ public abstract class BaseModel implements Serializable {
if (name.equals("_methods_")) if (name.equals("_methods_"))
continue; continue;
if (name.equals("handler")) if (name.equals("handler"))
continue; continue;
if (name.equals("_filter_signature")) if (name.equals("_filter_signature"))
continue; continue;
Boolean valid = false; Boolean valid = false;
for (java.lang.annotation.Annotation annotation : field.getDeclaredAnnotations()) { for (java.lang.annotation.Annotation annotation : field.getDeclaredAnnotations()) {
if (annotation instanceof JoinColumn) { if (annotation instanceof JoinColumn) {
@ -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())) {
@ -75,9 +78,9 @@ public abstract class BaseModel implements Serializable {
if (name.equals("_methods_")) if (name.equals("_methods_"))
continue; continue;
if (name.equals("handler")) if (name.equals("handler"))
continue; continue;
if (name.equals("_filter_signature")) if (name.equals("_filter_signature"))
continue; continue;
Boolean valid = false; Boolean valid = false;
for (java.lang.annotation.Annotation annotation : field.getDeclaredAnnotations()) { for (java.lang.annotation.Annotation annotation : field.getDeclaredAnnotations()) {
if (annotation instanceof JoinColumn) { if (annotation instanceof JoinColumn) {
@ -93,93 +96,91 @@ public abstract class BaseModel implements Serializable {
} }
} }
if (valid == false && field.get(this)!=null) if (valid == false && field.get(this) != null)
maps.put(field.getName(), field.get(this)); maps.put(field.getName(), field.get(this));
} }
if(index>1) if (index > 1)
for (Field field : BaseModel.GetFields(this.getClass())) { for (Field field : BaseModel.GetFields(this.getClass())) {
String str = field.getName(); String str = field.getName();
String name = field.getName(); String name = field.getName();
field.setAccessible(true); field.setAccessible(true);
if (name.equals("serialVersionUID")) if (name.equals("serialVersionUID"))
continue;
if (name.equals("_methods_"))
continue;
if (name.equals("handler"))
continue;
if (name.equals("_filter_signature"))
continue; continue;
Boolean valid = false; if (name.equals("_methods_"))
for (java.lang.annotation.Annotation annotation : field.getDeclaredAnnotations()) { continue;
if (annotation instanceof JoinColumn) { if (name.equals("handler"))
valid = true; continue;
} else if (annotation instanceof Column) { if (name.equals("_filter_signature"))
Column column = (Column) annotation; continue;
if (column.name().endsWith("Fk")) Boolean valid = false;
if (field.getName().endsWith("Id") == false) for (java.lang.annotation.Annotation annotation : field.getDeclaredAnnotations()) {
valid = true; if (annotation instanceof JoinColumn) {
} else if (annotation instanceof OneToMany) { valid = true;
} else if (annotation instanceof Column) {
Column column = (Column) annotation;
if (column.name().endsWith("Fk"))
if (field.getName().endsWith("Id") == false)
valid = true;
} else if (annotation instanceof OneToMany) {
valid = true; valid = true;
} }
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 { property = JsonUtil.initializeAndUnproxy(property);
}
if(property instanceof HibernateProxy) if (property instanceof BaseModel) {
{ Map<String, Object> mapItems = new HashMap<String, Object>();
property = JsonUtil.initializeAndUnproxy(property); for (Field fieldItem : BaseModel.GetFields(property.getClass())) {
} String nameItem = fieldItem.getName();
if (property instanceof BaseModel) { fieldItem.setAccessible(true);
Map<String, Object> mapItems = new HashMap<String, Object>(); if (nameItem.equals("serialVersionUID"))
for (Field fieldItem : BaseModel.GetFields(property.getClass())) {
String nameItem = fieldItem.getName();
fieldItem.setAccessible(true);
if (nameItem.equals("serialVersionUID"))
continue;
if (nameItem.equals("_methods_"))
continue;
if (nameItem.equals("handler"))
continue;
if (nameItem.equals("_filter_signature"))
continue; continue;
Boolean validItem = false; if (nameItem.equals("_methods_"))
for (java.lang.annotation.Annotation annotationItem : fieldItem continue;
.getDeclaredAnnotations()) { if (nameItem.equals("handler"))
if (annotationItem instanceof JoinColumn) { continue;
validItem = true; if (nameItem.equals("_filter_signature"))
} else if (annotationItem instanceof Column) { continue;
Column columnItem = (Column) annotationItem; Boolean validItem = false;
if (columnItem.name().endsWith("Fk")) for (java.lang.annotation.Annotation annotationItem : fieldItem
if (fieldItem.getName().endsWith("Id") == false) .getDeclaredAnnotations()) {
validItem = true; if (annotationItem instanceof JoinColumn) {
} else if (annotationItem instanceof OneToMany) { validItem = true;
} else if (annotationItem instanceof Column) {
Column columnItem = (Column) annotationItem;
if (columnItem.name().endsWith("Fk"))
if (fieldItem.getName().endsWith("Id") == false)
validItem = true;
} else if (annotationItem instanceof OneToMany) {
validItem = true; validItem = true;
}
}
if (validItem == false && fieldItem.get(property) != null) {
mapItems.put(fieldItem.getName(), fieldItem.get(property));
} }
} }
if (validItem == false && fieldItem.get(property)!=null) { maps.put(str, mapItems);
mapItems.put(fieldItem.getName(), fieldItem.get(property));
}
} }
maps.put(str, mapItems);
} }
} }
} }
} }
}
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;
@ -222,18 +225,18 @@ public abstract class BaseModel implements Serializable {
e.printStackTrace(); e.printStackTrace();
} }
Map<String, Object> fields = new HashMap<String, Object>(); Map<String, Object> fields = new HashMap<String, Object>();
if(CommonUtil.isNotNullOrEmpty(cl)){ if (CommonUtil.isNotNullOrEmpty(cl)) {
for (Object f : GetFields(cl).toArray()) { for (Object f : GetFields(cl).toArray()) {
if (!getName(((Field) f).getType().toString()).equalsIgnoreCase("Set")) { if (!getName(((Field) f).getType().toString()).equalsIgnoreCase("Set")) {
if (f instanceof Field) { if (f instanceof Field) {
((AccessibleObject) f).setAccessible(true); ((AccessibleObject) f).setAccessible(true);
boolean found = false; boolean found = false;
if (CommonUtil.isNotNullOrEmpty(fieldsToInclude)) { if (CommonUtil.isNotNullOrEmpty(fieldsToInclude)) {
for (String element : fieldsToInclude) { for (String element : fieldsToInclude) {
if (((Field) f).getName().equals(element)){ if (((Field) f).getName().equals(element)) {
found = true; found = true;
break; break;
} }
} }
} else { } else {
@ -247,10 +250,8 @@ 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,30 +57,27 @@ 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;
@Autowired @Autowired
private LoginUserService loginUserService; private LoginUserService loginUserService;
@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>();
/* /*
@ -90,64 +86,62 @@ public abstract class LocaleController<V extends BaseModelVO> {
protected String getMessage(String code, HttpServletRequest request) { protected String getMessage(String code, HttpServletRequest request) {
return messageSource.getMessage(code, null, new Locale(getCoociesLanguage(request))); return messageSource.getMessage(code, null, new Locale(getCoociesLanguage(request)));
} }
protected void SaveLog(String keterangan,String group, HttpServletRequest request) { protected void SaveLog(String keterangan, String group, 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 = "";
Gson gson = new Gson(); Gson gson = new Gson();
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").create();
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")//.excludeFieldsWithoutExposeAnnotation()
.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 = "";
Gson gson = new Gson(); Gson gson = new Gson();
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);
} }
GsonBuilder gsonBuilder = new GsonBuilder(); GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override @Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException { throws JsonParseException {
if(json.getAsString() instanceof String){ if (json.getAsString() instanceof String) {
return new Date(); return new Date();
}else{ } else {
return new Date(json.getAsJsonPrimitive().getAsLong()); return new Date(json.getAsJsonPrimitive().getAsLong());
} }
} }
}); });
gson = gsonBuilder.create(); gson = gsonBuilder.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());
} }
@RequestMapping(value = "/lang/{lang}", method = RequestMethod.GET) @RequestMapping(value = "/lang/{lang}", method = RequestMethod.GET)
@ -244,33 +238,26 @@ 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 {
String url =GetSettingDataFixed("UrlSocketMessaging"); String url = GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url); socket = IO.socket(url);
socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() { socket.on(io.socket.client.Socket.EVENT_CONNECT, new io.socket.emitter.Emitter.Listener() {
@Override @Override
public void call(Object... args) { public void call(Object... args) {
try { try {
Gson gson = new Gson(); Gson gson = new Gson();
String json = gson.toJson(data); String json = gson.toJson(data);
JSONObject item= new JSONObject("{\"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 {
@ -292,9 +280,9 @@ public abstract class LocaleController<V extends BaseModelVO> {
@Override @Override
public void call(Object... args) { public void call(Object... args) {
try { try {
JSONObject item= new JSONObject("{\"to\":\""+to+"\",\"message\":\""+data+"\"}"); JSONObject item = new JSONObject("{\"to\":\"" + to + "\",\"message\":\"" + data + "\"}");
socket.emit("subscribe", item); socket.emit("subscribe", item);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
@ -307,10 +295,10 @@ public abstract class LocaleController<V extends BaseModelVO> {
e.printStackTrace(); e.printStackTrace();
} }
} }
protected void BroadcastMessageOther(final String to, final Object data) { protected void BroadcastMessageOther(final String to, final Object data) {
final io.socket.client.Socket socket; final io.socket.client.Socket socket;
try { try {
String url = GetSettingDataFixed("UrlSocketMessaging"); String url = GetSettingDataFixed("UrlSocketMessaging");
socket = IO.socket(url); socket = IO.socket(url);
@ -322,7 +310,7 @@ public abstract class LocaleController<V extends BaseModelVO> {
Map<String, Object> result = new HashMap<>(); Map<String, Object> result = new HashMap<>();
result.put("message", data); result.put("message", data);
result.put("to", to); result.put("to", to);
Gson gson = new Gson(); Gson gson = new Gson();
JSONObject item = new JSONObject(gson.toJson(result)); JSONObject item = new JSONObject(gson.toJson(result));
socket.emit("subscribe", item); socket.emit("subscribe", item);