com.nikedlab.android.inject.InjectUtils Maven / Gradle / Ivy
package com.nikedlab.android.inject;
import android.content.Context;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created with Comodo Inc.
* User: nike
* Date: 8/5/13
* Time: 11:14 PM
*/
public class InjectUtils {
private static List beans = new ArrayList();
public static List getBeans(Context context) {
InputStream configIs;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
configIs = context.getAssets().open("context.xml");
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(configIs);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("bean");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Bean bean = new Bean();
Element element = (Element) nNode;
bean.setId(element.getAttribute("id"));
bean.setClazz(element.getAttribute("class"));
if ("systemService".equals(element.getAttribute("xml:base"))) {
bean.setSystemService(true);
}
if (!"".equals(element.getAttribute("scope"))) {
bean.setSingleton(true);
}
NodeList elementsByTagName = element.getElementsByTagName("constructor-arg");
for (int temp2 = 0; temp2 < elementsByTagName.getLength(); temp2++) {
Node nNodeChild = elementsByTagName.item(temp2);
Element child = (Element) nNodeChild;
if (child != null) {
Bean.Args args = new Bean().new Args();
args.setType(child.getAttribute("type"));
args.setValue(child.getAttribute("value"));
if (!child.getAttribute("ref").equals("")) {
String type = _getTypeByRef(child.getAttribute("ref"));
if (!"".equals(type)) {
args.setReferral(type);
} else {
throw new BeanNotFoundException("Not found bean with ID: " + child.getAttribute("ref") +
"\nBear in mind what bean with ID in field 'ref' should be declared early");
}
}
bean.setArgs(args);
}
}
beans.add(bean);
}
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return beans;
}
private static String _getTypeByRef(String ref){
for (Bean bean : beans) {
if(ref.equals(bean.getId())){
return bean.getClazz();
}
}
return "";
}
}