Added a JSON parser and a new DB connection handler and pool

This commit is contained in:
Ziver Koc 2010-05-04 12:59:57 +00:00
parent 952a388cf1
commit 6ad303a948
6 changed files with 785 additions and 1 deletions

View file

@ -0,0 +1,232 @@
package zutil.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* This class parses a string with math
* and solves it
*
* @author Ziver
*/
public class MathParser {
public static MathNode parse(String functionString){
StringBuffer functionStringBuffer = new StringBuffer(functionString+(char)0);
MathNode node = new MathNode();
parse(functionStringBuffer, new StringBuffer(), null, node);
System.out.println("----------------------------------------------------------------------");
System.out.println(node+" = "+node.exec());
System.out.println("----------------------------------------------------------------------");
return node;
}
private static void parse(StringBuffer functionString, StringBuffer temp, MathOperation previus, MathNode rootNode){
if(functionString.length() <= 0){
return;
}
char c = functionString.charAt(0);
functionString.deleteCharAt(0);
System.out.println("char: "+c);
MathOperation current = null;
if(!Character.isWhitespace(c)){
if(isNumber(c)){
temp.append(c);
}
else{
Math container = new MathNumber();
if(temp.length() > 0){
System.out.println("("+Double.parseDouble(temp.toString())+")");
((MathNumber)container).num = Double.parseDouble(temp.toString());
temp.delete(0, temp.length());
}
if(rootNode.math == null){
System.out.println("Initializing rootNode");
previus = getOperation(c);
System.out.println("operation: "+previus.getClass().getName());
previus.math1 = container;
rootNode.math = previus;
}
else{
if(c == '('){
MathNode parantes = new MathNode();
MathOperation previusParantes = previus;
parse(functionString, temp, previus, parantes);
previusParantes.math2 = parantes;
System.out.println(parantes);
container = parantes;
// get the next operation
c = functionString.charAt(0);
functionString.deleteCharAt(0);
System.out.println("char: "+c);
}
current = getOperation(c);
System.out.println("operation: "+current.getClass().getName());
current.math1 = container;
previus.math2 = current;
if(c == ')'){
return;
}
}
}
}
if(current != null) parse(functionString, temp, current, rootNode);
else parse(functionString, temp, previus, rootNode);
return;
}
private static boolean isNumber(char c){
if(Character.isDigit(c)){
return true;
}
return false;
}
private static MathOperation getOperation(char c){
switch(c){
case '+': return new MathAddition();
case '-': return new MathSubtraction();
case '*': return new MathMultiplication();
case '/': return new MathDivision();
case '%': return new MathModulus();
case '^': return new MathPow();
case ')':
case (char)0: return new EmptyMath();
default: return null;
}
}
public static void main(String[] args){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print(">>Math: ");
parse(in.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
abstract class Math{
public abstract double exec();
public abstract String toString();
}
class MathNode extends Math{
Math math;
public double exec() {
return math.exec();
}
public String toString() {
return "( "+math.toString()+" )";
}
}
class MathNumber extends Math{
double num;
public double exec() {
return num;
}
public String toString() {
return ""+num;
}
}
abstract class MathOperation extends Math{
Math math1;
Math math2;
public abstract double exec();
}
class MathAddition extends MathOperation{
public double exec() {
return math1.exec() + math2.exec();
}
public String toString() {
return math1.toString()+" + "+math2.toString();
}
}
class MathSubtraction extends MathOperation{
public double exec() {
return math1.exec() - math2.exec();
}
public String toString() {
return math1.toString()+" - "+math2.toString();
}
}
class MathMultiplication extends MathOperation{
public double exec() {
return math1.exec() * math2.exec();
}
public String toString() {
return math1.toString()+" * "+math2.toString();
}
}
class MathDivision extends MathOperation{
public double exec() {
return math1.exec() / math2.exec();
}
public String toString() {
return math1.toString()+" / "+math2.toString();
}
}
class MathModulus extends MathOperation{
public double exec() {
return math1.exec() % math2.exec();
}
public String toString() {
return math1.toString()+" % "+math2.toString();
}
}
class MathPow extends MathOperation{
public double exec() {
double ret = 1;
double tmp1 = math1.exec();
double tmp2 = math2.exec();
for(int i=0; i<tmp2 ;i++){
ret *= tmp1;
}
return ret;
}
public String toString() {
return math1.toString()+"^"+math2.toString();
}
}
class EmptyMath extends MathOperation{
public double exec() {
return math1.exec();
}
public String toString() {
return math1.toString();
}
}

View file

@ -0,0 +1,247 @@
package zutil.parser.json;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* This is an node in an JSON tree,
* it may contain a Map, list or value
*
* @author Ziver
*/
public class JSONNode implements Iterable<JSONNode>{
public enum JSONType{
Map, List, String, Number, Boolean
}
private Map<String,JSONNode> map = null;
private List<JSONNode> list = null;
private String value = null;
private JSONType type;
/**
* Creates an instance with an Boolean value
*/
public JSONNode(boolean value){
this.type = JSONType.Boolean;
this.value = ""+value;
}
/**
* Creates an instance with an int value
*/
public JSONNode(int value){
this.type = JSONType.Number;
this.value = ""+value;
}
/**
* Creates an instance with an double value
*/
public JSONNode(double value){
this.type = JSONType.Number;
this.value = ""+value;
}
/**
* Creates an instance with an String value
*/
public JSONNode(String value){
this.type = JSONType.String;
this.value = value;
}
/**
* Creates an instance with a specific type
*/
public JSONNode(JSONType type){
this.type = type;
switch(type){
case Map:
map = new HashMap<String,JSONNode>(); break;
case List:
list = new LinkedList<JSONNode>(); break;
}
}
/**
* @param index is the index of the List or Map
* @return an JSONNode that contains the next level of the List or Map
*/
public JSONNode get(int index){
if(map != null)
return map.get(""+index);
else if(list != null)
return list.get(index);
return null;
}
/**
* @param index is the key in the Map
* @return an JSONNode that contains the next level of the Map
*/
public JSONNode get(String index){
if(map != null)
return map.get(index);
return null;
}
/**
* @return a iterator for the Map or List or null if the node contains a value
*/
public Iterator<JSONNode> iterator(){
if(map != null)
return map.values().iterator();
else if(list != null)
return list.iterator();
return null;
}
/**
* @return a iterator for the keys in the Map or null if the node contains a value or List
*/
public Iterator<String> keyIterator(){
if(map != null)
return map.keySet().iterator();
return null;
}
/**
* @return the size of the Map or List or -1 if it is a value
*/
public int size(){
if(map != null)
return map.size();
else if(list != null)
return list.size();
return -1;
}
/**
* Adds a node to the List
*/
public void add(JSONNode node){
list.add(node);
}
public void add(boolean value){
list.add(new JSONNode( value ));
}
public void add(int value){
list.add(new JSONNode( value ));
}
public void add(double value){
list.add(new JSONNode( value ));
}
public void add(String value){
list.add(new JSONNode( value ));
}
/**
* Adds a node to the Map
*/
public void add(String key, JSONNode node){
map.put(key, node);
}
public void add(String key, boolean value){
map.put(key, new JSONNode(value));
}
public void add(String key, int value){
map.put(key, new JSONNode(value));
}
public void add(String key, double value){
map.put(key, new JSONNode(value));
}
public void add(String key, String value){
map.put(key, new JSONNode(value));
}
/**
* Sets the value of the node, but only if it is setup as an JSONType.Value
*/
public void set(int value){
if( !this.isValue() ) return;
type = JSONType.Number;
this.value = ""+value;
}
/**
* Sets the value of the node, but only if it is setup as an JSONType.Value
*/
public void set(double value){
if( !this.isValue() ) return;
type = JSONType.Number;
this.value = ""+value;
}
/**
* Sets the value of the node, but only if it is setup as an JSONType.Value
*/
public void set(boolean value){
if( !this.isValue() ) return;
type = JSONType.Boolean;
this.value = ""+value;
}
/**
* Sets the value of the node, but only if it is setup as an JSONType.Value
*/
public void set(String value){
if( !this.isValue() ) return;
type = JSONType.String;
this.value = value;
}
/**
* @return if this node contains an Map
*/
public boolean isMap(){
return type == JSONType.Map;
}
/**
* @return if this node contains an List
*/
public boolean isList(){
return type == JSONType.List;
}
/**
* @return if this node contains an value
*/
public boolean isValue(){
return type != JSONType.Map && type != JSONType.List;
}
/**
* @return the type of the node
*/
public JSONType getType(){
return type;
}
/**
* @return the String value in this node, null if its a Map or List
*/
public String getString(){
return value;
}
/**
* @return the boolean value in this node
*/
public boolean getBoolean(){
return Boolean.parseBoolean(value);
}
/**
* @return the integer value in this node
*/
public int getInt(){
return Integer.parseInt(value);
}
/**
* @return the double value in this node
*/
public double getDouble(){
return Double.parseDouble(value);
}
public String toString(){
if( this.isMap() )
return map.toString();
else if( this.isList() )
return list.toString();
return value;
}
}

View file

@ -0,0 +1,162 @@
package zutil.parser.json;
import zutil.MultiPrintStream;
import zutil.parser.json.JSONNode.JSONType;
public class JSONParser {
private String json;
private int index;
public static void main(String[] args){
JSONParser parser = new JSONParser("" +
"{"+
" \"firstName\": \"John\","+
" \"lastName\": \"Smith\","+
" \"age\": 25,"+
" \"address\": {"+
" \"streetAddress\": \"21 2nd Street\","+
" \"city\": \"New York\","+
" \"state\": \"NY\","+
" \"postalCode\": \"10021\""+
" },"+
" \"phoneNumber\": ["+
" { \"type\": \"home\", \"number\": \"212 555-1234\" },"+
" { \"type\": \"fax\", \"number\": \"646 555-4567\" }"+
" ]"+
"}");
JSONNode node = parser.read();
MultiPrintStream.out.dump( node );
JSONWriter writer = new JSONWriter(System.out);
writer.write(node);
}
public JSONParser(String json){
this.json = json;
}
public JSONNode read(){
index = 0;
return parse(new StringBuffer(json));
}
protected JSONNode parse(StringBuffer json){
JSONNode root = null;
JSONNode key = null;
JSONNode node = null;
int next_index;
while(Character.isWhitespace( json.charAt(0) ) ||
json.charAt(0) == ',' || json.charAt(0) == ':')
json.deleteCharAt(0);
char c = json.charAt(0);
json.deleteCharAt(0);
switch( c ){
case ']':
case '}':
return null;
case '{':
root = new JSONNode(JSONType.Map);
while((key = parse( json )) != null && (node = parse( json )) != null){
root.add( key.toString(), node );
}
break;
case '[':
root = new JSONNode(JSONType.List);
while((node = parse( json )) != null){
root.add( node );
}
break;
// Parse String
case '\"':
root = new JSONNode(JSONType.String);
next_index = json.indexOf("\"");
root.set( json.substring(0, next_index) );
json.delete(0, next_index+1);
break;
default:
root = new JSONNode(JSONType.Number);
for(next_index=0; next_index<json.length() ;++next_index)
if( json.charAt(next_index)==',' ||
json.charAt(next_index)==']' ||
json.charAt(next_index)=='}'){
break;
}
root.set( c+json.substring(0, next_index) );
json.delete(0, next_index);
break;
}
return root;
}
protected JSONNode parse2(){
System.out.println("Recursion");
JSONNode root = null;
for(; index<json.length() ;++index){
if(!Character.isWhitespace( json.charAt(index) ))
break;
}
// Parse Map
if( json.charAt(index)=='{' ){
++index;
System.out.println("Map:");
root = new JSONNode(JSONType.Map);
for(; index<json.length() ;++index){
if( json.charAt(index)=='}' ) break;
if( Character.isWhitespace( json.charAt(index) ))
continue;
int next = json.indexOf(":", index+1);
String key = json.substring(index, next);
index = next+1;
System.out.println("New Map element: "+key);
root.add( key, parse2() );
}
++index;
}
// Parse List
else if( json.charAt(index)=='[' ){
++index;
System.out.println("List");
root = new JSONNode(JSONType.List);
for(; index<json.length() ;++index){
if( json.charAt(index)==']' ) break;
if( Character.isWhitespace( json.charAt(index) ))
continue;
System.out.println("New List: ");
root.add( parse2() );
}
++index;
}
// Parse String
else if( json.charAt(index)=='\"' ){
++index;
int next = json.indexOf("\"", index);
root = new JSONNode(JSONType.String);
root.set( json.substring(index, next) );
System.out.println("String: "+root);
index = next;
}
// Parse Number or Boolean
else{
System.out.println("Number");
int next = index;
for(; next<json.length() ;++next)
if( json.charAt(next)==',' ||
json.charAt(next)==']' ||
json.charAt(next)=='}'){
break;
}
root = new JSONNode(JSONType.Number);
root.set( json.substring(index, next).trim() );
System.out.println("Number: "+root);
index = next;
}
System.out.println("Return");
return root;
}
}

View file

@ -0,0 +1,86 @@
package zutil.parser.json;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Iterator;
import zutil.parser.json.JSONNode.JSONType;
/**
* Writes An JSONNode to an String or stream
*
* @author Ziver
*/
public class JSONWriter {
private PrintStream out;
/**
* Creates a new instance of the writer
*
* @param out the OutputStream that the Nodes will be sent to
*/
public JSONWriter(OutputStream out){
this.out = new PrintStream(out);
}
/**
* Writes the specified node to the stream
*
* @param root is the root node
*/
public void write(JSONNode root){
boolean first = true;
switch(root.getType()){
// Write Map
case Map:
out.print('{');
Iterator<String> it = root.keyIterator();
while(it.hasNext()){
if(!first)
out.print(", ");
String key = it.next();
try{
out.print( Integer.parseInt(key) );
}catch(Exception e){
out.print('\"');
out.print(key);
out.print('\"');
}
out.print(": ");
write( root.get(key) );
first = false;
}
out.print('}');
break;
// Write an list
case List:
out.print('[');
for(JSONNode node : root){
if(!first)
out.print(", ");
write( node );
first = false;
}
out.print(']');
break;
default:
if(root.getType() == JSONType.String){
out.print('\"');
out.print(root.toString());
out.print('\"');
} else
out.print(root.toString());
break;
}
out.flush();
}
/**
* Closes the internal stream
*/
public void close(){
out.close();
}
}