package org.jibeframework.core.data.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.jibeframework.core.Context;
import org.jibeframework.core.service.ConfigService;
import org.jibeframework.core.service.impl.ManagedObjectFactoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
@JsonSerialize(using = FormDataModel.Serializer.class)
public class FormDataModel {
private String modelId;
private Object data;
@Autowired
private ConfigService configService;
public FormDataModel(String modelId, Object data) {
this.modelId = modelId;
this.data = data;
ManagedObjectFactoryImpl.injectDeps(this);
}
@SuppressWarnings("unchecked")
private List<Object> getModel() {
Map<String, Object> model = Context.getCurrentContext().getModel(modelId);
if (model == null) {
model = (Map<String, Object>) configService.getConfig(modelId + ".dataModel");
}
ExpressionParser parser = new SpelExpressionParser();
List<Object> d = new ArrayList<Object>();
for (Map.Entry<String, Object> entry : model.entrySet()) {
Map<String, Object> modelEntry = (Map<String, Object>) entry.getValue();
String name = entry.getKey();
String expr = (String) (modelEntry.containsKey("jread") ? modelEntry.get("jread") : modelEntry.get("jbind"));
if (expr != null) {
Object value = parser.parseExpression(expr).getValue(data);
Map<String, Object> m = new HashMap<String, Object>();
m.put("id", name);
m.put("value", value);
d.add(m);
}
}
return d;
}
public static class Serializer extends JsonSerializer<FormDataModel> {
@Override
public void serialize(FormDataModel value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeObject(value.getModel());
}
}
}