com.datastax.util.io.BigSAXParser Maven / Gradle / Ivy
package com.datastax.util.io;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* UserItem: Anders Hong
* Date: 6/19/13
* Time: 3:34 PM
*/
public class BigSAXParser extends DefaultHandler {
public static Map> extractData(InputStream is,String[] keys){
SAXParserFactory factory= SAXParserFactory.newInstance();
try {
SAXParser parser=factory.newSAXParser();
BigSAXParser bp=new BigSAXParser(keys);
parser.parse(is,bp);
return bp.getData();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
public static Map> extractData(String uri,String[] keys){
SAXParserFactory factory= SAXParserFactory.newInstance();
try {
SAXParser parser=factory.newSAXParser();
BigSAXParser bp=new BigSAXParser(keys);
parser.parse(uri,bp);
return bp.getData();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
public static Map> extractData(File file,String[] keys){
SAXParserFactory factory= SAXParserFactory.newInstance();
try {
SAXParser parser=factory.newSAXParser();
BigSAXParser bp=new BigSAXParser(keys);
parser.parse(file,bp);
return bp.getData();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
private String flag=null;
private String[] keys;
private Map> map=new HashMap>();
public BigSAXParser(String[] keys){
this.keys=keys;
for(String key : keys){
map.put(key,new ArrayList());
}
}
public Map> getData(){
return map;
}
private boolean isKey(String text){
for(String key : keys){
if(key.equals(text)) return true;
}
return false;
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String str=new String(ch,start,length);
if(isKey(flag)){
map.get(flag).add(str);
}
if(isKey(str)){
flag=str;
}else {
flag=null;
}
}
@Override
public void startElement(String url, String LocalName, String qName, Attributes attr) throws SAXException {
}
@Override
public void endElement(String url, String LocalName, String qName) throws SAXException {
}
}