com.github.aidensuen.mongo.command.DynamicCommandBuilder Maven / Gradle / Ivy
package com.github.aidensuen.mongo.command;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.aidensuen.mongo.exception.BindingException;
import com.github.aidensuen.mongo.mapping.ParameterHolder;
import com.github.aidensuen.mongo.parsing.GenericTokenParser;
import com.github.aidensuen.mongo.parsing.TokenHandler;
import com.github.aidensuen.mongo.session.Configuration;
import com.github.aidensuen.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
public class DynamicCommandBuilder {
private static Logger LOGGER = LoggerFactory.getLogger(DynamicCommandBuilder.class);
private final Configuration configuration;
public DynamicCommandBuilder(Configuration configuration) {
this.configuration = configuration;
}
public CommandSource parse(String originalCommandSource, ParameterHolder parameterHolder) {
LOGGER.debug("start parse time: {}", new Date().getTime());
ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(parameterHolder);
GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
String command = parser.parse(originalCommandSource);
LOGGER.debug("end parse time: {}", new Date().getTime());
LOGGER.debug("parsed command: {}", command);
return new StaticCommandSource(command, this.configuration);
}
private static class ParameterMappingTokenHandler implements TokenHandler {
private static ObjectMapper objectMapper = new ObjectMapper();
private final ParameterHolder parameterHolder;
public ParameterMappingTokenHandler(ParameterHolder parameterHolder) {
this.parameterHolder = parameterHolder;
}
@Override
public String handleToken(String content, int openTokenCount) {
try {
if (!StringUtil.isEmpty(content)) {
String key = content.trim();
if (ParameterHolder.PARAMETER_OBJECT_KEY.equals(key) || "collection".equals(content) || "list".equals(content) || "array".equals(content)) {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
} else {
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
}
if (openTokenCount > 1) {
// has child expression, can determine it's string expression
return (String) this.parameterHolder.getPropertyValue(key);
} else {
return objectMapper.writeValueAsString(this.parameterHolder.getPropertyValue(key));
}
}
} catch (Exception e) {
throw new BindingException("param bind failed! " + e.toString());
}
return null;
}
}
}