package com.mobcom.db;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.mobcom.conf.MobcomProperties;
import com.mobcom.models.Product;
public class MobcomAdapter {
private final DocumentBuilderFactory _docBuilderFactory;
private final DocumentBuilder _docBuilder;
private static MobcomAdapter _instance;
private final DBStore _dbStore;
private MobcomAdapter() throws ParserConfigurationException {
_docBuilderFactory = DocumentBuilderFactory.newInstance();
_docBuilder = _docBuilderFactory.newDocumentBuilder();
_dbStore = DBStore.newInstance();
}
public static MobcomAdapter newInstance() {
try {
if(_instance == null)
_instance = new MobcomAdapter();
return _instance;
}
catch(ParserConfigurationException pce) {
pce.printStackTrace();
return null;
}
}
public boolean parseAsProducts(InputStream xmlStream) {
boolean status = false;
try {
Document doc = _docBuilder.parse(xmlStream);
XPath xpath = XPathFactory.newInstance().newXPath();
MobcomProperties props = MobcomProperties.getInstance();
Node validNode = (Node) xpath.evaluate(props.get("XPATH_VALID"), doc,
XPathConstants.NODE);
if(validNode != null)
System.out.println(validNode.getTextContent());
if(validNode == null || validNode.getTextContent().equals("False"))
{
Node message = (Node) xpath.evaluate(props.get("XPATH_ERRORMESSAGE"),
doc,
XPathConstants.NODE);
System.out.println("Invalid xml response. " + message.getTextContent());
return status;
}
NodeList asinList = (NodeList) xpath.evaluate(props.get("XPATH_ASIN"),
doc, XPathConstants.NODESET);
NodeList smallImages = (NodeList) xpath.evaluate(props.get("XPATH_SMALL_IMAGES"),
doc, XPathConstants.NODESET);
if(asinList == null || smallImages == null)
{
System.out.println("Null");
return status;
}
System.out.println("node list size : " + asinList.getLength());
int size = asinList.getLength();
if(size != smallImages.getLength())
{
System.out.println("Smallimages size != size of asinList");
System.out.println("Small images : " + smallImages.getLength());
}
for(int i = 0; i < size; i++)
{
Product prod = new Product();
prod.setId(asinList.item(i).getTextContent());
prod.setSmallSizeImageUrl(smallImages.item(i).getTextContent());
_dbStore.addProduct(prod);
}
status = true;
}
catch(IOException ioe) {
ioe.printStackTrace();
}
catch(SAXException sae) {
sae.printStackTrace();
}
catch(XPathExpressionException xee) {
xee.printStackTrace();
}
return status;
}
}