package com.javaeye.jert.domain.query.impl;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.javaeye.jert.domain.query.Query;
import com.javaeye.jert.domain.query.QueryParameter;
import com.javaeye.jert.domain.query.impl.part.DynamicPartFactory;
import com.javaeye.jert.domain.query.impl.part.PlainPart;
/**
* @author Quake Wang
* @since 2005-1-4
* @version $Revision: 1.2 $
*/
public class DynamicParameterQuery implements Query {
private static final Log log = LogFactory.getLog(DynamicParameterQuery.class);
private static final String PARAMETER_TOKEN = "#";
private static final String SQL_PLACE_HOLDER = "?";
private static final String PLAIN_TAG = "plain";
private static final String DYNAMIC_TAG = "dynamic";
private List parts = new ArrayList();
public DynamicParameterQuery(String sql) {
try {
parse("<xml>" + sql + "</xml>");
} catch (Exception e) {
log.error("parse error", e);
//TODO: throw a customized runtime exception;
}
}
public String getSql(QueryParameter[] parameters) {
StringBuffer result = new StringBuffer();
for (Iterator iter = parts.iterator(); iter.hasNext();) {
result.append(((Query) iter.next()).getSql(parameters));
}
return result.toString();
}
public List getParameterNames() {
List result = new ArrayList();
for (Iterator iter = parts.iterator(); iter.hasNext();) {
result.addAll(((Query) iter.next()).getParameterNames());
}
return result;
}
private String format(String sql) {
return sql.replace('\r', ' ').replace('\n', ' ');
}
private void parse(String sql) throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(sql)));
NodeList nodes = d.getDocumentElement().getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node instanceof Element) {
Element child = (Element) node;
if (PLAIN_TAG.equals(child.getNodeName())) {
addPlain(child);
} else if (DYNAMIC_TAG.equals(child.getNodeName())) {
addDynamic(child);
}
}
}
}
private void addPlain(Element child) {
parts.add(new PlainPart(child));
}
private void addDynamic(Element child) {
parts.add(DynamicPartFactory.getPart(child));
}
}