From dec4a7827e9048d1f52d9e2c0e484ea51a4d527e Mon Sep 17 00:00:00 2001 From: AKASH V Date: Tue, 3 May 2016 17:20:42 +0530 Subject: [PATCH 01/10] initaial commit --- pom.xml | 14 +- .../sonar/org/json/simple/ItemList.java | 147 ++++ .../sonar/org/json/simple/JSONArray.java | 381 ++++++++++ .../sonar/org/json/simple/JSONAware.java | 12 + .../sonar/org/json/simple/JSONObject.java | 132 ++++ .../org/json/simple/JSONStreamAware.java | 15 + .../sonar/org/json/simple/JSONValue.java | 315 ++++++++ .../json/simple/parser/ContainerFactory.java | 23 + .../json/simple/parser/ContentHandler.java | 110 +++ .../org/json/simple/parser/JSONParser.java | 533 ++++++++++++++ .../json/simple/parser/ParseException.java | 90 +++ .../sonar/org/json/simple/parser/Yylex.java | 688 ++++++++++++++++++ .../sonar/org/json/simple/parser/Yytoken.java | 58 ++ .../com/godaddy/sonar/ruby/RubyPlugin.java | 10 +- .../com/godaddy/sonar/ruby/RubySensor.java | 1 - .../metricfu/MetricfuComplexitySensor.java | 7 +- .../MetricfuComplexityYamlParserImpl.java | 8 +- .../metricfu/MetricfuDuplicationSensor.java | 76 ++ .../MetricfuDuplicationYamlParser.java | 17 + .../MetricfuDuplicationYamlParserImpl.java | 77 ++ .../ruby/rules/MetricfuRoodiYamlParser.java | 15 + .../rules/MetricfuRoodiYamlParserImpl.java | 57 ++ .../sonar/ruby/rules/RoodiProblem.java | 25 + .../godaddy/sonar/ruby/rules/RoodiRule.java | 15 + .../sonar/ruby/rules/RoodiRuleParser.java | 81 +++ .../godaddy/sonar/ruby/rules/RoodiSensor.java | 109 +++ .../sonar/ruby/rules/RubyRuleRepository.java | 43 ++ .../SimpleCovRcovJsonParserImpl.java | 16 +- .../simplecovrcov/SimpleCovRcovSensor.java | 3 +- .../com/godaddy/sonar/ruby/rules/rules.yml | 66 ++ 30 files changed, 3119 insertions(+), 25 deletions(-) create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/ItemList.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONArray.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONAware.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONObject.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONStreamAware.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONValue.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/ContainerFactory.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/ContentHandler.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/JSONParser.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/ParseException.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/Yylex.java create mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/Yytoken.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationSensor.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationYamlParser.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationYamlParserImpl.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParser.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParserImpl.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/rules/RoodiProblem.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/rules/RoodiRule.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/rules/RoodiRuleParser.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/rules/RoodiSensor.java create mode 100644 src/main/java/com/godaddy/sonar/ruby/rules/RubyRuleRepository.java create mode 100644 src/main/resources/com/godaddy/sonar/ruby/rules/rules.yml diff --git a/pom.xml b/pom.xml index 8d368d6..2378926 100755 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ UTF-8 - 4.5.2 + 5.0.1 1.6 0.7.4.201502262128 @@ -35,7 +35,6 @@ sonar-batch ${sonar.buildVersion} - org.codehaus.sonar @@ -55,12 +54,6 @@ 3.3.1 test - - com.googlecode.json-simple - json-simple - 1.1.1 - - org.easytesting fest-assert @@ -83,7 +76,6 @@ commons-configuration 1.9 - @@ -91,7 +83,7 @@ org.codehaus.sonar sonar-packaging-maven-plugin - 1.7 + 1.8 true com.godaddy.sonar.ruby.RubyPlugin @@ -201,7 +193,7 @@ - + f diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/ItemList.java b/src/main/java/com/godaddy/sonar/org/json/simple/ItemList.java new file mode 100644 index 0000000..7485ef7 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/ItemList.java @@ -0,0 +1,147 @@ +/* + * $Id: ItemList.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-3-24 + */ +package com.godaddy.sonar.org.json.simple; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +/** + * |a:b:c| => |a|,|b|,|c| + * |:| => ||,|| + * |a:| => |a|,|| + * @author FangYidong + */ +public class ItemList { + private String sp=","; + List items=new ArrayList(); + + + public ItemList(){} + + + public ItemList(String s){ + this.split(s,sp,items); + } + + public ItemList(String s,String sp){ + this.sp=s; + this.split(s,sp,items); + } + + public ItemList(String s,String sp,boolean isMultiToken){ + split(s,sp,items,isMultiToken); + } + + public List getItems(){ + return this.items; + } + + public String[] getArray(){ + return (String[])this.items.toArray(); + } + + public void split(String s,String sp,List append,boolean isMultiToken){ + if(s==null || sp==null) + return; + if(isMultiToken){ + StringTokenizer tokens=new StringTokenizer(s,sp); + while(tokens.hasMoreTokens()){ + append.add(tokens.nextToken().trim()); + } + } + else{ + this.split(s,sp,append); + } + } + + public void split(String s,String sp,List append){ + if(s==null || sp==null) + return; + int pos=0; + int prevPos=0; + do{ + prevPos=pos; + pos=s.indexOf(sp,pos); + if(pos==-1) + break; + append.add(s.substring(prevPos,pos).trim()); + pos+=sp.length(); + }while(pos!=-1); + append.add(s.substring(prevPos).trim()); + } + + public void setSP(String sp){ + this.sp=sp; + } + + public void add(int i,String item){ + if(item==null) + return; + items.add(i,item.trim()); + } + + public void add(String item){ + if(item==null) + return; + items.add(item.trim()); + } + + public void addAll(ItemList list){ + items.addAll(list.items); + } + + public void addAll(String s){ + this.split(s,sp,items); + } + + public void addAll(String s,String sp){ + this.split(s,sp,items); + } + + public void addAll(String s,String sp,boolean isMultiToken){ + this.split(s,sp,items,isMultiToken); + } + + /** + * @param i 0-based + * @return + */ + public String get(int i){ + return (String)items.get(i); + } + + public int size(){ + return items.size(); + } + + public String toString(){ + return toString(sp); + } + + public String toString(String sp){ + StringBuffer sb=new StringBuffer(); + + for(int i=0;i + */ +public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware { + private static final long serialVersionUID = 3957988303675231981L; + + /** + * Constructs an empty JSONArray. + */ + public JSONArray(){ + super(); + } + + /** + * Constructs a JSONArray containing the elements of the specified + * collection, in the order they are returned by the collection's iterator. + * + * @param c the collection whose elements are to be placed into this JSONArray + */ + public JSONArray(Collection c){ + super(c); + } + + /** + * Encode a list into JSON text and write it to out. + * If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level. + * + * @see org.json.simple.JSONValue#writeJSONString(Object, Writer) + * + * @param collection + * @param out + */ + public static void writeJSONString(Collection collection, Writer out) throws IOException{ + if(collection == null){ + out.write("null"); + return; + } + + boolean first = true; + Iterator iter=collection.iterator(); + + out.write('['); + while(iter.hasNext()){ + if(first) + first = false; + else + out.write(','); + + Object value=iter.next(); + if(value == null){ + out.write("null"); + continue; + } + + JSONValue.writeJSONString(value, out); + } + out.write(']'); + } + + public void writeJSONString(Writer out) throws IOException{ + writeJSONString(this, out); + } + + /** + * Convert a list to JSON text. The result is a JSON array. + * If this list is also a JSONAware, JSONAware specific behaviours will be omitted at this top level. + * + * @see org.json.simple.JSONValue#toJSONString(Object) + * + * @param collection + * @return JSON text, or "null" if list is null. + */ + public static String toJSONString(Collection collection){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(collection, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(byte[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("["); + out.write(String.valueOf(array[0])); + + for(int i = 1; i < array.length; i++){ + out.write(","); + out.write(String.valueOf(array[i])); + } + + out.write("]"); + } + } + + public static String toJSONString(byte[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(short[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("["); + out.write(String.valueOf(array[0])); + + for(int i = 1; i < array.length; i++){ + out.write(","); + out.write(String.valueOf(array[i])); + } + + out.write("]"); + } + } + + public static String toJSONString(short[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(int[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("["); + out.write(String.valueOf(array[0])); + + for(int i = 1; i < array.length; i++){ + out.write(","); + out.write(String.valueOf(array[i])); + } + + out.write("]"); + } + } + + public static String toJSONString(int[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(long[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("["); + out.write(String.valueOf(array[0])); + + for(int i = 1; i < array.length; i++){ + out.write(","); + out.write(String.valueOf(array[i])); + } + + out.write("]"); + } + } + + public static String toJSONString(long[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(float[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("["); + out.write(String.valueOf(array[0])); + + for(int i = 1; i < array.length; i++){ + out.write(","); + out.write(String.valueOf(array[i])); + } + + out.write("]"); + } + } + + public static String toJSONString(float[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(double[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("["); + out.write(String.valueOf(array[0])); + + for(int i = 1; i < array.length; i++){ + out.write(","); + out.write(String.valueOf(array[i])); + } + + out.write("]"); + } + } + + public static String toJSONString(double[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(boolean[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("["); + out.write(String.valueOf(array[0])); + + for(int i = 1; i < array.length; i++){ + out.write(","); + out.write(String.valueOf(array[i])); + } + + out.write("]"); + } + } + + public static String toJSONString(boolean[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(char[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("[\""); + out.write(String.valueOf(array[0])); + + for(int i = 1; i < array.length; i++){ + out.write("\",\""); + out.write(String.valueOf(array[i])); + } + + out.write("\"]"); + } + } + + public static String toJSONString(char[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public static void writeJSONString(Object[] array, Writer out) throws IOException{ + if(array == null){ + out.write("null"); + } else if(array.length == 0) { + out.write("[]"); + } else { + out.write("["); + JSONValue.writeJSONString(array[0], out); + + for(int i = 1; i < array.length; i++){ + out.write(","); + JSONValue.writeJSONString(array[i], out); + } + + out.write("]"); + } + } + + public static String toJSONString(Object[] array){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(array, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + public String toJSONString(){ + return toJSONString(this); + } + + /** + * Returns a string representation of this array. This is equivalent to + * calling {@link JSONArray#toJSONString()}. + */ + public String toString() { + return toJSONString(); + } +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/JSONAware.java b/src/main/java/com/godaddy/sonar/org/json/simple/JSONAware.java new file mode 100644 index 0000000..9a648d3 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/JSONAware.java @@ -0,0 +1,12 @@ +package com.godaddy.sonar.org.json.simple; + +/** + * Beans that support customized output of JSON text shall implement this interface. + * @author FangYidong + */ +public interface JSONAware { + /** + * @return JSON text + */ + String toJSONString(); +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/JSONObject.java b/src/main/java/com/godaddy/sonar/org/json/simple/JSONObject.java new file mode 100644 index 0000000..d3f09c7 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/JSONObject.java @@ -0,0 +1,132 @@ +/* + * $Id: JSONObject.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-4-10 + */ +package com.godaddy.sonar.org.json.simple; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface. + * + * @author FangYidong + */ +public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware{ + + private static final long serialVersionUID = -503443796854799292L; + + + public JSONObject() { + super(); + } + + /** + * Allows creation of a JSONObject from a Map. After that, both the + * generated JSONObject and the Map can be modified independently. + * + * @param map + */ + public JSONObject(Map map) { + super(map); + } + + + /** + * Encode a map into JSON text and write it to out. + * If this map is also a JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific behaviours will be ignored at this top level. + * + * @see org.json.simple.JSONValue#writeJSONString(Object, Writer) + * + * @param map + * @param out + */ + public static void writeJSONString(Map map, Writer out) throws IOException { + if(map == null){ + out.write("null"); + return; + } + + boolean first = true; + Iterator iter=map.entrySet().iterator(); + + out.write('{'); + while(iter.hasNext()){ + if(first) + first = false; + else + out.write(','); + Map.Entry entry=(Map.Entry)iter.next(); + out.write('\"'); + out.write(escape(String.valueOf(entry.getKey()))); + out.write('\"'); + out.write(':'); + JSONValue.writeJSONString(entry.getValue(), out); + } + out.write('}'); + } + + public void writeJSONString(Writer out) throws IOException{ + writeJSONString(this, out); + } + + /** + * Convert a map to JSON text. The result is a JSON object. + * If this map is also a JSONAware, JSONAware specific behaviours will be omitted at this top level. + * + * @see org.json.simple.JSONValue#toJSONString(Object) + * + * @param map + * @return JSON text, or "null" if map is null. + */ + public static String toJSONString(Map map){ + final StringWriter writer = new StringWriter(); + + try { + writeJSONString(map, writer); + return writer.toString(); + } catch (IOException e) { + // This should never happen with a StringWriter + throw new RuntimeException(e); + } + } + + public String toJSONString(){ + return toJSONString(this); + } + + public String toString(){ + return toJSONString(); + } + + public static String toString(String key,Object value){ + StringBuffer sb = new StringBuffer(); + sb.append('\"'); + if(key == null) + sb.append("null"); + else + JSONValue.escape(key, sb); + sb.append('\"').append(':'); + + sb.append(JSONValue.toJSONString(value)); + + return sb.toString(); + } + + /** + * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). + * It's the same as JSONValue.escape() only for compatibility here. + * + * @see org.json.simple.JSONValue#escape(String) + * + * @param s + * @return + */ + public static String escape(String s){ + return JSONValue.escape(s); + } +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/JSONStreamAware.java b/src/main/java/com/godaddy/sonar/org/json/simple/JSONStreamAware.java new file mode 100644 index 0000000..24cf3f8 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/JSONStreamAware.java @@ -0,0 +1,15 @@ +package com.godaddy.sonar.org.json.simple; + +import java.io.IOException; +import java.io.Writer; + +/** + * Beans that support customized output of JSON text to a writer shall implement this interface. + * @author FangYidong + */ +public interface JSONStreamAware { + /** + * write JSON string to out. + */ + void writeJSONString(Writer out) throws IOException; +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/JSONValue.java b/src/main/java/com/godaddy/sonar/org/json/simple/JSONValue.java new file mode 100644 index 0000000..c34aa70 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/JSONValue.java @@ -0,0 +1,315 @@ +/* + * $Id: JSONValue.java,v 1.1 2006/04/15 14:37:04 platform Exp $ + * Created on 2006-4-15 + */ +package com.godaddy.sonar.org.json.simple; + +import com.godaddy.sonar.org.json.simple.parser.JSONParser; +import com.godaddy.sonar.org.json.simple.parser.ParseException; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Collection; +// import java.util.List; +import java.util.Map; + +/** + * @author FangYidong + */ +public class JSONValue { + /** + * Parse JSON text into java object from the input source. + * Please use parseWithException() if you don't want to ignore the exception. + * + * @see org.json.simple.parser.JSONParser#parse(Reader) + * @see #parseWithException(Reader) + * + * @param in + * @return Instance of the following: + * org.json.simple.JSONObject, + * org.json.simple.JSONArray, + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean, + * null + * + * @deprecated this method may throw an {@code Error} instead of returning + * {@code null}; please use {@link JSONValue#parseWithException(Reader)} + * instead + */ + public static Object parse(Reader in){ + try{ + JSONParser parser=new JSONParser(); + return parser.parse(in); + } + catch(Exception e){ + return null; + } + } + + /** + * Parse JSON text into java object from the given string. + * Please use parseWithException() if you don't want to ignore the exception. + * + * @see org.json.simple.parser.JSONParser#parse(Reader) + * @see #parseWithException(Reader) + * + * @param s + * @return Instance of the following: + * org.json.simple.JSONObject, + * org.json.simple.JSONArray, + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean, + * null + * + * @deprecated this method may throw an {@code Error} instead of returning + * {@code null}; please use {@link JSONValue#parseWithException(String)} + * instead + */ + public static Object parse(String s){ + StringReader in=new StringReader(s); + return parse(in); + } + + /** + * Parse JSON text into java object from the input source. + * + * @see org.json.simple.parser.JSONParser + * + * @param in + * @return Instance of the following: + * org.json.simple.JSONObject, + * org.json.simple.JSONArray, + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean, + * null + * + * @throws IOException + * @throws ParseException + */ + public static Object parseWithException(Reader in) throws IOException, ParseException{ + JSONParser parser=new JSONParser(); + return parser.parse(in); + } + + public static Object parseWithException(String s) throws ParseException { + JSONParser parser=new JSONParser(); + return parser.parse(s); + } + + /** + * Encode an object into JSON text and write it to out. + *

+ * If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly. + *

+ * DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with + * "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead. + * + * @see org.json.simple.JSONObject#writeJSONString(Map, Writer) + * @see org.json.simple.JSONArray#writeJSONString(List, Writer) + * + * @param value + * @param writer + */ + public static void writeJSONString(Object value, Writer out) throws IOException { + if(value == null){ + out.write("null"); + return; + } + + if(value instanceof String){ + out.write('\"'); + out.write(escape((String)value)); + out.write('\"'); + return; + } + + if(value instanceof Double){ + if(((Double)value).isInfinite() || ((Double)value).isNaN()) + out.write("null"); + else + out.write(value.toString()); + return; + } + + if(value instanceof Float){ + if(((Float)value).isInfinite() || ((Float)value).isNaN()) + out.write("null"); + else + out.write(value.toString()); + return; + } + + if(value instanceof Number){ + out.write(value.toString()); + return; + } + + if(value instanceof Boolean){ + out.write(value.toString()); + return; + } + + if((value instanceof JSONStreamAware)){ + ((JSONStreamAware)value).writeJSONString(out); + return; + } + + if((value instanceof JSONAware)){ + out.write(((JSONAware)value).toJSONString()); + return; + } + + if(value instanceof Map){ + JSONObject.writeJSONString((Map)value, out); + return; + } + + if(value instanceof Collection){ + JSONArray.writeJSONString((Collection)value, out); + return; + } + + if(value instanceof byte[]){ + JSONArray.writeJSONString((byte[])value, out); + return; + } + + if(value instanceof short[]){ + JSONArray.writeJSONString((short[])value, out); + return; + } + + if(value instanceof int[]){ + JSONArray.writeJSONString((int[])value, out); + return; + } + + if(value instanceof long[]){ + JSONArray.writeJSONString((long[])value, out); + return; + } + + if(value instanceof float[]){ + JSONArray.writeJSONString((float[])value, out); + return; + } + + if(value instanceof double[]){ + JSONArray.writeJSONString((double[])value, out); + return; + } + + if(value instanceof boolean[]){ + JSONArray.writeJSONString((boolean[])value, out); + return; + } + + if(value instanceof char[]){ + JSONArray.writeJSONString((char[])value, out); + return; + } + + if(value instanceof Object[]){ + JSONArray.writeJSONString((Object[])value, out); + return; + } + + out.write(value.toString()); + } + + /** + * Convert an object to JSON text. + *

+ * If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly. + *

+ * DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with + * "this" as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead. + * + * @see org.json.simple.JSONObject#toJSONString(Map) + * @see org.json.simple.JSONArray#toJSONString(List) + * + * @param value + * @return JSON text, or "null" if value is null or it's an NaN or an INF number. + */ + public static String toJSONString(Object value){ + final StringWriter writer = new StringWriter(); + + try{ + writeJSONString(value, writer); + return writer.toString(); + } catch(IOException e){ + // This should never happen for a StringWriter + throw new RuntimeException(e); + } + } + + /** + * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). + * @param s + * @return + */ + public static String escape(String s){ + if(s==null) + return null; + StringBuffer sb = new StringBuffer(); + escape(s, sb); + return sb.toString(); + } + + /** + * @param s - Must not be null. + * @param sb + */ + static void escape(String s, StringBuffer sb) { + final int len = s.length(); + for(int i=0;i='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')){ + String ss=Integer.toHexString(ch); + sb.append("\\u"); + for(int k=0;k<4-ss.length();k++){ + sb.append('0'); + } + sb.append(ss.toUpperCase()); + } + else{ + sb.append(ch); + } + } + }//for + } + +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContainerFactory.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContainerFactory.java new file mode 100644 index 0000000..667bd28 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContainerFactory.java @@ -0,0 +1,23 @@ +package com.godaddy.sonar.org.json.simple.parser; + +import java.util.List; +import java.util.Map; + +/** + * Container factory for creating containers for JSON object and JSON array. + * + * @see org.json.simple.parser.JSONParser#parse(java.io.Reader, ContainerFactory) + * + * @author FangYidong + */ +public interface ContainerFactory { + /** + * @return A Map instance to store JSON object, or null if you want to use org.json.simple.JSONObject. + */ + Map createObjectContainer(); + + /** + * @return A List instance to store JSON array, or null if you want to use org.json.simple.JSONArray. + */ + List creatArrayContainer(); +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContentHandler.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContentHandler.java new file mode 100644 index 0000000..619300d --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContentHandler.java @@ -0,0 +1,110 @@ +package com.godaddy.sonar.org.json.simple.parser; + +import java.io.IOException; + +/** + * A simplified and stoppable SAX-like content handler for stream processing of JSON text. + * + * @see org.xml.sax.ContentHandler + * @see org.json.simple.parser.JSONParser#parse(java.io.Reader, ContentHandler, boolean) + * + * @author FangYidong + */ +public interface ContentHandler { + /** + * Receive notification of the beginning of JSON processing. + * The parser will invoke this method only once. + * + * @throws ParseException + * - JSONParser will stop and throw the same exception to the caller when receiving this exception. + */ + void startJSON() throws ParseException, IOException; + + /** + * Receive notification of the end of JSON processing. + * + * @throws ParseException + */ + void endJSON() throws ParseException, IOException; + + /** + * Receive notification of the beginning of a JSON object. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * - JSONParser will stop and throw the same exception to the caller when receiving this exception. + * @see #endJSON + */ + boolean startObject() throws ParseException, IOException; + + /** + * Receive notification of the end of a JSON object. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #startObject + */ + boolean endObject() throws ParseException, IOException; + + /** + * Receive notification of the beginning of a JSON object entry. + * + * @param key - Key of a JSON object entry. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #endObjectEntry + */ + boolean startObjectEntry(String key) throws ParseException, IOException; + + /** + * Receive notification of the end of the value of previous object entry. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #startObjectEntry + */ + boolean endObjectEntry() throws ParseException, IOException; + + /** + * Receive notification of the beginning of a JSON array. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #endArray + */ + boolean startArray() throws ParseException, IOException; + + /** + * Receive notification of the end of a JSON array. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #startArray + */ + boolean endArray() throws ParseException, IOException; + + /** + * Receive notification of the JSON primitive values: + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean + * null + * + * @param value - Instance of the following: + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean + * null + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + */ + boolean primitive(Object value) throws ParseException, IOException; + +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/JSONParser.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/JSONParser.java new file mode 100644 index 0000000..c91a907 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/parser/JSONParser.java @@ -0,0 +1,533 @@ +/* + * $Id: JSONParser.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-4-15 + */ +package com.godaddy.sonar.org.json.simple.parser; + +import com.godaddy.sonar.org.json.simple.JSONArray; +import com.godaddy.sonar.org.json.simple.JSONObject; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + + +/** + * Parser for JSON text. Please note that JSONParser is NOT thread-safe. + * + * @author FangYidong + */ +public class JSONParser { + public static final int S_INIT=0; + public static final int S_IN_FINISHED_VALUE=1;//string,number,boolean,null,object,array + public static final int S_IN_OBJECT=2; + public static final int S_IN_ARRAY=3; + public static final int S_PASSED_PAIR_KEY=4; + public static final int S_IN_PAIR_VALUE=5; + public static final int S_END=6; + public static final int S_IN_ERROR=-1; + + private LinkedList handlerStatusStack; + private Yylex lexer = new Yylex((Reader)null); + private Yytoken token = null; + private int status = S_INIT; + + private int peekStatus(LinkedList statusStack){ + if(statusStack.size()==0) + return -1; + Integer status=(Integer)statusStack.getFirst(); + return status.intValue(); + } + + /** + * Reset the parser to the initial state without resetting the underlying reader. + * + */ + public void reset(){ + token = null; + status = S_INIT; + handlerStatusStack = null; + } + + /** + * Reset the parser to the initial state with a new character reader. + * + * @param in - The new character reader. + * @throws IOException + * @throws ParseException + */ + public void reset(Reader in){ + lexer.yyreset(in); + reset(); + } + + /** + * @return The position of the beginning of the current token. + */ + public int getPosition(){ + return lexer.getPosition(); + } + + public Object parse(String s) throws ParseException{ + return parse(s, (ContainerFactory)null); + } + + public Object parse(String s, ContainerFactory containerFactory) throws ParseException{ + StringReader in=new StringReader(s); + try{ + return parse(in, containerFactory); + } + catch(IOException ie){ + /* + * Actually it will never happen. + */ + throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie); + } + } + + public Object parse(Reader in) throws IOException, ParseException{ + return parse(in, (ContainerFactory)null); + } + + /** + * Parse JSON text into java object from the input source. + * + * @param in + * @param containerFactory - Use this factory to createyour own JSON object and JSON array containers. + * @return Instance of the following: + * org.json.simple.JSONObject, + * org.json.simple.JSONArray, + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean, + * null + * + * @throws IOException + * @throws ParseException + */ + public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException{ + reset(in); + LinkedList statusStack = new LinkedList(); + LinkedList valueStack = new LinkedList(); + + try{ + do{ + nextToken(); + switch(status){ + case S_INIT: + switch(token.type){ + case Yytoken.TYPE_VALUE: + status=S_IN_FINISHED_VALUE; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(token.value); + break; + case Yytoken.TYPE_LEFT_BRACE: + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(createObjectContainer(containerFactory)); + break; + case Yytoken.TYPE_LEFT_SQUARE: + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(createArrayContainer(containerFactory)); + break; + default: + status=S_IN_ERROR; + }//inner switch + break; + + case S_IN_FINISHED_VALUE: + if(token.type==Yytoken.TYPE_EOF) + return valueStack.removeFirst(); + else + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + + case S_IN_OBJECT: + switch(token.type){ + case Yytoken.TYPE_COMMA: + break; + case Yytoken.TYPE_VALUE: + if(token.value instanceof String){ + String key=(String)token.value; + valueStack.addFirst(key); + status=S_PASSED_PAIR_KEY; + statusStack.addFirst(new Integer(status)); + } + else{ + status=S_IN_ERROR; + } + break; + case Yytoken.TYPE_RIGHT_BRACE: + if(valueStack.size()>1){ + statusStack.removeFirst(); + valueStack.removeFirst(); + status=peekStatus(statusStack); + } + else{ + status=S_IN_FINISHED_VALUE; + } + break; + default: + status=S_IN_ERROR; + break; + }//inner switch + break; + + case S_PASSED_PAIR_KEY: + switch(token.type){ + case Yytoken.TYPE_COLON: + break; + case Yytoken.TYPE_VALUE: + statusStack.removeFirst(); + String key=(String)valueStack.removeFirst(); + Map parent=(Map)valueStack.getFirst(); + parent.put(key,token.value); + status=peekStatus(statusStack); + break; + case Yytoken.TYPE_LEFT_SQUARE: + statusStack.removeFirst(); + key=(String)valueStack.removeFirst(); + parent=(Map)valueStack.getFirst(); + List newArray=createArrayContainer(containerFactory); + parent.put(key,newArray); + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(newArray); + break; + case Yytoken.TYPE_LEFT_BRACE: + statusStack.removeFirst(); + key=(String)valueStack.removeFirst(); + parent=(Map)valueStack.getFirst(); + Map newObject=createObjectContainer(containerFactory); + parent.put(key,newObject); + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(newObject); + break; + default: + status=S_IN_ERROR; + } + break; + + case S_IN_ARRAY: + switch(token.type){ + case Yytoken.TYPE_COMMA: + break; + case Yytoken.TYPE_VALUE: + List val=(List)valueStack.getFirst(); + val.add(token.value); + break; + case Yytoken.TYPE_RIGHT_SQUARE: + if(valueStack.size()>1){ + statusStack.removeFirst(); + valueStack.removeFirst(); + status=peekStatus(statusStack); + } + else{ + status=S_IN_FINISHED_VALUE; + } + break; + case Yytoken.TYPE_LEFT_BRACE: + val=(List)valueStack.getFirst(); + Map newObject=createObjectContainer(containerFactory); + val.add(newObject); + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(newObject); + break; + case Yytoken.TYPE_LEFT_SQUARE: + val=(List)valueStack.getFirst(); + List newArray=createArrayContainer(containerFactory); + val.add(newArray); + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(newArray); + break; + default: + status=S_IN_ERROR; + }//inner switch + break; + case S_IN_ERROR: + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + }//switch + if(status==S_IN_ERROR){ + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } + }while(token.type!=Yytoken.TYPE_EOF); + } + catch(IOException ie){ + throw ie; + } + + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } + + private void nextToken() throws ParseException, IOException{ + token = lexer.yylex(); + if(token == null) + token = new Yytoken(Yytoken.TYPE_EOF, null); + } + + private Map createObjectContainer(ContainerFactory containerFactory){ + if(containerFactory == null) + return new JSONObject(); + Map m = containerFactory.createObjectContainer(); + + if(m == null) + return new JSONObject(); + return m; + } + + private List createArrayContainer(ContainerFactory containerFactory){ + if(containerFactory == null) + return new JSONArray(); + List l = containerFactory.creatArrayContainer(); + + if(l == null) + return new JSONArray(); + return l; + } + + public void parse(String s, ContentHandler contentHandler) throws ParseException{ + parse(s, contentHandler, false); + } + + public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException{ + StringReader in=new StringReader(s); + try{ + parse(in, contentHandler, isResume); + } + catch(IOException ie){ + /* + * Actually it will never happen. + */ + throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie); + } + } + + public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException{ + parse(in, contentHandler, false); + } + + /** + * Stream processing of JSON text. + * + * @see ContentHandler + * + * @param in + * @param contentHandler + * @param isResume - Indicates if it continues previous parsing operation. + * If set to true, resume parsing the old stream, and parameter 'in' will be ignored. + * If this method is called for the first time in this instance, isResume will be ignored. + * + * @throws IOException + * @throws ParseException + */ + public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException{ + if(!isResume){ + reset(in); + handlerStatusStack = new LinkedList(); + } + else{ + if(handlerStatusStack == null){ + isResume = false; + reset(in); + handlerStatusStack = new LinkedList(); + } + } + + LinkedList statusStack = handlerStatusStack; + + try{ + do{ + switch(status){ + case S_INIT: + contentHandler.startJSON(); + nextToken(); + switch(token.type){ + case Yytoken.TYPE_VALUE: + status=S_IN_FINISHED_VALUE; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.primitive(token.value)) + return; + break; + case Yytoken.TYPE_LEFT_BRACE: + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startObject()) + return; + break; + case Yytoken.TYPE_LEFT_SQUARE: + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startArray()) + return; + break; + default: + status=S_IN_ERROR; + }//inner switch + break; + + case S_IN_FINISHED_VALUE: + nextToken(); + if(token.type==Yytoken.TYPE_EOF){ + contentHandler.endJSON(); + status = S_END; + return; + } + else{ + status = S_IN_ERROR; + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } + + case S_IN_OBJECT: + nextToken(); + switch(token.type){ + case Yytoken.TYPE_COMMA: + break; + case Yytoken.TYPE_VALUE: + if(token.value instanceof String){ + String key=(String)token.value; + status=S_PASSED_PAIR_KEY; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startObjectEntry(key)) + return; + } + else{ + status=S_IN_ERROR; + } + break; + case Yytoken.TYPE_RIGHT_BRACE: + if(statusStack.size()>1){ + statusStack.removeFirst(); + status=peekStatus(statusStack); + } + else{ + status=S_IN_FINISHED_VALUE; + } + if(!contentHandler.endObject()) + return; + break; + default: + status=S_IN_ERROR; + break; + }//inner switch + break; + + case S_PASSED_PAIR_KEY: + nextToken(); + switch(token.type){ + case Yytoken.TYPE_COLON: + break; + case Yytoken.TYPE_VALUE: + statusStack.removeFirst(); + status=peekStatus(statusStack); + if(!contentHandler.primitive(token.value)) + return; + if(!contentHandler.endObjectEntry()) + return; + break; + case Yytoken.TYPE_LEFT_SQUARE: + statusStack.removeFirst(); + statusStack.addFirst(new Integer(S_IN_PAIR_VALUE)); + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startArray()) + return; + break; + case Yytoken.TYPE_LEFT_BRACE: + statusStack.removeFirst(); + statusStack.addFirst(new Integer(S_IN_PAIR_VALUE)); + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startObject()) + return; + break; + default: + status=S_IN_ERROR; + } + break; + + case S_IN_PAIR_VALUE: + /* + * S_IN_PAIR_VALUE is just a marker to indicate the end of an object entry, it doesn't proccess any token, + * therefore delay consuming token until next round. + */ + statusStack.removeFirst(); + status = peekStatus(statusStack); + if(!contentHandler.endObjectEntry()) + return; + break; + + case S_IN_ARRAY: + nextToken(); + switch(token.type){ + case Yytoken.TYPE_COMMA: + break; + case Yytoken.TYPE_VALUE: + if(!contentHandler.primitive(token.value)) + return; + break; + case Yytoken.TYPE_RIGHT_SQUARE: + if(statusStack.size()>1){ + statusStack.removeFirst(); + status=peekStatus(statusStack); + } + else{ + status=S_IN_FINISHED_VALUE; + } + if(!contentHandler.endArray()) + return; + break; + case Yytoken.TYPE_LEFT_BRACE: + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startObject()) + return; + break; + case Yytoken.TYPE_LEFT_SQUARE: + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startArray()) + return; + break; + default: + status=S_IN_ERROR; + }//inner switch + break; + + case S_END: + return; + + case S_IN_ERROR: + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + }//switch + if(status==S_IN_ERROR){ + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } + }while(token.type!=Yytoken.TYPE_EOF); + } + catch(IOException ie){ + status = S_IN_ERROR; + throw ie; + } + catch(ParseException pe){ + status = S_IN_ERROR; + throw pe; + } + catch(RuntimeException re){ + status = S_IN_ERROR; + throw re; + } + catch(Error e){ + status = S_IN_ERROR; + throw e; + } + + status = S_IN_ERROR; + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ParseException.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ParseException.java new file mode 100644 index 0000000..784a1f7 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ParseException.java @@ -0,0 +1,90 @@ +package com.godaddy.sonar.org.json.simple.parser; + +/** + * ParseException explains why and where the error occurs in source JSON text. + * + * @author FangYidong + * + */ +public class ParseException extends Exception { + private static final long serialVersionUID = -7880698968187728547L; + + public static final int ERROR_UNEXPECTED_CHAR = 0; + public static final int ERROR_UNEXPECTED_TOKEN = 1; + public static final int ERROR_UNEXPECTED_EXCEPTION = 2; + + private int errorType; + private Object unexpectedObject; + private int position; + + public ParseException(int errorType){ + this(-1, errorType, null); + } + + public ParseException(int errorType, Object unexpectedObject){ + this(-1, errorType, unexpectedObject); + } + + public ParseException(int position, int errorType, Object unexpectedObject){ + this.position = position; + this.errorType = errorType; + this.unexpectedObject = unexpectedObject; + } + + public int getErrorType() { + return errorType; + } + + public void setErrorType(int errorType) { + this.errorType = errorType; + } + + /** + * @see org.json.simple.parser.JSONParser#getPosition() + * + * @return The character position (starting with 0) of the input where the error occurs. + */ + public int getPosition() { + return position; + } + + public void setPosition(int position) { + this.position = position; + } + + /** + * @see org.json.simple.parser.Yytoken + * + * @return One of the following base on the value of errorType: + * ERROR_UNEXPECTED_CHAR java.lang.Character + * ERROR_UNEXPECTED_TOKEN org.json.simple.parser.Yytoken + * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception + */ + public Object getUnexpectedObject() { + return unexpectedObject; + } + + public void setUnexpectedObject(Object unexpectedObject) { + this.unexpectedObject = unexpectedObject; + } + + public String getMessage() { + StringBuffer sb = new StringBuffer(); + + switch(errorType){ + case ERROR_UNEXPECTED_CHAR: + sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append("."); + break; + case ERROR_UNEXPECTED_TOKEN: + sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append("."); + break; + case ERROR_UNEXPECTED_EXCEPTION: + sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject); + break; + default: + sb.append("Unkown error at position ").append(position).append("."); + break; + } + return sb.toString(); + } +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yylex.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yylex.java new file mode 100644 index 0000000..c9c463c --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yylex.java @@ -0,0 +1,688 @@ +/* The following code was generated by JFlex 1.4.2 */ + +package com.godaddy.sonar.org.json.simple.parser; + +class Yylex { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + public static final int STRING_BEGIN = 2; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0, 1, 1 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\7\1\7\2\0\1\7\22\0\1\7\1\0\1\11\10\0"+ + "\1\6\1\31\1\2\1\4\1\12\12\3\1\32\6\0\4\1\1\5"+ + "\1\1\24\0\1\27\1\10\1\30\3\0\1\22\1\13\2\1\1\21"+ + "\1\14\5\0\1\23\1\0\1\15\3\0\1\16\1\24\1\17\1\20"+ + "\5\0\1\25\1\0\1\26\uff82\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\2\0\2\1\1\2\1\3\1\4\3\1\1\5\1\6"+ + "\1\7\1\10\1\11\1\12\1\13\1\14\1\15\5\0"+ + "\1\14\1\16\1\17\1\20\1\21\1\22\1\23\1\24"+ + "\1\0\1\25\1\0\1\25\4\0\1\26\1\27\2\0"+ + "\1\30"; + + private static int [] zzUnpackAction() { + int [] result = new int[45]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\33\0\66\0\121\0\154\0\207\0\66\0\242"+ + "\0\275\0\330\0\66\0\66\0\66\0\66\0\66\0\66"+ + "\0\363\0\u010e\0\66\0\u0129\0\u0144\0\u015f\0\u017a\0\u0195"+ + "\0\66\0\66\0\66\0\66\0\66\0\66\0\66\0\66"+ + "\0\u01b0\0\u01cb\0\u01e6\0\u01e6\0\u0201\0\u021c\0\u0237\0\u0252"+ + "\0\66\0\66\0\u026d\0\u0288\0\66"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[45]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int ZZ_TRANS [] = { + 2, 2, 3, 4, 2, 2, 2, 5, 2, 6, + 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, + 2, 10, 11, 12, 13, 14, 15, 16, 16, 16, + 16, 16, 16, 16, 16, 17, 18, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 4, 19, 20, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 20, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 5, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 16, 16, 16, 16, 16, 16, 16, + 16, -1, -1, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + -1, -1, -1, -1, -1, -1, -1, -1, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 33, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 34, 35, -1, -1, + 34, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 37, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 38, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 39, -1, 39, -1, 39, -1, -1, + -1, -1, -1, 39, 39, -1, -1, -1, -1, 39, + 39, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 33, -1, 20, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 20, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 35, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 38, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 40, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 41, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 42, -1, 42, -1, 42, + -1, -1, -1, -1, -1, 42, 42, -1, -1, -1, + -1, 42, 42, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, + -1, -1, 43, 43, -1, -1, -1, -1, 43, 43, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, + -1, 44, -1, 44, -1, -1, -1, -1, -1, 44, + 44, -1, -1, -1, -1, 44, 44, -1, -1, -1, + -1, -1, -1, -1, -1, + }; + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\2\0\1\11\3\1\1\11\3\1\6\11\2\1\1\11"+ + "\5\0\10\11\1\0\1\1\1\0\1\1\4\0\2\11"+ + "\2\0\1\11"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[45]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /* user code: */ +private StringBuffer sb=new StringBuffer(); + +int getPosition(){ + return yychar; +} + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 90) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public Yytoken yylex() throws java.io.IOException, ParseException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 11: + { sb.append(yytext()); + } + case 25: break; + case 4: + { sb = null; sb = new StringBuffer(); yybegin(STRING_BEGIN); + } + case 26: break; + case 16: + { sb.append('\b'); + } + case 27: break; + case 6: + { return new Yytoken(Yytoken.TYPE_RIGHT_BRACE,null); + } + case 28: break; + case 23: + { Boolean val=Boolean.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); + } + case 29: break; + case 22: + { return new Yytoken(Yytoken.TYPE_VALUE, null); + } + case 30: break; + case 13: + { yybegin(YYINITIAL);return new Yytoken(Yytoken.TYPE_VALUE, sb.toString()); + } + case 31: break; + case 12: + { sb.append('\\'); + } + case 32: break; + case 21: + { Double val=Double.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); + } + case 33: break; + case 1: + { throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, new Character(yycharat(0))); + } + case 34: break; + case 8: + { return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE,null); + } + case 35: break; + case 19: + { sb.append('\r'); + } + case 36: break; + case 15: + { sb.append('/'); + } + case 37: break; + case 10: + { return new Yytoken(Yytoken.TYPE_COLON,null); + } + case 38: break; + case 14: + { sb.append('"'); + } + case 39: break; + case 5: + { return new Yytoken(Yytoken.TYPE_LEFT_BRACE,null); + } + case 40: break; + case 17: + { sb.append('\f'); + } + case 41: break; + case 24: + { try{ + int ch=Integer.parseInt(yytext().substring(2),16); + sb.append((char)ch); + } + catch(Exception e){ + throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e); + } + } + case 42: break; + case 20: + { sb.append('\t'); + } + case 43: break; + case 7: + { return new Yytoken(Yytoken.TYPE_LEFT_SQUARE,null); + } + case 44: break; + case 2: + { Long val=Long.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); + } + case 45: break; + case 18: + { sb.append('\n'); + } + case 46: break; + case 9: + { return new Yytoken(Yytoken.TYPE_COMMA,null); + } + case 47: break; + case 3: + { + } + case 48: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + return null; + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yytoken.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yytoken.java new file mode 100644 index 0000000..f703b32 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yytoken.java @@ -0,0 +1,58 @@ +/* + * $Id: Yytoken.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-4-15 + */ +package com.godaddy.sonar.org.json.simple.parser; + +/** + * @author FangYidong + */ +public class Yytoken { + public static final int TYPE_VALUE=0;//JSON primitive value: string,number,boolean,null + public static final int TYPE_LEFT_BRACE=1; + public static final int TYPE_RIGHT_BRACE=2; + public static final int TYPE_LEFT_SQUARE=3; + public static final int TYPE_RIGHT_SQUARE=4; + public static final int TYPE_COMMA=5; + public static final int TYPE_COLON=6; + public static final int TYPE_EOF=-1;//end of file + + public int type=0; + public Object value=null; + + public Yytoken(int type,Object value){ + this.type=type; + this.value=value; + } + + public String toString(){ + StringBuffer sb = new StringBuffer(); + switch(type){ + case TYPE_VALUE: + sb.append("VALUE(").append(value).append(")"); + break; + case TYPE_LEFT_BRACE: + sb.append("LEFT BRACE({)"); + break; + case TYPE_RIGHT_BRACE: + sb.append("RIGHT BRACE(})"); + break; + case TYPE_LEFT_SQUARE: + sb.append("LEFT SQUARE([)"); + break; + case TYPE_RIGHT_SQUARE: + sb.append("RIGHT SQUARE(])"); + break; + case TYPE_COMMA: + sb.append("COMMA(,)"); + break; + case TYPE_COLON: + sb.append("COLON(:)"); + break; + case TYPE_EOF: + sb.append("END OF FILE"); + break; + } + return sb.toString(); + } +} diff --git a/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java b/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java index 435bdd2..2c2aec1 100755 --- a/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java +++ b/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java @@ -4,6 +4,9 @@ import java.util.Arrays; import java.util.List; +import com.godaddy.sonar.ruby.rules.MetricfuRoodiYamlParserImpl; +import com.godaddy.sonar.ruby.rules.RoodiSensor; +import com.godaddy.sonar.ruby.rules.RubyRuleRepository; import org.sonar.api.CoreProperties; import org.sonar.api.Properties; import org.sonar.api.PropertyType; @@ -32,6 +35,7 @@ public final class RubyPlugin extends SonarPlugin public List getExtensions() { List extensions = new ArrayList(); + extensions.add(RubyRuleRepository.class); extensions.add(Ruby.class); extensions.add(SimpleCovRcovSensor.class); extensions.add(SimpleCovRcovJsonParserImpl.class); @@ -70,12 +74,16 @@ public List getExtensions() .subCategory("Ruby Coverage") .name("MetricFu Complexity Metric") .description("Type of complexity, Saikuro or Cane") - .defaultValue("Saikuro") + .defaultValue("Cane") .onQualifiers(Qualifiers.PROJECT) .type(PropertyType.SINGLE_SELECT_LIST) .options(options) .build(); extensions.add(ComplexityMetric); + extensions.add(MetricfuRoodiYamlParserImpl.class); + extensions.add(RoodiSensor.class); +// extensions.add(MetricfuDuplicationSensor.class); +// extensions.add(MetricfuDuplicationYamlParserImpl.class); return extensions; } diff --git a/src/main/java/com/godaddy/sonar/ruby/RubySensor.java b/src/main/java/com/godaddy/sonar/ruby/RubySensor.java index 02dd819..62128e5 100755 --- a/src/main/java/com/godaddy/sonar/ruby/RubySensor.java +++ b/src/main/java/com/godaddy/sonar/ruby/RubySensor.java @@ -12,7 +12,6 @@ import org.sonar.api.batch.Sensor; import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.FilePredicate; -import org.sonar.api.batch.fs.FilePredicates; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.config.Settings; diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensor.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensor.java index 81c07d9..3873fed 100755 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensor.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensor.java @@ -53,6 +53,7 @@ public boolean shouldExecuteOnProject(Project project) return fs.hasFiles(fs.predicates().hasLanguage("ruby")); } + @Override public void analyse(Project project, SensorContext context) { File report = pathResolver.relativeFile(fs.baseDir(), reportPath); @@ -89,6 +90,7 @@ private void analyzeFile(InputFile inputFile, SensorContext sensorContext, File // on that file if (functions.isEmpty() || functions.size() == 0 || functions == null) { + System.out.println("returning..... function"+ functions + " File"+ inputFile); return; } @@ -100,7 +102,7 @@ private void analyzeFile(InputFile inputFile, SensorContext sensorContext, File fileComplexity += function.getComplexity(); LOG.info("File complexity " + fileComplexity); } - + sensorContext.saveMeasure(inputFile, CoreMetrics.COMPLEXITY, Double.valueOf(fileComplexity)); RangeDistributionBuilder fileDistribution = new RangeDistributionBuilder(CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION, FILES_DISTRIB_BOTTOM_LIMITS); fileDistribution.add(Double.valueOf(fileComplexity)); @@ -115,6 +117,7 @@ private void analyzeFile(InputFile inputFile, SensorContext sensorContext, File { functionDistribution.add(Double.valueOf(function.getComplexity())); } + System.out.println("Analyzeds for : "+ inputFile); sensorContext.saveMeasure(inputFile, functionDistribution.build().setPersistenceMode(PersistenceMode.MEMORY)); } -} +} \ No newline at end of file diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexityYamlParserImpl.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexityYamlParserImpl.java index f012895..7742a9a 100755 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexityYamlParserImpl.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexityYamlParserImpl.java @@ -19,6 +19,8 @@ public class MetricfuComplexityYamlParserImpl implements MetricfuComplexityYamlParser { + + private Map metricfuResult; private static final Logger LOG = LoggerFactory .getLogger(MetricfuComplexityYamlParser.class); @@ -44,10 +46,12 @@ public List parseFunctions(String fileNameFromModule, File results // } Yaml yaml = new Yaml(); - Map metricfuResult = new HashMap(); try { // metricfuResult = (Map) yaml.loadAs(fileString, Map.class); - metricfuResult = (Map) yaml.load(resultsStream); + if(metricfuResult == null) { + metricfuResult = new HashMap(); + metricfuResult = (Map) yaml.load(resultsStream); + } Map saikuroResult = (Map) metricfuResult.get(":saikuro"); Map caneResult = (Map) metricfuResult.get(":cane"); diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationSensor.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationSensor.java new file mode 100644 index 0000000..1c6ac27 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationSensor.java @@ -0,0 +1,76 @@ +package com.godaddy.sonar.ruby.metricfu; + +import com.godaddy.sonar.ruby.RubyPlugin; +import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.batch.sensor.duplication.DuplicationBuilder; +import org.sonar.api.config.Settings; +import org.sonar.api.resources.Project; +import org.sonar.api.scan.filesystem.PathResolver; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +/** + * Created by akash.v on 22/04/16. + */ +public class MetricfuDuplicationSensor implements Sensor { + + private static final Logger LOG = LoggerFactory + .getLogger(MetricfuComplexitySensor.class); + + private MetricfuDuplicationYamlParserImpl metricfuDuplicationYamlParserImpl; + private Settings settings; + private FileSystem fs; + + private static final Number[] FILES_DISTRIB_BOTTOM_LIMITS = { 0, 5, 10, 20, 30, 60, 90 }; + private static final Number[] FUNCTIONS_DISTRIB_BOTTOM_LIMITS = { 1, 2, 4, 6, 8, 10, 12, 20, 30 }; + + private String reportPath = "tmp/metric_fu/report.yml"; + private PathResolver pathResolver; + + public MetricfuDuplicationSensor(Settings settings, FileSystem fs, + PathResolver pathResolver, + MetricfuDuplicationYamlParserImpl metricfuDuplicationYamlParserImpl) { + this.settings = settings; + this.fs = fs; + this.metricfuDuplicationYamlParserImpl = metricfuDuplicationYamlParserImpl; + this.pathResolver = pathResolver; + String reportpath_prop = settings.getString(RubyPlugin.METRICFU_REPORT_PATH_PROPERTY); + if (null != reportpath_prop) { + this.reportPath = reportpath_prop; + } + } + + @Override + public void analyse(Project project, SensorContext sensorContext) { + LOG.info("Analysing Duplications."); + File report = pathResolver.relativeFile(fs.baseDir(), reportPath); + LOG.info("Calling analyse for report results: " + report.getPath()); + if (!report.isFile()) { + LOG.warn("MetricFu report not found at {}", report); + return; + } + + List sourceFiles = Lists.newArrayList(fs.inputFiles(fs.predicates().hasLanguage("ruby"))); + + try { + metricfuDuplicationYamlParserImpl.parse(sourceFiles, report); + } catch (IOException e) { + LOG.error("Parsing duplications failed:"); + e.printStackTrace(); + } + } + + + @Override + public boolean shouldExecuteOnProject(Project project) { + return fs.hasFiles(fs.predicates().hasLanguage("ruby")); + } +} diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationYamlParser.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationYamlParser.java new file mode 100644 index 0000000..b2a29d2 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationYamlParser.java @@ -0,0 +1,17 @@ +package com.godaddy.sonar.ruby.metricfu; + +import org.sonar.api.BatchExtension; +import org.sonar.api.batch.fs.InputFile; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +/** + * Created by akash.v on 25/04/16. + */ +public interface MetricfuDuplicationYamlParser extends BatchExtension { + + public void parse(List inputFiles, File resultsFile) throws IOException; + +} diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationYamlParserImpl.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationYamlParserImpl.java new file mode 100644 index 0000000..67027bd --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuDuplicationYamlParserImpl.java @@ -0,0 +1,77 @@ +package com.godaddy.sonar.ruby.metricfu; + +import com.google.common.base.Throwables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.fs.InputFile; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by akash.v on 22/04/16. + */ +public class MetricfuDuplicationYamlParserImpl implements MetricfuDuplicationYamlParser { + + private static final Logger LOG = LoggerFactory + .getLogger(MetricfuComplexityYamlParser.class); + + @SuppressWarnings("unchecked") + @Override + public void parse(List inputFiles, File resultsFile) throws IOException + { + InputStream resultsStream = new FileInputStream(resultsFile); + + LOG.debug("MetricfuDuplicationYamlParserImpl: Start start parse of metrics_fu YAML"); + + Yaml yaml = new Yaml(); + Map> metricfuResult = new HashMap(); + try { + metricfuResult = (Map>) yaml.load(resultsStream); + + ArrayList> flayResult = metricfuResult.get(":flay").get(":matches"); + + analyzeFlay(inputFiles, flayResult); + + } catch (Exception e) { + LOG.error(Throwables.getStackTraceAsString(e)); + throw new IOException("Failure parsing YAML results", e); + } + + } + + private void analyzeFlay(List inputFiles, ArrayList> flayResult) { + Map indexedInputFiles = index(inputFiles); + for(Map duplicate : flayResult){ + if(((String)duplicate.get(":reason")).contains("IDENTICAL")){ + ArrayList> matches = (ArrayList>) duplicate.get(":matches"); +// DuplicationBuilder duplicationBuilder = new DefaultDuplicationBuilder(indexedInputFiles.get(matches.get(0).get(":name"))); + LOG.info("Identical Code Found: {}", matches ); + for(Map match : matches ){ +// duplicationBuilder.isDuplicatedBy(indexedInputFiles.get(match.get(":name")), Integer.parseInt(match.get(":line")), 1); + + } + } + } + + } + + private Map index(List inputFiles) { + Map indexedFiles= Maps.newConcurrentMap(); + + for(InputFile inputFile : inputFiles){ + indexedFiles.put(inputFile.relativePath(), inputFile); + } + + return indexedFiles; + } +} diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParser.java b/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParser.java new file mode 100644 index 0000000..37110b1 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParser.java @@ -0,0 +1,15 @@ +package com.godaddy.sonar.ruby.rules; + +import org.sonar.api.BatchExtension; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.List; + +/** + * Created by akash.v on 27/04/16. + */ +public interface MetricfuRoodiYamlParser extends BatchExtension{ + + public List parse(String fileName, File resultsFile) throws FileNotFoundException; +} diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParserImpl.java b/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParserImpl.java new file mode 100644 index 0000000..9c93734 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParserImpl.java @@ -0,0 +1,57 @@ +package com.godaddy.sonar.ruby.rules; + +import com.google.common.base.Throwables; +import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +import java.io.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by akash.v on 27/04/16. + */ +public class MetricfuRoodiYamlParserImpl implements MetricfuRoodiYamlParser { + private static final Logger LOG = LoggerFactory + .getLogger(MetricfuRoodiYamlParser.class); + private static Map metricfuResult; + @Override + public List parse(String fileName, File resultsFile) throws FileNotFoundException { + + InputStream resultsStream = new FileInputStream(resultsFile); + LOG.debug("MetricfuRoodiYamlParserImpl Start start parse of metrics_fu YAML"); + List roodiProblems = Lists.newArrayList(); + Yaml yaml = new Yaml(); + + try { + if(metricfuResult == null) + metricfuResult = (Map) yaml.load(resultsStream); + Map> roodiResult = (Map>) metricfuResult.get(":roodi"); + + for(Map problemMap: (List >) roodiResult.get(":problems")){ + String file = problemMap.get(":file"); + if(fileName.equals(file)) { + roodiProblems.add(getProblem(problemMap)); + + } + } + + } catch (Exception e) { + LOG.error("Failure parsing YAML results {}", Throwables.getStackTraceAsString(e)); + } + + return roodiProblems; + } + + private RoodiProblem getProblem(Map problem) { + return new RoodiProblem(problem.get(":file"), Integer.parseInt(problem.get(":line")), problem.get(":problem")); + } + + public static void main(String[] args) throws FileNotFoundException { + MetricfuRoodiYamlParser parser= new MetricfuRoodiYamlParserImpl(); + List problems = parser.parse("app/builders/fulfillment_model_builder_factory.rb", new File("/Users/akash.v/Sources/office/symphony/tmp/metric_fu/report.yml")); + } +} diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiProblem.java b/src/main/java/com/godaddy/sonar/ruby/rules/RoodiProblem.java new file mode 100644 index 0000000..594d38b --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/rules/RoodiProblem.java @@ -0,0 +1,25 @@ +package com.godaddy.sonar.ruby.rules; + +/** + * Created by akash.v on 27/04/16. + */ +public class RoodiProblem { + + public String file; + + public int line; + + public String problem; + + public RoodiProblem(String file, int line, String problem){ + this.file = file; + this.line = line; + this.problem = problem; + } + + + public int getLine() { + return line; + } + +} diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRule.java b/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRule.java new file mode 100644 index 0000000..a28ae6e --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRule.java @@ -0,0 +1,15 @@ +package com.godaddy.sonar.ruby.rules; + +import org.sonar.api.rule.Severity; + +/** + * Created by akash.v on 02/05/16. + */ +public class RoodiRule { + String key; + String name; + String description; + String severity; + String debtRemediationFunctionOffset; + String regex; +} diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRuleParser.java b/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRuleParser.java new file mode 100644 index 0000000..bbb9984 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRuleParser.java @@ -0,0 +1,81 @@ +package com.godaddy.sonar.ruby.rules; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Created by akash.v on 02/05/16. + */ +public class RoodiRuleParser { + + private static final String RULES_FILE = "rules.yml"; + private Yaml yaml; + private List roodiRules; + private Map regexIdMap; + private static final Logger LOG = LoggerFactory + .getLogger(RoodiRuleParser.class); + + public RoodiRuleParser(){ + yaml = new Yaml(); + } + + public List parse(){ + + if(roodiRules == null) { + roodiRules = Lists.newArrayList(); + + for(Map p: (List>) yaml.load(getClass().getResourceAsStream(RULES_FILE))){ + roodiRules.add(ruleFor(p)); + } + createMap(); + } + + return roodiRules; + } + + private RoodiRule ruleFor(Map p) { + RoodiRule r = new RoodiRule(); + r.key = (String) p.get("key"); + r.description = (String) p.get("description"); + r.name = (String) p.get("name"); + r.regex = (String) p.get("regex"); + r.severity = (String) p.get("severity"); + r.debtRemediationFunctionOffset = (String) p.get("debtRemediationFunctionOffset"); + + return r; + } + + + private void createMap() { + regexIdMap = Maps.newConcurrentMap(); + for(RoodiRule r : roodiRules){ + regexIdMap.put(Pattern.compile(r.regex), r.key); + } + } + + public String getKey(String discription){ + if(regexIdMap == null){ + parse(); + } + for(Pattern p : regexIdMap.keySet()){ + if(p.matcher(discription).find()){ + return regexIdMap.get(p); + } + } + return null; + } + + public static void main(String[] args) { + RoodiRuleParser roodiRuleParser = new RoodiRuleParser(); + roodiRuleParser.parse(); + } +} diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiSensor.java b/src/main/java/com/godaddy/sonar/ruby/rules/RoodiSensor.java new file mode 100644 index 0000000..e8582ed --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/rules/RoodiSensor.java @@ -0,0 +1,109 @@ +package com.godaddy.sonar.ruby.rules; + +import com.godaddy.sonar.ruby.RubyPlugin; +import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.batch.Sensor; +import org.sonar.api.batch.SensorContext; +import org.sonar.api.batch.fs.FileSystem; +import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.batch.rule.ActiveRules; +import org.sonar.api.component.ResourcePerspectives; +import org.sonar.api.config.Settings; +import org.sonar.api.issue.Issuable; +import org.sonar.api.issue.Issue; +import org.sonar.api.measures.Measure; +import org.sonar.api.resources.Project; +import org.sonar.api.rule.RuleKey; +import org.sonar.api.scan.filesystem.PathResolver; +import org.sonar.batch.protocol.input.Metric; + +import java.io.File; +import java.io.FileNotFoundException; + +import java.util.List; + +/** + * Created by akash.v on 27/04/16. + */ +public class RoodiSensor implements Sensor { + + private static final Logger LOG = LoggerFactory + .getLogger(RoodiSensor.class); + private MetricfuRoodiYamlParser metricfuRoodiYamlParser; + private ActiveRules activeRules; + private ResourcePerspectives resourcePerspectives; + private Settings settings; + private FileSystem fs; + private String reportPath = "tmp/metric_fu/report.yml"; + private PathResolver pathResolver; + private RoodiRuleParser roodiRuleParser; + + public RoodiSensor(Settings settings, FileSystem fs, ActiveRules activeRules, ResourcePerspectives resourcePerspectives, PathResolver pathResolver, MetricfuRoodiYamlParser metricfuRoodiYamlParser) { + + this.settings = settings; + this.fs = fs; + this.activeRules = activeRules; + this.resourcePerspectives = resourcePerspectives; + this.pathResolver = pathResolver; + String reportpath_prop = settings.getString(RubyPlugin.METRICFU_REPORT_PATH_PROPERTY); + this.metricfuRoodiYamlParser = metricfuRoodiYamlParser; + if (null != reportpath_prop) { + this.reportPath = reportpath_prop; + } + roodiRuleParser = new RoodiRuleParser(); + roodiRuleParser.parse(); + } + + + @Override + public void analyse(Project project, SensorContext sensorContext) { + File report = pathResolver.relativeFile(fs.baseDir(), reportPath); + LOG.info("Calling analyse for report results: " + report.getPath()); + if (!report.isFile()) { + LOG.warn("MetricFu report not found at {}", report); + return; + } + + List sourceFiles = Lists.newArrayList(fs.inputFiles(fs.predicates().hasLanguage("ruby"))); + + for (InputFile inputFile : sourceFiles) + { + LOG.debug("analyzing functions for Issues in the file: " + inputFile.file().getName()); + try + { + analyzeFile(inputFile, sensorContext, report); + } catch (Exception e) + { + LOG.error("Can not analyze the file " + inputFile.absolutePath() + " for issues", e); + } + } + } + + private void analyzeFile(InputFile inputFile, SensorContext sensorContext, File report) throws FileNotFoundException { + List issues= metricfuRoodiYamlParser.parse(inputFile.relativePath(), report); + for (RoodiProblem roodiProblem: issues) { + if (roodiRuleParser.getKey(roodiProblem.problem) != null) { + RuleKey ruleKey = RuleKey.of(RubyRuleRepository.REPOSITORY_KEY, roodiRuleParser.getKey(roodiProblem.problem)); + LOG.info("Rule Key: {}", ruleKey); + Issuable issuable = resourcePerspectives.as(Issuable.class, inputFile); + if (issuable != null) { + issuable.addIssue(issuable.newIssueBuilder() + .ruleKey(ruleKey) + .line(roodiProblem.getLine()) + .message(roodiProblem.problem) + .build()); + LOG.info("adding issue."); + } + } else { + LOG.warn("Ruby rule '{}' is unknown in Sonar", roodiProblem.problem); + } + } + } + + @Override + public boolean shouldExecuteOnProject(Project project) { + return fs.hasFiles(fs.predicates().hasLanguage("ruby")); + } +} \ No newline at end of file diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RubyRuleRepository.java b/src/main/java/com/godaddy/sonar/ruby/rules/RubyRuleRepository.java new file mode 100644 index 0000000..1666962 --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/rules/RubyRuleRepository.java @@ -0,0 +1,43 @@ +package com.godaddy.sonar.ruby.rules; + +import com.godaddy.sonar.ruby.core.Ruby; +import org.apache.commons.codec.Charsets; +import org.sonar.api.rule.RuleStatus; +import org.sonar.api.rule.Severity; +import org.sonar.api.server.rule.RulesDefinition; +import org.sonar.api.server.rule.RulesDefinitionXmlLoader; + +import javax.annotation.ParametersAreNonnullByDefault; + + +/** + * Created by akash.v on 27/04/16. + */ +public class RubyRuleRepository implements RulesDefinition { + + public static final String REPOSITORY_NAME = "Roodi"; + public static final String REPOSITORY_KEY = REPOSITORY_NAME; + RoodiRuleParser roodiRuleParser = new RoodiRuleParser(); + + @ParametersAreNonnullByDefault + public void define(Context context) { + NewRepository repository = context + .createRepository(REPOSITORY_KEY, Ruby.KEY) + .setName(REPOSITORY_NAME); + + roodiRuleParser = new RoodiRuleParser(); + + for(RoodiRule rule : roodiRuleParser.parse()){ + NewRule newRule = repository.createRule(rule.key) + .setName(rule.name) + .setHtmlDescription(rule.description) + .setStatus(RuleStatus.READY) + .setSeverity(rule.severity); + newRule.setDebtSubCharacteristic(SubCharacteristics.LOGIC_RELIABILITY) + .setDebtRemediationFunction(newRule.debtRemediationFunctions().constantPerIssue(rule.debtRemediationFunctionOffset)); + } + + + repository.done(); + } +} diff --git a/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovJsonParserImpl.java b/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovJsonParserImpl.java index 16e198e..446e0db 100755 --- a/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovJsonParserImpl.java +++ b/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovJsonParserImpl.java @@ -2,18 +2,22 @@ import java.io.File; import java.io.IOException; + +import java.util.Collection; import java.util.Map; +import com.godaddy.sonar.org.json.simple.JSONArray; +import com.godaddy.sonar.org.json.simple.JSONObject; +import com.godaddy.sonar.org.json.simple.JSONValue; import org.apache.commons.io.FileUtils; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.JSONValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.measures.CoverageMeasuresBuilder; -import com.godaddy.sonar.ruby.simplecovrcov.SimpleCovRcovJsonParser; import com.google.common.collect.Maps; +import org.sonar.api.measures.Measure; +import org.sonar.core.measure.db.MeasureDto; +import org.sonar.squid.api.SourceCode; public class SimpleCovRcovJsonParserImpl implements SimpleCovRcovJsonParser { @@ -26,11 +30,9 @@ public Map parse(File file) throws IOException File fileToFindCoverage = file; String fileString = FileUtils.readFileToString(fileToFindCoverage, "UTF-8"); - JSONObject resultJsonObject = (JSONObject) JSONValue.parse(fileString); - JSONObject coverageJsonObj = (JSONObject) ((JSONObject) resultJsonObject.get("RSpec")).get("coverage"); + JSONObject coverageJsonObj = (JSONObject) ((JSONObject) resultJsonObject.get(resultJsonObject.keySet().iterator().next())).get("coverage"); - // for each file in the coverage report for (int j = 0; j < coverageJsonObj.keySet().size(); j++) { CoverageMeasuresBuilder fileCoverage = CoverageMeasuresBuilder.create(); diff --git a/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovSensor.java b/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovSensor.java index d42ffe7..3f15717 100755 --- a/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovSensor.java +++ b/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovSensor.java @@ -55,7 +55,7 @@ public SimpleCovRcovSensor(Settings settings, FileSystem fs, this.reportPath = reportpath_prop; } } - + @Override public boolean shouldExecuteOnProject(Project project) { // return Ruby.KEY.equals(fs.languages()); @@ -63,6 +63,7 @@ public boolean shouldExecuteOnProject(Project project) return fs.hasFiles(fs.predicates().hasLanguage("ruby")); } + @Override public void analyse(Project project, SensorContext context) { File report = pathResolver.relativeFile(fs.baseDir(), reportPath); diff --git a/src/main/resources/com/godaddy/sonar/ruby/rules/rules.yml b/src/main/resources/com/godaddy/sonar/ruby/rules/rules.yml new file mode 100644 index 0000000..de9fdb7 --- /dev/null +++ b/src/main/resources/com/godaddy/sonar/ruby/rules/rules.yml @@ -0,0 +1,66 @@ +--- +- + key: "R0001" + name: "Case statement is missing an else clause" + description: "Case statement is missing an else clause" + severity: "MINOR" + status: "READY" + debtRemediationFunctionOffset: "0d 0h 5min" + regex: "Case statement is missing an else clause." +- + key: "R0002" + name: "Class should have 300 or less lines." + description: "Class should have 300 or less number of lines." + severity: "MINOR" + status: "READY" + debtRemediationFunctionOffset: "0d 2h 5min" + regex: "Class \".*\" has .* lines. It should have 300 or less" +- + key: "R0003" + name: "Block cyclomatic complexity should be 4 or less" + description: "Block cyclomatic complexity should be 4 or less." + severity: "MINOR" + status: "READY" + debtRemediationFunctionOffset: "0d 0h 20min" + regex: "Block cyclomatic complexity is .* It should be 4 or less." +- + key: "R0004" + name: "Method cyclomatic complexity should be 8 or less." + description: "Method cyclomatic complexity should be 8 or less." + severity: "MINOR" + status: "READY" + debtRemediationFunctionOffset: "0d 0h 20min" + regex: "Method name \".*\" cyclomatic complexity is .* It should be 8 or less." +- + key: "R0005" + name: "Don't use 'for' loops. Use Enumerable.each instead." + description: "Don't use 'for' loops. Use Enumerable.each instead." + severity: "MINOR" + status: "READY" + debtRemediationFunctionOffset: "0d 0h 10min" + regex: "Don't use 'for' loops. Use Enumerable.each instead." +- + key: "R0006" + name: "Method should have 20 or less lines." + description: "Method should have 20 or less lines." + severity: "MINOR" + status: "READY" + debtRemediationFunctionOffset: "0d 0h 12min" + regex: "Method \".*\" has .* lines. It should have 20 or less." +- + key: "R0007" + name: "Method name should match pattern /^[_a-z<>=\\[\\]|+-\\/\\*`]+[_a-z0-9_<>=~@\\[\\]]*[=!\\?]?$/" + description: "Method name should match pattern /^[_a-z<>=\\[\\]|+-\\/\\*`]+[_a-z0-9_<>=~@\\[\\]]*[=!\\?]?$/" + severity: "MINOR" + status: "READY" + debtRemediationFunctionOffset: "0d 0h 5min" + regex: "Method name \".*\" should match pattern .*" +- + key: "R0008" + name: "Method should have 5 or less parameters." + description: "Method should have 5 or less parameters." + severity: "MINOR" + status: "READY" + debtRemediationFunctionOffset: "0d 0h 15min" + regex: "Method name \".*\" has .* parameters. It should have 5 or less" + From bc48f1d0392266fc821b94d30ed38dfd63d471b5 Mon Sep 17 00:00:00 2001 From: AKASH V Date: Tue, 3 May 2016 17:35:52 +0530 Subject: [PATCH 02/10] deleting RubyFileTest --- .../godaddy/sonar/ruby/RubySensorTest.java | 123 ------------------ .../godaddy/sonar/ruby/core/RubyFileTest.java | 103 --------------- .../MetricfuComplexitySensorTest.java | 97 -------------- 3 files changed, 323 deletions(-) delete mode 100755 src/test/java/com/godaddy/sonar/ruby/RubySensorTest.java delete mode 100755 src/test/java/com/godaddy/sonar/ruby/core/RubyFileTest.java delete mode 100755 src/test/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensorTest.java diff --git a/src/test/java/com/godaddy/sonar/ruby/RubySensorTest.java b/src/test/java/com/godaddy/sonar/ruby/RubySensorTest.java deleted file mode 100755 index 7aa6c4e..0000000 --- a/src/test/java/com/godaddy/sonar/ruby/RubySensorTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.godaddy.sonar.ruby; - -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -import org.easymock.EasyMock; -import org.easymock.IMocksControl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.fs.FilePredicate; -import org.sonar.api.batch.fs.FilePredicates; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.config.Settings; -import org.sonar.api.measures.Measure; -import org.sonar.api.measures.Metric; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.Resource; - -import com.godaddy.sonar.ruby.core.LanguageRuby; - -public class RubySensorTest { - public static String INPUT_SOURCE_DIR = "src/test/resources/test-data"; - public static String INPUT_SOURCE_FILE = "src/test/resources/test-data/hello_world.rb"; - - private IMocksControl mocksControl; - private SensorContext sensorContext; - private Project project; - private List sourceDirs; - private List files; - - private Settings settings; - private FileSystem fs; - private FilePredicates filePredicates; - private FilePredicate filePredicate; - - @Before - public void setUp() throws Exception { - mocksControl = EasyMock.createControl(); - fs = mocksControl.createMock(FileSystem.class); - filePredicates = mocksControl.createMock(FilePredicates.class); - filePredicate = mocksControl.createMock(FilePredicate.class); - - project = new Project("test project"); - settings = new Settings(); - project.setLanguage(LanguageRuby.INSTANCE); - - sensorContext = mocksControl.createMock(SensorContext.class); - - sourceDirs = new ArrayList(); - sourceDirs.add(new File(INPUT_SOURCE_DIR)); - files = new ArrayList(); - files.add(new File(INPUT_SOURCE_FILE)); - - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testRubySensor() { - RubySensor sensor = new RubySensor(settings, fs); - assertNotNull(sensor); - } - - @Test - public void testShouldExecuteOnProject() { - RubySensor sensor = new RubySensor(settings, fs); - - expect(fs.predicates()).andReturn(filePredicates).times(1); - expect(fs.hasFiles(isA(FilePredicate.class))).andReturn(true).times(1); - expect(filePredicates.hasLanguage(eq("ruby"))).andReturn(filePredicate).times(1); - mocksControl.replay(); - - sensor.shouldExecuteOnProject(project); - - mocksControl.verify(); - } - - @Test - public void testAnalyse() { - RubySensor sensor = new RubySensor(settings, fs); - - Measure measure = new Measure(); - List inputFiles = new ArrayList(); - File aFile = new File(INPUT_SOURCE_FILE); - DefaultInputFile difFile = new DefaultInputFile(aFile.getPath()); - difFile.setFile(aFile); - - inputFiles.add(difFile); - - expect(sensorContext.saveMeasure(isA(InputFile.class), isA(Metric.class), isA(Double.class))).andReturn(measure).times(4); - expect(sensorContext.saveMeasure(isA(Resource.class), isA(Metric.class), isA(Double.class))).andReturn(measure).times(1); - expect(fs.predicates()).andReturn(filePredicates).times(1); - expect(filePredicates.hasLanguage(eq("ruby"))).andReturn(filePredicate).times(1); - expect(fs.inputFiles(isA(FilePredicate.class))).andReturn((Iterable) inputFiles).times(1); - expect(fs.encoding()).andReturn(StandardCharsets.UTF_8).times(1); - - mocksControl.replay(); - - sensor.analyse(project, sensorContext); - mocksControl.verify(); - } - - @Test - public void testToString() { - RubySensor sensor = new RubySensor(settings, fs); - String result = sensor.toString(); - assertEquals("RubySensor", result); - } -} diff --git a/src/test/java/com/godaddy/sonar/ruby/core/RubyFileTest.java b/src/test/java/com/godaddy/sonar/ruby/core/RubyFileTest.java deleted file mode 100755 index d4ed81f..0000000 --- a/src/test/java/com/godaddy/sonar/ruby/core/RubyFileTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.godaddy.sonar.ruby.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.resources.Scopes; - -public class RubyFileTest { - protected final static String SOURCE_FILE = "/path/to/source/file.rb"; - - protected RubyFile rubyFile; - - @Before - public void setUp() { - File file = new File(SOURCE_FILE); - List sourceDirs = new ArrayList(); - -// fs.add(new DefaultInputFile(file.getPath()).setAbsolutePath(file.getAbsolutePath()).setType(Type.MAIN).setLanguage(Java.KEY)); - File aSrcDir = new File("/path/to/source"); -// sourceDirs.add(new DefaultInputFile("/path/to/source")); - sourceDirs.add(new DefaultInputFile(aSrcDir.getPath()).setAbsolutePath(file.getParent())); - - rubyFile = new RubyFile(file, sourceDirs); - } - - @After - public void tearDown() { - - } - - - - @Test(expected=IllegalArgumentException.class) - public void testRubyFileWithNullFile() { - new RubyFile(null, new ArrayList()); - } - - @Test - public void testRubyFileWithNullSourceDirs() { - File file = new File(SOURCE_FILE); - rubyFile = new RubyFile(file, null); - assertEquals("[default].file", rubyFile.getKey()); - } - - @Test - public void testGetParent() { - RubyPackage parent = rubyFile.getParent(); - assertEquals("source", parent.getKey()); - } - - @Test - public void testGetDescription() { - assertNull(rubyFile.getDescription()); - } - - @Test - public void testGetLanguage() { - assertEquals(Ruby.INSTANCE, rubyFile.getLanguage()); - } - - @Test - public void testGetName() { - assertEquals("file", rubyFile.getName()); - } - - @Test - public void testGetLongName() { - assertEquals("source.file", rubyFile.getLongName()); - } - - @Test - public void testGetScope() { - assertEquals(Scopes.FILE, rubyFile.getScope()); - } - - @Test - public void testGetQualifier() { - assertEquals(Qualifiers.CLASS, rubyFile.getQualifier()); - } - - @Test - public void testMatchFilePatternString() { - assertTrue(rubyFile.matchFilePattern("source.file.rb")); - } - -// @Test -// public void testToString() { -// System.out.println(rubyFile.toString()); -// assertTrue(rubyFile.toString().contains("key=source.file,package=source,longName=source.file")); -// } - -} diff --git a/src/test/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensorTest.java b/src/test/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensorTest.java deleted file mode 100755 index 9a2b122..0000000 --- a/src/test/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensorTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.godaddy.sonar.ruby.metricfu; - -import static org.easymock.EasyMock.expect; -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.configuration.Configuration; -import org.easymock.EasyMock; - -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.eq; - -import org.easymock.IMocksControl; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.config.Settings; -import org.sonar.api.measures.Measure; -import org.sonar.api.measures.Metric; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.Resource; -import org.sonar.api.scan.filesystem.FileQuery; -import org.sonar.api.scan.filesystem.ModuleFileSystem; -import org.sonar.api.scan.filesystem.PathResolver; - -import com.godaddy.sonar.ruby.RubySensor; -import com.godaddy.sonar.ruby.core.LanguageRuby; -import com.godaddy.sonar.ruby.core.RubyFile; - - -public class MetricfuComplexitySensorTest -{ - private IMocksControl mocksControl; - - private PathResolver pathResolver; - private SensorContext sensorContext; - private MetricfuComplexityYamlParser metricfuComplexityYamlParser; - private MetricfuComplexitySensor metricfuComplexitySensor; - private Configuration config; - private Project project; - - private Settings settings; - private FileSystem fs; - - @Before - public void setUp() throws Exception - { - mocksControl = EasyMock.createControl(); - pathResolver = mocksControl.createMock(PathResolver.class); - fs = mocksControl.createMock(FileSystem.class); - metricfuComplexityYamlParser = mocksControl.createMock(MetricfuComplexityYamlParser.class); - settings = new Settings(); - - metricfuComplexitySensor = new MetricfuComplexitySensor(settings, fs, pathResolver, metricfuComplexityYamlParser); - config = mocksControl.createMock(Configuration.class); - expect(config.getString("sonar.language", "java")).andStubReturn("ruby"); - - project = new Project("test project"); - project.setLanguage(LanguageRuby.INSTANCE); - project.setConfiguration(config); - - } - - @Test - public void testConstructor() - { - assertNotNull(metricfuComplexitySensor); - } - - @Test - public void testAnalyse() throws IOException - { - List sourceFiles= new ArrayList(); - List sourceDirs = new ArrayList(); - - sourceDirs.add(new File("lib")); - sourceFiles.add(new File("lib/some_path/foo_bar.rb")); - - sensorContext = mocksControl.createMock(SensorContext.class); - List functions = new ArrayList(); - functions.add(new RubyFunction("validate", 5, 10)); - - expect(fs.baseDir()).andReturn(new File("bar")); - expect(pathResolver.relativeFile(isA(File.class),isA(String.class))).andReturn(new File("foo")); - mocksControl.replay(); - - metricfuComplexitySensor.analyse(project, sensorContext); - mocksControl.verify(); - } -} From c19e0d1bdf6402efbdb43ef1d862a086dfeaa555 Mon Sep 17 00:00:00 2001 From: AKASH V Date: Wed, 4 May 2016 15:38:14 +0530 Subject: [PATCH 03/10] resolving merge conflic, add json-simple for packaging --- pom.xml | 12 +- .../sonar/org/json/simple/ItemList.java | 147 ---- .../sonar/org/json/simple/JSONArray.java | 381 ---------- .../sonar/org/json/simple/JSONAware.java | 12 - .../sonar/org/json/simple/JSONObject.java | 132 ---- .../org/json/simple/JSONStreamAware.java | 15 - .../sonar/org/json/simple/JSONValue.java | 315 -------- .../json/simple/parser/ContainerFactory.java | 23 - .../json/simple/parser/ContentHandler.java | 110 --- .../org/json/simple/parser/JSONParser.java | 533 -------------- .../json/simple/parser/ParseException.java | 90 --- .../sonar/org/json/simple/parser/Yylex.java | 688 ------------------ .../sonar/org/json/simple/parser/Yytoken.java | 58 -- .../SimpleCovRcovJsonParserImpl.java | 6 +- 14 files changed, 14 insertions(+), 2508 deletions(-) delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/ItemList.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONArray.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONAware.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONObject.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONStreamAware.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/JSONValue.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/ContainerFactory.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/ContentHandler.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/JSONParser.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/ParseException.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/Yylex.java delete mode 100644 src/main/java/com/godaddy/sonar/org/json/simple/parser/Yytoken.java diff --git a/pom.xml b/pom.xml index 2378926..860317c 100755 --- a/pom.xml +++ b/pom.xml @@ -24,7 +24,6 @@ snakeyaml 1.16 - org.codehaus.sonar sonar-plugin-api @@ -34,6 +33,12 @@ org.codehaus.sonar sonar-batch ${sonar.buildVersion} + + + com.googlecode.json-simple + json-simple + + @@ -76,6 +81,11 @@ commons-configuration 1.9 + + com.googlecode.json-simple + json-simple + 1.1.1 + diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/ItemList.java b/src/main/java/com/godaddy/sonar/org/json/simple/ItemList.java deleted file mode 100644 index 7485ef7..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/ItemList.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * $Id: ItemList.java,v 1.1 2006/04/15 14:10:48 platform Exp $ - * Created on 2006-3-24 - */ -package com.godaddy.sonar.org.json.simple; - -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -/** - * |a:b:c| => |a|,|b|,|c| - * |:| => ||,|| - * |a:| => |a|,|| - * @author FangYidong - */ -public class ItemList { - private String sp=","; - List items=new ArrayList(); - - - public ItemList(){} - - - public ItemList(String s){ - this.split(s,sp,items); - } - - public ItemList(String s,String sp){ - this.sp=s; - this.split(s,sp,items); - } - - public ItemList(String s,String sp,boolean isMultiToken){ - split(s,sp,items,isMultiToken); - } - - public List getItems(){ - return this.items; - } - - public String[] getArray(){ - return (String[])this.items.toArray(); - } - - public void split(String s,String sp,List append,boolean isMultiToken){ - if(s==null || sp==null) - return; - if(isMultiToken){ - StringTokenizer tokens=new StringTokenizer(s,sp); - while(tokens.hasMoreTokens()){ - append.add(tokens.nextToken().trim()); - } - } - else{ - this.split(s,sp,append); - } - } - - public void split(String s,String sp,List append){ - if(s==null || sp==null) - return; - int pos=0; - int prevPos=0; - do{ - prevPos=pos; - pos=s.indexOf(sp,pos); - if(pos==-1) - break; - append.add(s.substring(prevPos,pos).trim()); - pos+=sp.length(); - }while(pos!=-1); - append.add(s.substring(prevPos).trim()); - } - - public void setSP(String sp){ - this.sp=sp; - } - - public void add(int i,String item){ - if(item==null) - return; - items.add(i,item.trim()); - } - - public void add(String item){ - if(item==null) - return; - items.add(item.trim()); - } - - public void addAll(ItemList list){ - items.addAll(list.items); - } - - public void addAll(String s){ - this.split(s,sp,items); - } - - public void addAll(String s,String sp){ - this.split(s,sp,items); - } - - public void addAll(String s,String sp,boolean isMultiToken){ - this.split(s,sp,items,isMultiToken); - } - - /** - * @param i 0-based - * @return - */ - public String get(int i){ - return (String)items.get(i); - } - - public int size(){ - return items.size(); - } - - public String toString(){ - return toString(sp); - } - - public String toString(String sp){ - StringBuffer sb=new StringBuffer(); - - for(int i=0;i - */ -public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware { - private static final long serialVersionUID = 3957988303675231981L; - - /** - * Constructs an empty JSONArray. - */ - public JSONArray(){ - super(); - } - - /** - * Constructs a JSONArray containing the elements of the specified - * collection, in the order they are returned by the collection's iterator. - * - * @param c the collection whose elements are to be placed into this JSONArray - */ - public JSONArray(Collection c){ - super(c); - } - - /** - * Encode a list into JSON text and write it to out. - * If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level. - * - * @see org.json.simple.JSONValue#writeJSONString(Object, Writer) - * - * @param collection - * @param out - */ - public static void writeJSONString(Collection collection, Writer out) throws IOException{ - if(collection == null){ - out.write("null"); - return; - } - - boolean first = true; - Iterator iter=collection.iterator(); - - out.write('['); - while(iter.hasNext()){ - if(first) - first = false; - else - out.write(','); - - Object value=iter.next(); - if(value == null){ - out.write("null"); - continue; - } - - JSONValue.writeJSONString(value, out); - } - out.write(']'); - } - - public void writeJSONString(Writer out) throws IOException{ - writeJSONString(this, out); - } - - /** - * Convert a list to JSON text. The result is a JSON array. - * If this list is also a JSONAware, JSONAware specific behaviours will be omitted at this top level. - * - * @see org.json.simple.JSONValue#toJSONString(Object) - * - * @param collection - * @return JSON text, or "null" if list is null. - */ - public static String toJSONString(Collection collection){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(collection, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(byte[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("["); - out.write(String.valueOf(array[0])); - - for(int i = 1; i < array.length; i++){ - out.write(","); - out.write(String.valueOf(array[i])); - } - - out.write("]"); - } - } - - public static String toJSONString(byte[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(short[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("["); - out.write(String.valueOf(array[0])); - - for(int i = 1; i < array.length; i++){ - out.write(","); - out.write(String.valueOf(array[i])); - } - - out.write("]"); - } - } - - public static String toJSONString(short[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(int[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("["); - out.write(String.valueOf(array[0])); - - for(int i = 1; i < array.length; i++){ - out.write(","); - out.write(String.valueOf(array[i])); - } - - out.write("]"); - } - } - - public static String toJSONString(int[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(long[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("["); - out.write(String.valueOf(array[0])); - - for(int i = 1; i < array.length; i++){ - out.write(","); - out.write(String.valueOf(array[i])); - } - - out.write("]"); - } - } - - public static String toJSONString(long[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(float[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("["); - out.write(String.valueOf(array[0])); - - for(int i = 1; i < array.length; i++){ - out.write(","); - out.write(String.valueOf(array[i])); - } - - out.write("]"); - } - } - - public static String toJSONString(float[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(double[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("["); - out.write(String.valueOf(array[0])); - - for(int i = 1; i < array.length; i++){ - out.write(","); - out.write(String.valueOf(array[i])); - } - - out.write("]"); - } - } - - public static String toJSONString(double[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(boolean[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("["); - out.write(String.valueOf(array[0])); - - for(int i = 1; i < array.length; i++){ - out.write(","); - out.write(String.valueOf(array[i])); - } - - out.write("]"); - } - } - - public static String toJSONString(boolean[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(char[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("[\""); - out.write(String.valueOf(array[0])); - - for(int i = 1; i < array.length; i++){ - out.write("\",\""); - out.write(String.valueOf(array[i])); - } - - out.write("\"]"); - } - } - - public static String toJSONString(char[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public static void writeJSONString(Object[] array, Writer out) throws IOException{ - if(array == null){ - out.write("null"); - } else if(array.length == 0) { - out.write("[]"); - } else { - out.write("["); - JSONValue.writeJSONString(array[0], out); - - for(int i = 1; i < array.length; i++){ - out.write(","); - JSONValue.writeJSONString(array[i], out); - } - - out.write("]"); - } - } - - public static String toJSONString(Object[] array){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(array, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - public String toJSONString(){ - return toJSONString(this); - } - - /** - * Returns a string representation of this array. This is equivalent to - * calling {@link JSONArray#toJSONString()}. - */ - public String toString() { - return toJSONString(); - } -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/JSONAware.java b/src/main/java/com/godaddy/sonar/org/json/simple/JSONAware.java deleted file mode 100644 index 9a648d3..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/JSONAware.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.godaddy.sonar.org.json.simple; - -/** - * Beans that support customized output of JSON text shall implement this interface. - * @author FangYidong - */ -public interface JSONAware { - /** - * @return JSON text - */ - String toJSONString(); -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/JSONObject.java b/src/main/java/com/godaddy/sonar/org/json/simple/JSONObject.java deleted file mode 100644 index d3f09c7..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/JSONObject.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * $Id: JSONObject.java,v 1.1 2006/04/15 14:10:48 platform Exp $ - * Created on 2006-4-10 - */ -package com.godaddy.sonar.org.json.simple; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface. - * - * @author FangYidong - */ -public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware{ - - private static final long serialVersionUID = -503443796854799292L; - - - public JSONObject() { - super(); - } - - /** - * Allows creation of a JSONObject from a Map. After that, both the - * generated JSONObject and the Map can be modified independently. - * - * @param map - */ - public JSONObject(Map map) { - super(map); - } - - - /** - * Encode a map into JSON text and write it to out. - * If this map is also a JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific behaviours will be ignored at this top level. - * - * @see org.json.simple.JSONValue#writeJSONString(Object, Writer) - * - * @param map - * @param out - */ - public static void writeJSONString(Map map, Writer out) throws IOException { - if(map == null){ - out.write("null"); - return; - } - - boolean first = true; - Iterator iter=map.entrySet().iterator(); - - out.write('{'); - while(iter.hasNext()){ - if(first) - first = false; - else - out.write(','); - Map.Entry entry=(Map.Entry)iter.next(); - out.write('\"'); - out.write(escape(String.valueOf(entry.getKey()))); - out.write('\"'); - out.write(':'); - JSONValue.writeJSONString(entry.getValue(), out); - } - out.write('}'); - } - - public void writeJSONString(Writer out) throws IOException{ - writeJSONString(this, out); - } - - /** - * Convert a map to JSON text. The result is a JSON object. - * If this map is also a JSONAware, JSONAware specific behaviours will be omitted at this top level. - * - * @see org.json.simple.JSONValue#toJSONString(Object) - * - * @param map - * @return JSON text, or "null" if map is null. - */ - public static String toJSONString(Map map){ - final StringWriter writer = new StringWriter(); - - try { - writeJSONString(map, writer); - return writer.toString(); - } catch (IOException e) { - // This should never happen with a StringWriter - throw new RuntimeException(e); - } - } - - public String toJSONString(){ - return toJSONString(this); - } - - public String toString(){ - return toJSONString(); - } - - public static String toString(String key,Object value){ - StringBuffer sb = new StringBuffer(); - sb.append('\"'); - if(key == null) - sb.append("null"); - else - JSONValue.escape(key, sb); - sb.append('\"').append(':'); - - sb.append(JSONValue.toJSONString(value)); - - return sb.toString(); - } - - /** - * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). - * It's the same as JSONValue.escape() only for compatibility here. - * - * @see org.json.simple.JSONValue#escape(String) - * - * @param s - * @return - */ - public static String escape(String s){ - return JSONValue.escape(s); - } -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/JSONStreamAware.java b/src/main/java/com/godaddy/sonar/org/json/simple/JSONStreamAware.java deleted file mode 100644 index 24cf3f8..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/JSONStreamAware.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.godaddy.sonar.org.json.simple; - -import java.io.IOException; -import java.io.Writer; - -/** - * Beans that support customized output of JSON text to a writer shall implement this interface. - * @author FangYidong - */ -public interface JSONStreamAware { - /** - * write JSON string to out. - */ - void writeJSONString(Writer out) throws IOException; -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/JSONValue.java b/src/main/java/com/godaddy/sonar/org/json/simple/JSONValue.java deleted file mode 100644 index c34aa70..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/JSONValue.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * $Id: JSONValue.java,v 1.1 2006/04/15 14:37:04 platform Exp $ - * Created on 2006-4-15 - */ -package com.godaddy.sonar.org.json.simple; - -import com.godaddy.sonar.org.json.simple.parser.JSONParser; -import com.godaddy.sonar.org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Collection; -// import java.util.List; -import java.util.Map; - -/** - * @author FangYidong - */ -public class JSONValue { - /** - * Parse JSON text into java object from the input source. - * Please use parseWithException() if you don't want to ignore the exception. - * - * @see org.json.simple.parser.JSONParser#parse(Reader) - * @see #parseWithException(Reader) - * - * @param in - * @return Instance of the following: - * org.json.simple.JSONObject, - * org.json.simple.JSONArray, - * java.lang.String, - * java.lang.Number, - * java.lang.Boolean, - * null - * - * @deprecated this method may throw an {@code Error} instead of returning - * {@code null}; please use {@link JSONValue#parseWithException(Reader)} - * instead - */ - public static Object parse(Reader in){ - try{ - JSONParser parser=new JSONParser(); - return parser.parse(in); - } - catch(Exception e){ - return null; - } - } - - /** - * Parse JSON text into java object from the given string. - * Please use parseWithException() if you don't want to ignore the exception. - * - * @see org.json.simple.parser.JSONParser#parse(Reader) - * @see #parseWithException(Reader) - * - * @param s - * @return Instance of the following: - * org.json.simple.JSONObject, - * org.json.simple.JSONArray, - * java.lang.String, - * java.lang.Number, - * java.lang.Boolean, - * null - * - * @deprecated this method may throw an {@code Error} instead of returning - * {@code null}; please use {@link JSONValue#parseWithException(String)} - * instead - */ - public static Object parse(String s){ - StringReader in=new StringReader(s); - return parse(in); - } - - /** - * Parse JSON text into java object from the input source. - * - * @see org.json.simple.parser.JSONParser - * - * @param in - * @return Instance of the following: - * org.json.simple.JSONObject, - * org.json.simple.JSONArray, - * java.lang.String, - * java.lang.Number, - * java.lang.Boolean, - * null - * - * @throws IOException - * @throws ParseException - */ - public static Object parseWithException(Reader in) throws IOException, ParseException{ - JSONParser parser=new JSONParser(); - return parser.parse(in); - } - - public static Object parseWithException(String s) throws ParseException { - JSONParser parser=new JSONParser(); - return parser.parse(s); - } - - /** - * Encode an object into JSON text and write it to out. - *

- * If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly. - *

- * DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with - * "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead. - * - * @see org.json.simple.JSONObject#writeJSONString(Map, Writer) - * @see org.json.simple.JSONArray#writeJSONString(List, Writer) - * - * @param value - * @param writer - */ - public static void writeJSONString(Object value, Writer out) throws IOException { - if(value == null){ - out.write("null"); - return; - } - - if(value instanceof String){ - out.write('\"'); - out.write(escape((String)value)); - out.write('\"'); - return; - } - - if(value instanceof Double){ - if(((Double)value).isInfinite() || ((Double)value).isNaN()) - out.write("null"); - else - out.write(value.toString()); - return; - } - - if(value instanceof Float){ - if(((Float)value).isInfinite() || ((Float)value).isNaN()) - out.write("null"); - else - out.write(value.toString()); - return; - } - - if(value instanceof Number){ - out.write(value.toString()); - return; - } - - if(value instanceof Boolean){ - out.write(value.toString()); - return; - } - - if((value instanceof JSONStreamAware)){ - ((JSONStreamAware)value).writeJSONString(out); - return; - } - - if((value instanceof JSONAware)){ - out.write(((JSONAware)value).toJSONString()); - return; - } - - if(value instanceof Map){ - JSONObject.writeJSONString((Map)value, out); - return; - } - - if(value instanceof Collection){ - JSONArray.writeJSONString((Collection)value, out); - return; - } - - if(value instanceof byte[]){ - JSONArray.writeJSONString((byte[])value, out); - return; - } - - if(value instanceof short[]){ - JSONArray.writeJSONString((short[])value, out); - return; - } - - if(value instanceof int[]){ - JSONArray.writeJSONString((int[])value, out); - return; - } - - if(value instanceof long[]){ - JSONArray.writeJSONString((long[])value, out); - return; - } - - if(value instanceof float[]){ - JSONArray.writeJSONString((float[])value, out); - return; - } - - if(value instanceof double[]){ - JSONArray.writeJSONString((double[])value, out); - return; - } - - if(value instanceof boolean[]){ - JSONArray.writeJSONString((boolean[])value, out); - return; - } - - if(value instanceof char[]){ - JSONArray.writeJSONString((char[])value, out); - return; - } - - if(value instanceof Object[]){ - JSONArray.writeJSONString((Object[])value, out); - return; - } - - out.write(value.toString()); - } - - /** - * Convert an object to JSON text. - *

- * If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly. - *

- * DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with - * "this" as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead. - * - * @see org.json.simple.JSONObject#toJSONString(Map) - * @see org.json.simple.JSONArray#toJSONString(List) - * - * @param value - * @return JSON text, or "null" if value is null or it's an NaN or an INF number. - */ - public static String toJSONString(Object value){ - final StringWriter writer = new StringWriter(); - - try{ - writeJSONString(value, writer); - return writer.toString(); - } catch(IOException e){ - // This should never happen for a StringWriter - throw new RuntimeException(e); - } - } - - /** - * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). - * @param s - * @return - */ - public static String escape(String s){ - if(s==null) - return null; - StringBuffer sb = new StringBuffer(); - escape(s, sb); - return sb.toString(); - } - - /** - * @param s - Must not be null. - * @param sb - */ - static void escape(String s, StringBuffer sb) { - final int len = s.length(); - for(int i=0;i='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')){ - String ss=Integer.toHexString(ch); - sb.append("\\u"); - for(int k=0;k<4-ss.length();k++){ - sb.append('0'); - } - sb.append(ss.toUpperCase()); - } - else{ - sb.append(ch); - } - } - }//for - } - -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContainerFactory.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContainerFactory.java deleted file mode 100644 index 667bd28..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContainerFactory.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.godaddy.sonar.org.json.simple.parser; - -import java.util.List; -import java.util.Map; - -/** - * Container factory for creating containers for JSON object and JSON array. - * - * @see org.json.simple.parser.JSONParser#parse(java.io.Reader, ContainerFactory) - * - * @author FangYidong - */ -public interface ContainerFactory { - /** - * @return A Map instance to store JSON object, or null if you want to use org.json.simple.JSONObject. - */ - Map createObjectContainer(); - - /** - * @return A List instance to store JSON array, or null if you want to use org.json.simple.JSONArray. - */ - List creatArrayContainer(); -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContentHandler.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContentHandler.java deleted file mode 100644 index 619300d..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ContentHandler.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.godaddy.sonar.org.json.simple.parser; - -import java.io.IOException; - -/** - * A simplified and stoppable SAX-like content handler for stream processing of JSON text. - * - * @see org.xml.sax.ContentHandler - * @see org.json.simple.parser.JSONParser#parse(java.io.Reader, ContentHandler, boolean) - * - * @author FangYidong - */ -public interface ContentHandler { - /** - * Receive notification of the beginning of JSON processing. - * The parser will invoke this method only once. - * - * @throws ParseException - * - JSONParser will stop and throw the same exception to the caller when receiving this exception. - */ - void startJSON() throws ParseException, IOException; - - /** - * Receive notification of the end of JSON processing. - * - * @throws ParseException - */ - void endJSON() throws ParseException, IOException; - - /** - * Receive notification of the beginning of a JSON object. - * - * @return false if the handler wants to stop parsing after return. - * @throws ParseException - * - JSONParser will stop and throw the same exception to the caller when receiving this exception. - * @see #endJSON - */ - boolean startObject() throws ParseException, IOException; - - /** - * Receive notification of the end of a JSON object. - * - * @return false if the handler wants to stop parsing after return. - * @throws ParseException - * - * @see #startObject - */ - boolean endObject() throws ParseException, IOException; - - /** - * Receive notification of the beginning of a JSON object entry. - * - * @param key - Key of a JSON object entry. - * - * @return false if the handler wants to stop parsing after return. - * @throws ParseException - * - * @see #endObjectEntry - */ - boolean startObjectEntry(String key) throws ParseException, IOException; - - /** - * Receive notification of the end of the value of previous object entry. - * - * @return false if the handler wants to stop parsing after return. - * @throws ParseException - * - * @see #startObjectEntry - */ - boolean endObjectEntry() throws ParseException, IOException; - - /** - * Receive notification of the beginning of a JSON array. - * - * @return false if the handler wants to stop parsing after return. - * @throws ParseException - * - * @see #endArray - */ - boolean startArray() throws ParseException, IOException; - - /** - * Receive notification of the end of a JSON array. - * - * @return false if the handler wants to stop parsing after return. - * @throws ParseException - * - * @see #startArray - */ - boolean endArray() throws ParseException, IOException; - - /** - * Receive notification of the JSON primitive values: - * java.lang.String, - * java.lang.Number, - * java.lang.Boolean - * null - * - * @param value - Instance of the following: - * java.lang.String, - * java.lang.Number, - * java.lang.Boolean - * null - * - * @return false if the handler wants to stop parsing after return. - * @throws ParseException - */ - boolean primitive(Object value) throws ParseException, IOException; - -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/JSONParser.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/JSONParser.java deleted file mode 100644 index c91a907..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/parser/JSONParser.java +++ /dev/null @@ -1,533 +0,0 @@ -/* - * $Id: JSONParser.java,v 1.1 2006/04/15 14:10:48 platform Exp $ - * Created on 2006-4-15 - */ -package com.godaddy.sonar.org.json.simple.parser; - -import com.godaddy.sonar.org.json.simple.JSONArray; -import com.godaddy.sonar.org.json.simple.JSONObject; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - - -/** - * Parser for JSON text. Please note that JSONParser is NOT thread-safe. - * - * @author FangYidong - */ -public class JSONParser { - public static final int S_INIT=0; - public static final int S_IN_FINISHED_VALUE=1;//string,number,boolean,null,object,array - public static final int S_IN_OBJECT=2; - public static final int S_IN_ARRAY=3; - public static final int S_PASSED_PAIR_KEY=4; - public static final int S_IN_PAIR_VALUE=5; - public static final int S_END=6; - public static final int S_IN_ERROR=-1; - - private LinkedList handlerStatusStack; - private Yylex lexer = new Yylex((Reader)null); - private Yytoken token = null; - private int status = S_INIT; - - private int peekStatus(LinkedList statusStack){ - if(statusStack.size()==0) - return -1; - Integer status=(Integer)statusStack.getFirst(); - return status.intValue(); - } - - /** - * Reset the parser to the initial state without resetting the underlying reader. - * - */ - public void reset(){ - token = null; - status = S_INIT; - handlerStatusStack = null; - } - - /** - * Reset the parser to the initial state with a new character reader. - * - * @param in - The new character reader. - * @throws IOException - * @throws ParseException - */ - public void reset(Reader in){ - lexer.yyreset(in); - reset(); - } - - /** - * @return The position of the beginning of the current token. - */ - public int getPosition(){ - return lexer.getPosition(); - } - - public Object parse(String s) throws ParseException{ - return parse(s, (ContainerFactory)null); - } - - public Object parse(String s, ContainerFactory containerFactory) throws ParseException{ - StringReader in=new StringReader(s); - try{ - return parse(in, containerFactory); - } - catch(IOException ie){ - /* - * Actually it will never happen. - */ - throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie); - } - } - - public Object parse(Reader in) throws IOException, ParseException{ - return parse(in, (ContainerFactory)null); - } - - /** - * Parse JSON text into java object from the input source. - * - * @param in - * @param containerFactory - Use this factory to createyour own JSON object and JSON array containers. - * @return Instance of the following: - * org.json.simple.JSONObject, - * org.json.simple.JSONArray, - * java.lang.String, - * java.lang.Number, - * java.lang.Boolean, - * null - * - * @throws IOException - * @throws ParseException - */ - public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException{ - reset(in); - LinkedList statusStack = new LinkedList(); - LinkedList valueStack = new LinkedList(); - - try{ - do{ - nextToken(); - switch(status){ - case S_INIT: - switch(token.type){ - case Yytoken.TYPE_VALUE: - status=S_IN_FINISHED_VALUE; - statusStack.addFirst(new Integer(status)); - valueStack.addFirst(token.value); - break; - case Yytoken.TYPE_LEFT_BRACE: - status=S_IN_OBJECT; - statusStack.addFirst(new Integer(status)); - valueStack.addFirst(createObjectContainer(containerFactory)); - break; - case Yytoken.TYPE_LEFT_SQUARE: - status=S_IN_ARRAY; - statusStack.addFirst(new Integer(status)); - valueStack.addFirst(createArrayContainer(containerFactory)); - break; - default: - status=S_IN_ERROR; - }//inner switch - break; - - case S_IN_FINISHED_VALUE: - if(token.type==Yytoken.TYPE_EOF) - return valueStack.removeFirst(); - else - throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); - - case S_IN_OBJECT: - switch(token.type){ - case Yytoken.TYPE_COMMA: - break; - case Yytoken.TYPE_VALUE: - if(token.value instanceof String){ - String key=(String)token.value; - valueStack.addFirst(key); - status=S_PASSED_PAIR_KEY; - statusStack.addFirst(new Integer(status)); - } - else{ - status=S_IN_ERROR; - } - break; - case Yytoken.TYPE_RIGHT_BRACE: - if(valueStack.size()>1){ - statusStack.removeFirst(); - valueStack.removeFirst(); - status=peekStatus(statusStack); - } - else{ - status=S_IN_FINISHED_VALUE; - } - break; - default: - status=S_IN_ERROR; - break; - }//inner switch - break; - - case S_PASSED_PAIR_KEY: - switch(token.type){ - case Yytoken.TYPE_COLON: - break; - case Yytoken.TYPE_VALUE: - statusStack.removeFirst(); - String key=(String)valueStack.removeFirst(); - Map parent=(Map)valueStack.getFirst(); - parent.put(key,token.value); - status=peekStatus(statusStack); - break; - case Yytoken.TYPE_LEFT_SQUARE: - statusStack.removeFirst(); - key=(String)valueStack.removeFirst(); - parent=(Map)valueStack.getFirst(); - List newArray=createArrayContainer(containerFactory); - parent.put(key,newArray); - status=S_IN_ARRAY; - statusStack.addFirst(new Integer(status)); - valueStack.addFirst(newArray); - break; - case Yytoken.TYPE_LEFT_BRACE: - statusStack.removeFirst(); - key=(String)valueStack.removeFirst(); - parent=(Map)valueStack.getFirst(); - Map newObject=createObjectContainer(containerFactory); - parent.put(key,newObject); - status=S_IN_OBJECT; - statusStack.addFirst(new Integer(status)); - valueStack.addFirst(newObject); - break; - default: - status=S_IN_ERROR; - } - break; - - case S_IN_ARRAY: - switch(token.type){ - case Yytoken.TYPE_COMMA: - break; - case Yytoken.TYPE_VALUE: - List val=(List)valueStack.getFirst(); - val.add(token.value); - break; - case Yytoken.TYPE_RIGHT_SQUARE: - if(valueStack.size()>1){ - statusStack.removeFirst(); - valueStack.removeFirst(); - status=peekStatus(statusStack); - } - else{ - status=S_IN_FINISHED_VALUE; - } - break; - case Yytoken.TYPE_LEFT_BRACE: - val=(List)valueStack.getFirst(); - Map newObject=createObjectContainer(containerFactory); - val.add(newObject); - status=S_IN_OBJECT; - statusStack.addFirst(new Integer(status)); - valueStack.addFirst(newObject); - break; - case Yytoken.TYPE_LEFT_SQUARE: - val=(List)valueStack.getFirst(); - List newArray=createArrayContainer(containerFactory); - val.add(newArray); - status=S_IN_ARRAY; - statusStack.addFirst(new Integer(status)); - valueStack.addFirst(newArray); - break; - default: - status=S_IN_ERROR; - }//inner switch - break; - case S_IN_ERROR: - throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); - }//switch - if(status==S_IN_ERROR){ - throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); - } - }while(token.type!=Yytoken.TYPE_EOF); - } - catch(IOException ie){ - throw ie; - } - - throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); - } - - private void nextToken() throws ParseException, IOException{ - token = lexer.yylex(); - if(token == null) - token = new Yytoken(Yytoken.TYPE_EOF, null); - } - - private Map createObjectContainer(ContainerFactory containerFactory){ - if(containerFactory == null) - return new JSONObject(); - Map m = containerFactory.createObjectContainer(); - - if(m == null) - return new JSONObject(); - return m; - } - - private List createArrayContainer(ContainerFactory containerFactory){ - if(containerFactory == null) - return new JSONArray(); - List l = containerFactory.creatArrayContainer(); - - if(l == null) - return new JSONArray(); - return l; - } - - public void parse(String s, ContentHandler contentHandler) throws ParseException{ - parse(s, contentHandler, false); - } - - public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException{ - StringReader in=new StringReader(s); - try{ - parse(in, contentHandler, isResume); - } - catch(IOException ie){ - /* - * Actually it will never happen. - */ - throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie); - } - } - - public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException{ - parse(in, contentHandler, false); - } - - /** - * Stream processing of JSON text. - * - * @see ContentHandler - * - * @param in - * @param contentHandler - * @param isResume - Indicates if it continues previous parsing operation. - * If set to true, resume parsing the old stream, and parameter 'in' will be ignored. - * If this method is called for the first time in this instance, isResume will be ignored. - * - * @throws IOException - * @throws ParseException - */ - public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException{ - if(!isResume){ - reset(in); - handlerStatusStack = new LinkedList(); - } - else{ - if(handlerStatusStack == null){ - isResume = false; - reset(in); - handlerStatusStack = new LinkedList(); - } - } - - LinkedList statusStack = handlerStatusStack; - - try{ - do{ - switch(status){ - case S_INIT: - contentHandler.startJSON(); - nextToken(); - switch(token.type){ - case Yytoken.TYPE_VALUE: - status=S_IN_FINISHED_VALUE; - statusStack.addFirst(new Integer(status)); - if(!contentHandler.primitive(token.value)) - return; - break; - case Yytoken.TYPE_LEFT_BRACE: - status=S_IN_OBJECT; - statusStack.addFirst(new Integer(status)); - if(!contentHandler.startObject()) - return; - break; - case Yytoken.TYPE_LEFT_SQUARE: - status=S_IN_ARRAY; - statusStack.addFirst(new Integer(status)); - if(!contentHandler.startArray()) - return; - break; - default: - status=S_IN_ERROR; - }//inner switch - break; - - case S_IN_FINISHED_VALUE: - nextToken(); - if(token.type==Yytoken.TYPE_EOF){ - contentHandler.endJSON(); - status = S_END; - return; - } - else{ - status = S_IN_ERROR; - throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); - } - - case S_IN_OBJECT: - nextToken(); - switch(token.type){ - case Yytoken.TYPE_COMMA: - break; - case Yytoken.TYPE_VALUE: - if(token.value instanceof String){ - String key=(String)token.value; - status=S_PASSED_PAIR_KEY; - statusStack.addFirst(new Integer(status)); - if(!contentHandler.startObjectEntry(key)) - return; - } - else{ - status=S_IN_ERROR; - } - break; - case Yytoken.TYPE_RIGHT_BRACE: - if(statusStack.size()>1){ - statusStack.removeFirst(); - status=peekStatus(statusStack); - } - else{ - status=S_IN_FINISHED_VALUE; - } - if(!contentHandler.endObject()) - return; - break; - default: - status=S_IN_ERROR; - break; - }//inner switch - break; - - case S_PASSED_PAIR_KEY: - nextToken(); - switch(token.type){ - case Yytoken.TYPE_COLON: - break; - case Yytoken.TYPE_VALUE: - statusStack.removeFirst(); - status=peekStatus(statusStack); - if(!contentHandler.primitive(token.value)) - return; - if(!contentHandler.endObjectEntry()) - return; - break; - case Yytoken.TYPE_LEFT_SQUARE: - statusStack.removeFirst(); - statusStack.addFirst(new Integer(S_IN_PAIR_VALUE)); - status=S_IN_ARRAY; - statusStack.addFirst(new Integer(status)); - if(!contentHandler.startArray()) - return; - break; - case Yytoken.TYPE_LEFT_BRACE: - statusStack.removeFirst(); - statusStack.addFirst(new Integer(S_IN_PAIR_VALUE)); - status=S_IN_OBJECT; - statusStack.addFirst(new Integer(status)); - if(!contentHandler.startObject()) - return; - break; - default: - status=S_IN_ERROR; - } - break; - - case S_IN_PAIR_VALUE: - /* - * S_IN_PAIR_VALUE is just a marker to indicate the end of an object entry, it doesn't proccess any token, - * therefore delay consuming token until next round. - */ - statusStack.removeFirst(); - status = peekStatus(statusStack); - if(!contentHandler.endObjectEntry()) - return; - break; - - case S_IN_ARRAY: - nextToken(); - switch(token.type){ - case Yytoken.TYPE_COMMA: - break; - case Yytoken.TYPE_VALUE: - if(!contentHandler.primitive(token.value)) - return; - break; - case Yytoken.TYPE_RIGHT_SQUARE: - if(statusStack.size()>1){ - statusStack.removeFirst(); - status=peekStatus(statusStack); - } - else{ - status=S_IN_FINISHED_VALUE; - } - if(!contentHandler.endArray()) - return; - break; - case Yytoken.TYPE_LEFT_BRACE: - status=S_IN_OBJECT; - statusStack.addFirst(new Integer(status)); - if(!contentHandler.startObject()) - return; - break; - case Yytoken.TYPE_LEFT_SQUARE: - status=S_IN_ARRAY; - statusStack.addFirst(new Integer(status)); - if(!contentHandler.startArray()) - return; - break; - default: - status=S_IN_ERROR; - }//inner switch - break; - - case S_END: - return; - - case S_IN_ERROR: - throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); - }//switch - if(status==S_IN_ERROR){ - throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); - } - }while(token.type!=Yytoken.TYPE_EOF); - } - catch(IOException ie){ - status = S_IN_ERROR; - throw ie; - } - catch(ParseException pe){ - status = S_IN_ERROR; - throw pe; - } - catch(RuntimeException re){ - status = S_IN_ERROR; - throw re; - } - catch(Error e){ - status = S_IN_ERROR; - throw e; - } - - status = S_IN_ERROR; - throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); - } -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ParseException.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/ParseException.java deleted file mode 100644 index 784a1f7..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/parser/ParseException.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.godaddy.sonar.org.json.simple.parser; - -/** - * ParseException explains why and where the error occurs in source JSON text. - * - * @author FangYidong - * - */ -public class ParseException extends Exception { - private static final long serialVersionUID = -7880698968187728547L; - - public static final int ERROR_UNEXPECTED_CHAR = 0; - public static final int ERROR_UNEXPECTED_TOKEN = 1; - public static final int ERROR_UNEXPECTED_EXCEPTION = 2; - - private int errorType; - private Object unexpectedObject; - private int position; - - public ParseException(int errorType){ - this(-1, errorType, null); - } - - public ParseException(int errorType, Object unexpectedObject){ - this(-1, errorType, unexpectedObject); - } - - public ParseException(int position, int errorType, Object unexpectedObject){ - this.position = position; - this.errorType = errorType; - this.unexpectedObject = unexpectedObject; - } - - public int getErrorType() { - return errorType; - } - - public void setErrorType(int errorType) { - this.errorType = errorType; - } - - /** - * @see org.json.simple.parser.JSONParser#getPosition() - * - * @return The character position (starting with 0) of the input where the error occurs. - */ - public int getPosition() { - return position; - } - - public void setPosition(int position) { - this.position = position; - } - - /** - * @see org.json.simple.parser.Yytoken - * - * @return One of the following base on the value of errorType: - * ERROR_UNEXPECTED_CHAR java.lang.Character - * ERROR_UNEXPECTED_TOKEN org.json.simple.parser.Yytoken - * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception - */ - public Object getUnexpectedObject() { - return unexpectedObject; - } - - public void setUnexpectedObject(Object unexpectedObject) { - this.unexpectedObject = unexpectedObject; - } - - public String getMessage() { - StringBuffer sb = new StringBuffer(); - - switch(errorType){ - case ERROR_UNEXPECTED_CHAR: - sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append("."); - break; - case ERROR_UNEXPECTED_TOKEN: - sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append("."); - break; - case ERROR_UNEXPECTED_EXCEPTION: - sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject); - break; - default: - sb.append("Unkown error at position ").append(position).append("."); - break; - } - return sb.toString(); - } -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yylex.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yylex.java deleted file mode 100644 index c9c463c..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yylex.java +++ /dev/null @@ -1,688 +0,0 @@ -/* The following code was generated by JFlex 1.4.2 */ - -package com.godaddy.sonar.org.json.simple.parser; - -class Yylex { - - /** This character denotes the end of file */ - public static final int YYEOF = -1; - - /** initial size of the lookahead buffer */ - private static final int ZZ_BUFFERSIZE = 16384; - - /** lexical states */ - public static final int YYINITIAL = 0; - public static final int STRING_BEGIN = 2; - - /** - * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l - * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l - * at the beginning of a line - * l is of the form l = 2*k, k a non negative integer - */ - private static final int ZZ_LEXSTATE[] = { - 0, 0, 1, 1 - }; - - /** - * Translates characters to character classes - */ - private static final String ZZ_CMAP_PACKED = - "\11\0\1\7\1\7\2\0\1\7\22\0\1\7\1\0\1\11\10\0"+ - "\1\6\1\31\1\2\1\4\1\12\12\3\1\32\6\0\4\1\1\5"+ - "\1\1\24\0\1\27\1\10\1\30\3\0\1\22\1\13\2\1\1\21"+ - "\1\14\5\0\1\23\1\0\1\15\3\0\1\16\1\24\1\17\1\20"+ - "\5\0\1\25\1\0\1\26\uff82\0"; - - /** - * Translates characters to character classes - */ - private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); - - /** - * Translates DFA states to action switch labels. - */ - private static final int [] ZZ_ACTION = zzUnpackAction(); - - private static final String ZZ_ACTION_PACKED_0 = - "\2\0\2\1\1\2\1\3\1\4\3\1\1\5\1\6"+ - "\1\7\1\10\1\11\1\12\1\13\1\14\1\15\5\0"+ - "\1\14\1\16\1\17\1\20\1\21\1\22\1\23\1\24"+ - "\1\0\1\25\1\0\1\25\4\0\1\26\1\27\2\0"+ - "\1\30"; - - private static int [] zzUnpackAction() { - int [] result = new int[45]; - int offset = 0; - offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); - return result; - } - - private static int zzUnpackAction(String packed, int offset, int [] result) { - int i = 0; /* index in packed string */ - int j = offset; /* index in unpacked array */ - int l = packed.length(); - while (i < l) { - int count = packed.charAt(i++); - int value = packed.charAt(i++); - do result[j++] = value; while (--count > 0); - } - return j; - } - - - /** - * Translates a state to a row index in the transition table - */ - private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); - - private static final String ZZ_ROWMAP_PACKED_0 = - "\0\0\0\33\0\66\0\121\0\154\0\207\0\66\0\242"+ - "\0\275\0\330\0\66\0\66\0\66\0\66\0\66\0\66"+ - "\0\363\0\u010e\0\66\0\u0129\0\u0144\0\u015f\0\u017a\0\u0195"+ - "\0\66\0\66\0\66\0\66\0\66\0\66\0\66\0\66"+ - "\0\u01b0\0\u01cb\0\u01e6\0\u01e6\0\u0201\0\u021c\0\u0237\0\u0252"+ - "\0\66\0\66\0\u026d\0\u0288\0\66"; - - private static int [] zzUnpackRowMap() { - int [] result = new int[45]; - int offset = 0; - offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); - return result; - } - - private static int zzUnpackRowMap(String packed, int offset, int [] result) { - int i = 0; /* index in packed string */ - int j = offset; /* index in unpacked array */ - int l = packed.length(); - while (i < l) { - int high = packed.charAt(i++) << 16; - result[j++] = high | packed.charAt(i++); - } - return j; - } - - /** - * The transition table of the DFA - */ - private static final int ZZ_TRANS [] = { - 2, 2, 3, 4, 2, 2, 2, 5, 2, 6, - 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, - 2, 10, 11, 12, 13, 14, 15, 16, 16, 16, - 16, 16, 16, 16, 16, 17, 18, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 4, 19, 20, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 20, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 5, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 16, 16, 16, 16, 16, 16, 16, - 16, -1, -1, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - -1, -1, -1, -1, -1, -1, -1, -1, 24, 25, - 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 33, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 34, 35, -1, -1, - 34, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 37, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 38, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 39, -1, 39, -1, 39, -1, -1, - -1, -1, -1, 39, 39, -1, -1, -1, -1, 39, - 39, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 33, -1, 20, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 20, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 35, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 38, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 40, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 41, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 42, -1, 42, -1, 42, - -1, -1, -1, -1, -1, 42, 42, -1, -1, -1, - -1, 42, 42, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, - -1, -1, 43, 43, -1, -1, -1, -1, 43, 43, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, - -1, 44, -1, 44, -1, -1, -1, -1, -1, 44, - 44, -1, -1, -1, -1, 44, 44, -1, -1, -1, - -1, -1, -1, -1, -1, - }; - - /* error codes */ - private static final int ZZ_UNKNOWN_ERROR = 0; - private static final int ZZ_NO_MATCH = 1; - private static final int ZZ_PUSHBACK_2BIG = 2; - - /* error messages for the codes above */ - private static final String ZZ_ERROR_MSG[] = { - "Unkown internal scanner error", - "Error: could not match input", - "Error: pushback value was too large" - }; - - /** - * ZZ_ATTRIBUTE[aState] contains the attributes of state aState - */ - private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); - - private static final String ZZ_ATTRIBUTE_PACKED_0 = - "\2\0\1\11\3\1\1\11\3\1\6\11\2\1\1\11"+ - "\5\0\10\11\1\0\1\1\1\0\1\1\4\0\2\11"+ - "\2\0\1\11"; - - private static int [] zzUnpackAttribute() { - int [] result = new int[45]; - int offset = 0; - offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); - return result; - } - - private static int zzUnpackAttribute(String packed, int offset, int [] result) { - int i = 0; /* index in packed string */ - int j = offset; /* index in unpacked array */ - int l = packed.length(); - while (i < l) { - int count = packed.charAt(i++); - int value = packed.charAt(i++); - do result[j++] = value; while (--count > 0); - } - return j; - } - - /** the input device */ - private java.io.Reader zzReader; - - /** the current state of the DFA */ - private int zzState; - - /** the current lexical state */ - private int zzLexicalState = YYINITIAL; - - /** this buffer contains the current text to be matched and is - the source of the yytext() string */ - private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; - - /** the textposition at the last accepting state */ - private int zzMarkedPos; - - /** the current text position in the buffer */ - private int zzCurrentPos; - - /** startRead marks the beginning of the yytext() string in the buffer */ - private int zzStartRead; - - /** endRead marks the last character in the buffer, that has been read - from input */ - private int zzEndRead; - - /** number of newlines encountered up to the start of the matched text */ - private int yyline; - - /** the number of characters up to the start of the matched text */ - private int yychar; - - /** - * the number of characters from the last newline up to the start of the - * matched text - */ - private int yycolumn; - - /** - * zzAtBOL == true <=> the scanner is currently at the beginning of a line - */ - private boolean zzAtBOL = true; - - /** zzAtEOF == true <=> the scanner is at the EOF */ - private boolean zzAtEOF; - - /* user code: */ -private StringBuffer sb=new StringBuffer(); - -int getPosition(){ - return yychar; -} - - - - /** - * Creates a new scanner - * There is also a java.io.InputStream version of this constructor. - * - * @param in the java.io.Reader to read input from. - */ - Yylex(java.io.Reader in) { - this.zzReader = in; - } - - /** - * Creates a new scanner. - * There is also java.io.Reader version of this constructor. - * - * @param in the java.io.Inputstream to read input from. - */ - Yylex(java.io.InputStream in) { - this(new java.io.InputStreamReader(in)); - } - - /** - * Unpacks the compressed character translation table. - * - * @param packed the packed character translation table - * @return the unpacked character translation table - */ - private static char [] zzUnpackCMap(String packed) { - char [] map = new char[0x10000]; - int i = 0; /* index in packed string */ - int j = 0; /* index in unpacked array */ - while (i < 90) { - int count = packed.charAt(i++); - char value = packed.charAt(i++); - do map[j++] = value; while (--count > 0); - } - return map; - } - - - /** - * Refills the input buffer. - * - * @return false, iff there was new input. - * - * @exception java.io.IOException if any I/O-Error occurs - */ - private boolean zzRefill() throws java.io.IOException { - - /* first: make room (if you can) */ - if (zzStartRead > 0) { - System.arraycopy(zzBuffer, zzStartRead, - zzBuffer, 0, - zzEndRead-zzStartRead); - - /* translate stored positions */ - zzEndRead-= zzStartRead; - zzCurrentPos-= zzStartRead; - zzMarkedPos-= zzStartRead; - zzStartRead = 0; - } - - /* is the buffer big enough? */ - if (zzCurrentPos >= zzBuffer.length) { - /* if not: blow it up */ - char newBuffer[] = new char[zzCurrentPos*2]; - System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); - zzBuffer = newBuffer; - } - - /* finally: fill the buffer with new input */ - int numRead = zzReader.read(zzBuffer, zzEndRead, - zzBuffer.length-zzEndRead); - - if (numRead > 0) { - zzEndRead+= numRead; - return false; - } - // unlikely but not impossible: read 0 characters, but not at end of stream - if (numRead == 0) { - int c = zzReader.read(); - if (c == -1) { - return true; - } else { - zzBuffer[zzEndRead++] = (char) c; - return false; - } - } - - // numRead < 0 - return true; - } - - - /** - * Closes the input stream. - */ - public final void yyclose() throws java.io.IOException { - zzAtEOF = true; /* indicate end of file */ - zzEndRead = zzStartRead; /* invalidate buffer */ - - if (zzReader != null) - zzReader.close(); - } - - - /** - * Resets the scanner to read from a new input stream. - * Does not close the old reader. - * - * All internal variables are reset, the old input stream - * cannot be reused (internal buffer is discarded and lost). - * Lexical state is set to ZZ_INITIAL. - * - * @param reader the new input stream - */ - public final void yyreset(java.io.Reader reader) { - zzReader = reader; - zzAtBOL = true; - zzAtEOF = false; - zzEndRead = zzStartRead = 0; - zzCurrentPos = zzMarkedPos = 0; - yyline = yychar = yycolumn = 0; - zzLexicalState = YYINITIAL; - } - - - /** - * Returns the current lexical state. - */ - public final int yystate() { - return zzLexicalState; - } - - - /** - * Enters a new lexical state - * - * @param newState the new lexical state - */ - public final void yybegin(int newState) { - zzLexicalState = newState; - } - - - /** - * Returns the text matched by the current regular expression. - */ - public final String yytext() { - return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); - } - - - /** - * Returns the character at position pos from the - * matched text. - * - * It is equivalent to yytext().charAt(pos), but faster - * - * @param pos the position of the character to fetch. - * A value from 0 to yylength()-1. - * - * @return the character at position pos - */ - public final char yycharat(int pos) { - return zzBuffer[zzStartRead+pos]; - } - - - /** - * Returns the length of the matched text region. - */ - public final int yylength() { - return zzMarkedPos-zzStartRead; - } - - - /** - * Reports an error that occured while scanning. - * - * In a wellformed scanner (no or only correct usage of - * yypushback(int) and a match-all fallback rule) this method - * will only be called with things that "Can't Possibly Happen". - * If this method is called, something is seriously wrong - * (e.g. a JFlex bug producing a faulty scanner etc.). - * - * Usual syntax/scanner level error handling should be done - * in error fallback rules. - * - * @param errorCode the code of the errormessage to display - */ - private void zzScanError(int errorCode) { - String message; - try { - message = ZZ_ERROR_MSG[errorCode]; - } - catch (ArrayIndexOutOfBoundsException e) { - message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; - } - - throw new Error(message); - } - - - /** - * Pushes the specified amount of characters back into the input stream. - * - * They will be read again by then next call of the scanning method - * - * @param number the number of characters to be read again. - * This number must not be greater than yylength()! - */ - public void yypushback(int number) { - if ( number > yylength() ) - zzScanError(ZZ_PUSHBACK_2BIG); - - zzMarkedPos -= number; - } - - - /** - * Resumes scanning until the next regular expression is matched, - * the end of input is encountered or an I/O-Error occurs. - * - * @return the next token - * @exception java.io.IOException if any I/O-Error occurs - */ - public Yytoken yylex() throws java.io.IOException, ParseException { - int zzInput; - int zzAction; - - // cached fields: - int zzCurrentPosL; - int zzMarkedPosL; - int zzEndReadL = zzEndRead; - char [] zzBufferL = zzBuffer; - char [] zzCMapL = ZZ_CMAP; - - int [] zzTransL = ZZ_TRANS; - int [] zzRowMapL = ZZ_ROWMAP; - int [] zzAttrL = ZZ_ATTRIBUTE; - - while (true) { - zzMarkedPosL = zzMarkedPos; - - yychar+= zzMarkedPosL-zzStartRead; - - zzAction = -1; - - zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; - - zzState = ZZ_LEXSTATE[zzLexicalState]; - - - zzForAction: { - while (true) { - - if (zzCurrentPosL < zzEndReadL) - zzInput = zzBufferL[zzCurrentPosL++]; - else if (zzAtEOF) { - zzInput = YYEOF; - break zzForAction; - } - else { - // store back cached positions - zzCurrentPos = zzCurrentPosL; - zzMarkedPos = zzMarkedPosL; - boolean eof = zzRefill(); - // get translated positions and possibly new buffer - zzCurrentPosL = zzCurrentPos; - zzMarkedPosL = zzMarkedPos; - zzBufferL = zzBuffer; - zzEndReadL = zzEndRead; - if (eof) { - zzInput = YYEOF; - break zzForAction; - } - else { - zzInput = zzBufferL[zzCurrentPosL++]; - } - } - int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; - if (zzNext == -1) break zzForAction; - zzState = zzNext; - - int zzAttributes = zzAttrL[zzState]; - if ( (zzAttributes & 1) == 1 ) { - zzAction = zzState; - zzMarkedPosL = zzCurrentPosL; - if ( (zzAttributes & 8) == 8 ) break zzForAction; - } - - } - } - - // store back cached position - zzMarkedPos = zzMarkedPosL; - - switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { - case 11: - { sb.append(yytext()); - } - case 25: break; - case 4: - { sb = null; sb = new StringBuffer(); yybegin(STRING_BEGIN); - } - case 26: break; - case 16: - { sb.append('\b'); - } - case 27: break; - case 6: - { return new Yytoken(Yytoken.TYPE_RIGHT_BRACE,null); - } - case 28: break; - case 23: - { Boolean val=Boolean.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); - } - case 29: break; - case 22: - { return new Yytoken(Yytoken.TYPE_VALUE, null); - } - case 30: break; - case 13: - { yybegin(YYINITIAL);return new Yytoken(Yytoken.TYPE_VALUE, sb.toString()); - } - case 31: break; - case 12: - { sb.append('\\'); - } - case 32: break; - case 21: - { Double val=Double.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); - } - case 33: break; - case 1: - { throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, new Character(yycharat(0))); - } - case 34: break; - case 8: - { return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE,null); - } - case 35: break; - case 19: - { sb.append('\r'); - } - case 36: break; - case 15: - { sb.append('/'); - } - case 37: break; - case 10: - { return new Yytoken(Yytoken.TYPE_COLON,null); - } - case 38: break; - case 14: - { sb.append('"'); - } - case 39: break; - case 5: - { return new Yytoken(Yytoken.TYPE_LEFT_BRACE,null); - } - case 40: break; - case 17: - { sb.append('\f'); - } - case 41: break; - case 24: - { try{ - int ch=Integer.parseInt(yytext().substring(2),16); - sb.append((char)ch); - } - catch(Exception e){ - throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e); - } - } - case 42: break; - case 20: - { sb.append('\t'); - } - case 43: break; - case 7: - { return new Yytoken(Yytoken.TYPE_LEFT_SQUARE,null); - } - case 44: break; - case 2: - { Long val=Long.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); - } - case 45: break; - case 18: - { sb.append('\n'); - } - case 46: break; - case 9: - { return new Yytoken(Yytoken.TYPE_COMMA,null); - } - case 47: break; - case 3: - { - } - case 48: break; - default: - if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { - zzAtEOF = true; - return null; - } - else { - zzScanError(ZZ_NO_MATCH); - } - } - } - } - - -} diff --git a/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yytoken.java b/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yytoken.java deleted file mode 100644 index f703b32..0000000 --- a/src/main/java/com/godaddy/sonar/org/json/simple/parser/Yytoken.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * $Id: Yytoken.java,v 1.1 2006/04/15 14:10:48 platform Exp $ - * Created on 2006-4-15 - */ -package com.godaddy.sonar.org.json.simple.parser; - -/** - * @author FangYidong - */ -public class Yytoken { - public static final int TYPE_VALUE=0;//JSON primitive value: string,number,boolean,null - public static final int TYPE_LEFT_BRACE=1; - public static final int TYPE_RIGHT_BRACE=2; - public static final int TYPE_LEFT_SQUARE=3; - public static final int TYPE_RIGHT_SQUARE=4; - public static final int TYPE_COMMA=5; - public static final int TYPE_COLON=6; - public static final int TYPE_EOF=-1;//end of file - - public int type=0; - public Object value=null; - - public Yytoken(int type,Object value){ - this.type=type; - this.value=value; - } - - public String toString(){ - StringBuffer sb = new StringBuffer(); - switch(type){ - case TYPE_VALUE: - sb.append("VALUE(").append(value).append(")"); - break; - case TYPE_LEFT_BRACE: - sb.append("LEFT BRACE({)"); - break; - case TYPE_RIGHT_BRACE: - sb.append("RIGHT BRACE(})"); - break; - case TYPE_LEFT_SQUARE: - sb.append("LEFT SQUARE([)"); - break; - case TYPE_RIGHT_SQUARE: - sb.append("RIGHT SQUARE(])"); - break; - case TYPE_COMMA: - sb.append("COMMA(,)"); - break; - case TYPE_COLON: - sb.append("COLON(:)"); - break; - case TYPE_EOF: - sb.append("END OF FILE"); - break; - } - return sb.toString(); - } -} diff --git a/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovJsonParserImpl.java b/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovJsonParserImpl.java index 446e0db..b87485c 100755 --- a/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovJsonParserImpl.java +++ b/src/main/java/com/godaddy/sonar/ruby/simplecovrcov/SimpleCovRcovJsonParserImpl.java @@ -6,9 +6,9 @@ import java.util.Collection; import java.util.Map; -import com.godaddy.sonar.org.json.simple.JSONArray; -import com.godaddy.sonar.org.json.simple.JSONObject; -import com.godaddy.sonar.org.json.simple.JSONValue; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; From 183c1b4e3f653d9db191768804baad1843f87141 Mon Sep 17 00:00:00 2001 From: AKASH V Date: Wed, 4 May 2016 19:53:45 +0530 Subject: [PATCH 04/10] moving rules to com.godaddy.sonar.ruby.metricfu.rules --- src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java | 6 +++--- .../ruby/{rules => metricfu}/MetricfuRoodiYamlParser.java | 3 ++- .../{rules => metricfu}/MetricfuRoodiYamlParserImpl.java | 4 ++-- .../sonar/ruby/{ => metricfu}/rules/RoodiProblem.java | 2 +- .../godaddy/sonar/ruby/{ => metricfu}/rules/RoodiRule.java | 4 +--- .../sonar/ruby/{ => metricfu}/rules/RoodiRuleParser.java | 4 +--- .../sonar/ruby/{ => metricfu}/rules/RoodiSensor.java | 6 ++---- .../sonar/ruby/{ => metricfu}/rules/RubyRuleRepository.java | 5 +---- .../com/godaddy/sonar/ruby/{ => metricfu}/rules/rules.yml | 0 9 files changed, 13 insertions(+), 21 deletions(-) rename src/main/java/com/godaddy/sonar/ruby/{rules => metricfu}/MetricfuRoodiYamlParser.java (76%) rename src/main/java/com/godaddy/sonar/ruby/{rules => metricfu}/MetricfuRoodiYamlParserImpl.java (95%) rename src/main/java/com/godaddy/sonar/ruby/{ => metricfu}/rules/RoodiProblem.java (88%) rename src/main/java/com/godaddy/sonar/ruby/{ => metricfu}/rules/RoodiRule.java (73%) rename src/main/java/com/godaddy/sonar/ruby/{ => metricfu}/rules/RoodiRuleParser.java (95%) rename src/main/java/com/godaddy/sonar/ruby/{ => metricfu}/rules/RoodiSensor.java (96%) rename src/main/java/com/godaddy/sonar/ruby/{ => metricfu}/rules/RubyRuleRepository.java (88%) rename src/main/resources/com/godaddy/sonar/ruby/{ => metricfu}/rules/rules.yml (100%) diff --git a/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java b/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java index 2c2aec1..ae55182 100755 --- a/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java +++ b/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java @@ -4,9 +4,9 @@ import java.util.Arrays; import java.util.List; -import com.godaddy.sonar.ruby.rules.MetricfuRoodiYamlParserImpl; -import com.godaddy.sonar.ruby.rules.RoodiSensor; -import com.godaddy.sonar.ruby.rules.RubyRuleRepository; +import com.godaddy.sonar.ruby.metricfu.MetricfuRoodiYamlParserImpl; +import com.godaddy.sonar.ruby.metricfu.rules.RoodiSensor; +import com.godaddy.sonar.ruby.metricfu.rules.RubyRuleRepository; import org.sonar.api.CoreProperties; import org.sonar.api.Properties; import org.sonar.api.PropertyType; diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParser.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParser.java similarity index 76% rename from src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParser.java rename to src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParser.java index 37110b1..9647273 100644 --- a/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParser.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParser.java @@ -1,5 +1,6 @@ -package com.godaddy.sonar.ruby.rules; +package com.godaddy.sonar.ruby.metricfu; +import com.godaddy.sonar.ruby.metricfu.rules.RoodiProblem; import org.sonar.api.BatchExtension; import java.io.File; diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParserImpl.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParserImpl.java similarity index 95% rename from src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParserImpl.java rename to src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParserImpl.java index 9c93734..be518ee 100644 --- a/src/main/java/com/godaddy/sonar/ruby/rules/MetricfuRoodiYamlParserImpl.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParserImpl.java @@ -1,5 +1,6 @@ -package com.godaddy.sonar.ruby.rules; +package com.godaddy.sonar.ruby.metricfu; +import com.godaddy.sonar.ruby.metricfu.rules.RoodiProblem; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import org.slf4j.Logger; @@ -7,7 +8,6 @@ import org.yaml.snakeyaml.Yaml; import java.io.*; -import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiProblem.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiProblem.java similarity index 88% rename from src/main/java/com/godaddy/sonar/ruby/rules/RoodiProblem.java rename to src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiProblem.java index 594d38b..ed3e394 100644 --- a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiProblem.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiProblem.java @@ -1,4 +1,4 @@ -package com.godaddy.sonar.ruby.rules; +package com.godaddy.sonar.ruby.metricfu.rules; /** * Created by akash.v on 27/04/16. diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRule.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRule.java similarity index 73% rename from src/main/java/com/godaddy/sonar/ruby/rules/RoodiRule.java rename to src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRule.java index a28ae6e..c2d5cab 100644 --- a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRule.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRule.java @@ -1,6 +1,4 @@ -package com.godaddy.sonar.ruby.rules; - -import org.sonar.api.rule.Severity; +package com.godaddy.sonar.ruby.metricfu.rules; /** * Created by akash.v on 02/05/16. diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRuleParser.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java similarity index 95% rename from src/main/java/com/godaddy/sonar/ruby/rules/RoodiRuleParser.java rename to src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java index bbb9984..db46170 100644 --- a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiRuleParser.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java @@ -1,4 +1,4 @@ -package com.godaddy.sonar.ruby.rules; +package com.godaddy.sonar.ruby.metricfu.rules; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -6,8 +6,6 @@ import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.util.List; import java.util.Map; import java.util.regex.Pattern; diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiSensor.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java similarity index 96% rename from src/main/java/com/godaddy/sonar/ruby/rules/RoodiSensor.java rename to src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java index e8582ed..eb7c335 100644 --- a/src/main/java/com/godaddy/sonar/ruby/rules/RoodiSensor.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java @@ -1,6 +1,7 @@ -package com.godaddy.sonar.ruby.rules; +package com.godaddy.sonar.ruby.metricfu.rules; import com.godaddy.sonar.ruby.RubyPlugin; +import com.godaddy.sonar.ruby.metricfu.MetricfuRoodiYamlParser; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,12 +13,9 @@ import org.sonar.api.component.ResourcePerspectives; import org.sonar.api.config.Settings; import org.sonar.api.issue.Issuable; -import org.sonar.api.issue.Issue; -import org.sonar.api.measures.Measure; import org.sonar.api.resources.Project; import org.sonar.api.rule.RuleKey; import org.sonar.api.scan.filesystem.PathResolver; -import org.sonar.batch.protocol.input.Metric; import java.io.File; import java.io.FileNotFoundException; diff --git a/src/main/java/com/godaddy/sonar/ruby/rules/RubyRuleRepository.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RubyRuleRepository.java similarity index 88% rename from src/main/java/com/godaddy/sonar/ruby/rules/RubyRuleRepository.java rename to src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RubyRuleRepository.java index 1666962..7d478cd 100644 --- a/src/main/java/com/godaddy/sonar/ruby/rules/RubyRuleRepository.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RubyRuleRepository.java @@ -1,11 +1,8 @@ -package com.godaddy.sonar.ruby.rules; +package com.godaddy.sonar.ruby.metricfu.rules; import com.godaddy.sonar.ruby.core.Ruby; -import org.apache.commons.codec.Charsets; import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rule.Severity; import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.server.rule.RulesDefinitionXmlLoader; import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/resources/com/godaddy/sonar/ruby/rules/rules.yml b/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml similarity index 100% rename from src/main/resources/com/godaddy/sonar/ruby/rules/rules.yml rename to src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml From 4a0290989470b5246c7ad92f9f629d1caeafd3ab Mon Sep 17 00:00:00 2001 From: AKASH V Date: Fri, 6 May 2016 15:09:53 +0530 Subject: [PATCH 05/10] using lucene for rule key lookup --- pom.xml | 15 ++++ .../metricfu/MetricfuComplexitySensor.java | 1 - .../metricfu/rules/InMemoryRuleStore.java | 90 +++++++++++++++++++ .../sonar/ruby/metricfu/rules/RoodiRule.java | 2 +- .../ruby/metricfu/rules/RoodiRuleParser.java | 24 ++--- .../sonar/ruby/metricfu/rules/rules.yml | 16 ++-- 6 files changed, 123 insertions(+), 25 deletions(-) create mode 100644 src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java diff --git a/pom.xml b/pom.xml index 860317c..3f0651f 100755 --- a/pom.xml +++ b/pom.xml @@ -29,6 +29,21 @@ sonar-plugin-api ${sonar.buildVersion} + + org.apache.lucene + lucene-analyzers-common + 4.2.0 + + + org.apache.lucene + lucene-queryparser + 4.2.0 + + + org.apache.lucene + lucene-core + 4.2.0 + org.codehaus.sonar sonar-batch diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensor.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensor.java index 3873fed..0d0cde7 100755 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensor.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuComplexitySensor.java @@ -90,7 +90,6 @@ private void analyzeFile(InputFile inputFile, SensorContext sensorContext, File // on that file if (functions.isEmpty() || functions.size() == 0 || functions == null) { - System.out.println("returning..... function"+ functions + " File"+ inputFile); return; } diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java new file mode 100644 index 0000000..693226d --- /dev/null +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java @@ -0,0 +1,90 @@ +package com.godaddy.sonar.ruby.metricfu.rules; + + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.core.SimpleAnalyzer; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.*; +import org.apache.lucene.document.Field.Store; +import org.apache.lucene.index.*; +import org.apache.lucene.queries.mlt.MoreLikeThis; +import org.apache.lucene.queryparser.classic.ParseException; +import org.apache.lucene.queryparser.classic.QueryParser; +import org.apache.lucene.search.*; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.LockObtainFailedException; +import org.apache.lucene.store.RAMDirectory; +import org.apache.lucene.util.Version; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + + +/** + * Created by akash.v on 06/05/16. + */ +public class InMemoryRuleStore { + + private Directory ramDirectory; + private StandardAnalyzer analyzer; + private IndexWriterConfig config; + private IndexWriter indexWriter; + + public InMemoryRuleStore(){ + analyzer = new StandardAnalyzer(Version.LUCENE_42); + config = new IndexWriterConfig(Version.LUCENE_42, analyzer); + config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); + + ramDirectory = new RAMDirectory(); + + } + + public void addRule(String ruleId, String discription){ + try { + indexWriter = new IndexWriter(ramDirectory, config); + FieldType type = new FieldType(); + type.setIndexed(true); + type.setStored(true); + type.setStoreTermVectors(true); + Document doc = new Document(); + doc.add(new StringField("ruleId", ruleId, Store.YES)); + doc.add(new Field("description", discription, type)); + indexWriter.addDocument(doc); + indexWriter.commit(); + indexWriter.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String findRule(String searchForSimilar) { + IndexReader reader = null; + try { + reader = DirectoryReader.open(ramDirectory); + IndexSearcher indexSearcher = new IndexSearcher(reader); + + MoreLikeThis mlt = new MoreLikeThis(reader); + mlt.setAnalyzer(analyzer); + mlt.setFieldNames(new String[]{"description", "ruleId"}); + mlt.setMinTermFreq(0); + mlt.setMinDocFreq(0); + + Reader sReader = new StringReader(searchForSimilar); + Query query = mlt.like(sReader, null); + TopDocs topDocs = indexSearcher.search(query, 1); + + if(topDocs.scoreDocs.length > 0) + return indexSearcher.doc(topDocs.scoreDocs[0].doc).get("ruleId"); + + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } + +} + diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRule.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRule.java index c2d5cab..7092087 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRule.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRule.java @@ -9,5 +9,5 @@ public class RoodiRule { String description; String severity; String debtRemediationFunctionOffset; - String regex; + String match; } diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java index db46170..5afb4bd 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java @@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; +import java.io.IOException; import java.util.List; import java.util.Map; import java.util.regex.Pattern; @@ -18,12 +19,14 @@ public class RoodiRuleParser { private static final String RULES_FILE = "rules.yml"; private Yaml yaml; private List roodiRules; - private Map regexIdMap; + InMemoryRuleStore inMemoryRuleStore = new InMemoryRuleStore(); + private static final Logger LOG = LoggerFactory .getLogger(RoodiRuleParser.class); public RoodiRuleParser(){ yaml = new Yaml(); + parse(); } public List parse(){ @@ -34,7 +37,7 @@ public List parse(){ for(Map p: (List>) yaml.load(getClass().getResourceAsStream(RULES_FILE))){ roodiRules.add(ruleFor(p)); } - createMap(); + updateRuleStore(); } return roodiRules; @@ -45,7 +48,7 @@ private RoodiRule ruleFor(Map p) { r.key = (String) p.get("key"); r.description = (String) p.get("description"); r.name = (String) p.get("name"); - r.regex = (String) p.get("regex"); + r.match = (String) p.get("match"); r.severity = (String) p.get("severity"); r.debtRemediationFunctionOffset = (String) p.get("debtRemediationFunctionOffset"); @@ -53,23 +56,14 @@ private RoodiRule ruleFor(Map p) { } - private void createMap() { - regexIdMap = Maps.newConcurrentMap(); + private void updateRuleStore() { for(RoodiRule r : roodiRules){ - regexIdMap.put(Pattern.compile(r.regex), r.key); + inMemoryRuleStore.addRule(r.key, r.match); } } public String getKey(String discription){ - if(regexIdMap == null){ - parse(); - } - for(Pattern p : regexIdMap.keySet()){ - if(p.matcher(discription).find()){ - return regexIdMap.get(p); - } - } - return null; + return inMemoryRuleStore.findRule(discription); } public static void main(String[] args) { diff --git a/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml b/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml index de9fdb7..ce674e8 100644 --- a/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml +++ b/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml @@ -6,7 +6,7 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 0h 5min" - regex: "Case statement is missing an else clause." + match: "Case statement is missing an else clause." - key: "R0002" name: "Class should have 300 or less lines." @@ -14,7 +14,7 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 2h 5min" - regex: "Class \".*\" has .* lines. It should have 300 or less" + match: "Class \"abc\" has 123 lines. It should have 300 or less" - key: "R0003" name: "Block cyclomatic complexity should be 4 or less" @@ -22,7 +22,7 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 0h 20min" - regex: "Block cyclomatic complexity is .* It should be 4 or less." + match: "Block cyclomatic complexity is 123 It should be 4 or less." - key: "R0004" name: "Method cyclomatic complexity should be 8 or less." @@ -30,7 +30,7 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 0h 20min" - regex: "Method name \".*\" cyclomatic complexity is .* It should be 8 or less." + match: "Method name \"abc\" cyclomatic complexity is 123 It should be 8 or less." - key: "R0005" name: "Don't use 'for' loops. Use Enumerable.each instead." @@ -38,7 +38,7 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 0h 10min" - regex: "Don't use 'for' loops. Use Enumerable.each instead." + match: "Don't use 'for' loops. Use Enumerable.each instead." - key: "R0006" name: "Method should have 20 or less lines." @@ -46,7 +46,7 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 0h 12min" - regex: "Method \".*\" has .* lines. It should have 20 or less." + match: "Method \"abc\" has abc lines. It should have 20 or less." - key: "R0007" name: "Method name should match pattern /^[_a-z<>=\\[\\]|+-\\/\\*`]+[_a-z0-9_<>=~@\\[\\]]*[=!\\?]?$/" @@ -54,7 +54,7 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 0h 5min" - regex: "Method name \".*\" should match pattern .*" + match: "Method name \"abc\" should match pattern abc" - key: "R0008" name: "Method should have 5 or less parameters." @@ -62,5 +62,5 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 0h 15min" - regex: "Method name \".*\" has .* parameters. It should have 5 or less" + match: "Method name \"abc\" has 123 parameters. It should have 5 or less" From bed16617a4bb52309108db5013fb741f49219b8a Mon Sep 17 00:00:00 2001 From: AKASH V Date: Mon, 9 May 2016 13:16:46 +0530 Subject: [PATCH 06/10] Moving lookup logic to roodiSensor --- pom.xml | 6 +++--- .../com/godaddy/sonar/ruby/RubyPlugin.java | 20 +++++++++++------- .../metricfu/MetricfuRoodiYamlParserImpl.java | 5 ----- .../metricfu/rules/InMemoryRuleStore.java | 6 +++--- .../ruby/metricfu/rules/RoodiRuleParser.java | 21 ------------------- .../ruby/metricfu/rules/RoodiSensor.java | 12 +++++++---- .../metricfu/rules/RubyRuleRepository.java | 9 ++++---- .../sonar/ruby/metricfu/rules/rules.yml | 2 +- 8 files changed, 32 insertions(+), 49 deletions(-) diff --git a/pom.xml b/pom.xml index 3f0651f..dec4d4f 100755 --- a/pom.xml +++ b/pom.xml @@ -32,17 +32,17 @@ org.apache.lucene lucene-analyzers-common - 4.2.0 + 4.3.0 org.apache.lucene lucene-queryparser - 4.2.0 + 4.3.0 org.apache.lucene lucene-core - 4.2.0 + 4.3.0 org.codehaus.sonar diff --git a/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java b/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java index ae55182..8809583 100755 --- a/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java +++ b/src/main/java/com/godaddy/sonar/ruby/RubyPlugin.java @@ -5,6 +5,7 @@ import java.util.List; import com.godaddy.sonar.ruby.metricfu.MetricfuRoodiYamlParserImpl; +import com.godaddy.sonar.ruby.metricfu.rules.RoodiRuleParser; import com.godaddy.sonar.ruby.metricfu.rules.RoodiSensor; import com.godaddy.sonar.ruby.metricfu.rules.RubyRuleRepository; import org.sonar.api.CoreProperties; @@ -35,14 +36,14 @@ public final class RubyPlugin extends SonarPlugin public List getExtensions() { List extensions = new ArrayList(); - extensions.add(RubyRuleRepository.class); - extensions.add(Ruby.class); - extensions.add(SimpleCovRcovSensor.class); - extensions.add(SimpleCovRcovJsonParserImpl.class); - extensions.add(MetricfuComplexityYamlParserImpl.class); - extensions.add(RubySourceCodeColorizer.class); - extensions.add(RubySensor.class); - extensions.add(MetricfuComplexitySensor.class); + + extensions.add(Ruby.class); + extensions.add(SimpleCovRcovSensor.class); + extensions.add(SimpleCovRcovJsonParserImpl.class); + extensions.add(MetricfuComplexityYamlParserImpl.class); + extensions.add(RubySourceCodeColorizer.class); + extensions.add(RubySensor.class); + extensions.add(MetricfuComplexitySensor.class); // Profiles extensions.add(SonarWayProfile.class); @@ -80,6 +81,9 @@ public List getExtensions() .options(options) .build(); extensions.add(ComplexityMetric); + + extensions.add(RubyRuleRepository.class); + extensions.add(MetricfuRoodiYamlParserImpl.class); extensions.add(RoodiSensor.class); // extensions.add(MetricfuDuplicationSensor.class); diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParserImpl.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParserImpl.java index be518ee..6956c9c 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParserImpl.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/MetricfuRoodiYamlParserImpl.java @@ -49,9 +49,4 @@ public List parse(String fileName, File resultsFile) throws FileNo private RoodiProblem getProblem(Map problem) { return new RoodiProblem(problem.get(":file"), Integer.parseInt(problem.get(":line")), problem.get(":problem")); } - - public static void main(String[] args) throws FileNotFoundException { - MetricfuRoodiYamlParser parser= new MetricfuRoodiYamlParserImpl(); - List problems = parser.parse("app/builders/fulfillment_model_builder_factory.rb", new File("/Users/akash.v/Sources/office/symphony/tmp/metric_fu/report.yml")); - } } diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java index 693226d..19c9c2a 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java @@ -34,8 +34,8 @@ public class InMemoryRuleStore { private IndexWriter indexWriter; public InMemoryRuleStore(){ - analyzer = new StandardAnalyzer(Version.LUCENE_42); - config = new IndexWriterConfig(Version.LUCENE_42, analyzer); + analyzer = new StandardAnalyzer(Version.LUCENE_43); + config = new IndexWriterConfig(Version.LUCENE_43, analyzer); config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); ramDirectory = new RAMDirectory(); @@ -68,7 +68,7 @@ public String findRule(String searchForSimilar) { MoreLikeThis mlt = new MoreLikeThis(reader); mlt.setAnalyzer(analyzer); - mlt.setFieldNames(new String[]{"description", "ruleId"}); + mlt.setFieldNames(new String[]{"description"}); mlt.setMinTermFreq(0); mlt.setMinDocFreq(0); diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java index 5afb4bd..fb7c673 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiRuleParser.java @@ -1,15 +1,12 @@ package com.godaddy.sonar.ruby.metricfu.rules; import com.google.common.collect.Lists; -import com.google.common.collect.Maps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; -import java.io.IOException; import java.util.List; import java.util.Map; -import java.util.regex.Pattern; /** * Created by akash.v on 02/05/16. @@ -19,7 +16,6 @@ public class RoodiRuleParser { private static final String RULES_FILE = "rules.yml"; private Yaml yaml; private List roodiRules; - InMemoryRuleStore inMemoryRuleStore = new InMemoryRuleStore(); private static final Logger LOG = LoggerFactory .getLogger(RoodiRuleParser.class); @@ -37,7 +33,6 @@ public List parse(){ for(Map p: (List>) yaml.load(getClass().getResourceAsStream(RULES_FILE))){ roodiRules.add(ruleFor(p)); } - updateRuleStore(); } return roodiRules; @@ -54,20 +49,4 @@ private RoodiRule ruleFor(Map p) { return r; } - - - private void updateRuleStore() { - for(RoodiRule r : roodiRules){ - inMemoryRuleStore.addRule(r.key, r.match); - } - } - - public String getKey(String discription){ - return inMemoryRuleStore.findRule(discription); - } - - public static void main(String[] args) { - RoodiRuleParser roodiRuleParser = new RoodiRuleParser(); - roodiRuleParser.parse(); - } } diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java index eb7c335..8451d5d 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java @@ -37,6 +37,7 @@ public class RoodiSensor implements Sensor { private String reportPath = "tmp/metric_fu/report.yml"; private PathResolver pathResolver; private RoodiRuleParser roodiRuleParser; + private InMemoryRuleStore inMemoryRuleStore; public RoodiSensor(Settings settings, FileSystem fs, ActiveRules activeRules, ResourcePerspectives resourcePerspectives, PathResolver pathResolver, MetricfuRoodiYamlParser metricfuRoodiYamlParser) { @@ -47,11 +48,14 @@ public RoodiSensor(Settings settings, FileSystem fs, ActiveRules activeRules, Re this.pathResolver = pathResolver; String reportpath_prop = settings.getString(RubyPlugin.METRICFU_REPORT_PATH_PROPERTY); this.metricfuRoodiYamlParser = metricfuRoodiYamlParser; + inMemoryRuleStore = new InMemoryRuleStore(); if (null != reportpath_prop) { this.reportPath = reportpath_prop; } - roodiRuleParser = new RoodiRuleParser(); - roodiRuleParser.parse(); + this.roodiRuleParser = new RoodiRuleParser(); + for(RoodiRule roodiRule: roodiRuleParser.parse()){ + inMemoryRuleStore.addRule(roodiRule.key, roodiRule.match); + } } @@ -82,8 +86,8 @@ public void analyse(Project project, SensorContext sensorContext) { private void analyzeFile(InputFile inputFile, SensorContext sensorContext, File report) throws FileNotFoundException { List issues= metricfuRoodiYamlParser.parse(inputFile.relativePath(), report); for (RoodiProblem roodiProblem: issues) { - if (roodiRuleParser.getKey(roodiProblem.problem) != null) { - RuleKey ruleKey = RuleKey.of(RubyRuleRepository.REPOSITORY_KEY, roodiRuleParser.getKey(roodiProblem.problem)); + if (inMemoryRuleStore.findRule(roodiProblem.problem) != null) { + RuleKey ruleKey = RuleKey.of(RubyRuleRepository.REPOSITORY_KEY, inMemoryRuleStore.findRule(roodiProblem.problem)); LOG.info("Rule Key: {}", ruleKey); Issuable issuable = resourcePerspectives.as(Issuable.class, inputFile); if (issuable != null) { diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RubyRuleRepository.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RubyRuleRepository.java index 7d478cd..fa9d007 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RubyRuleRepository.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RubyRuleRepository.java @@ -14,7 +14,11 @@ public class RubyRuleRepository implements RulesDefinition { public static final String REPOSITORY_NAME = "Roodi"; public static final String REPOSITORY_KEY = REPOSITORY_NAME; - RoodiRuleParser roodiRuleParser = new RoodiRuleParser(); + RoodiRuleParser roodiRuleParser; + + public RubyRuleRepository(){ + this.roodiRuleParser = new RoodiRuleParser(); + } @ParametersAreNonnullByDefault public void define(Context context) { @@ -22,8 +26,6 @@ public void define(Context context) { .createRepository(REPOSITORY_KEY, Ruby.KEY) .setName(REPOSITORY_NAME); - roodiRuleParser = new RoodiRuleParser(); - for(RoodiRule rule : roodiRuleParser.parse()){ NewRule newRule = repository.createRule(rule.key) .setName(rule.name) @@ -34,7 +36,6 @@ public void define(Context context) { .setDebtRemediationFunction(newRule.debtRemediationFunctions().constantPerIssue(rule.debtRemediationFunctionOffset)); } - repository.done(); } } diff --git a/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml b/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml index ce674e8..447857c 100644 --- a/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml +++ b/src/main/resources/com/godaddy/sonar/ruby/metricfu/rules/rules.yml @@ -46,7 +46,7 @@ severity: "MINOR" status: "READY" debtRemediationFunctionOffset: "0d 0h 12min" - match: "Method \"abc\" has abc lines. It should have 20 or less." + match: "Method \"abc\" has 12 lines. It should have 20 or less." - key: "R0007" name: "Method name should match pattern /^[_a-z<>=\\[\\]|+-\\/\\*`]+[_a-z0-9_<>=~@\\[\\]]*[=!\\?]?$/" From e524b3c1203b2f28d6c13f7aceb59570c37658fa Mon Sep 17 00:00:00 2001 From: AKASH V Date: Mon, 9 May 2016 13:32:04 +0530 Subject: [PATCH 07/10] closing ramDirectory and streams after analysis --- .../ruby/metricfu/rules/InMemoryRuleStore.java | 18 ++++++++++++++---- .../sonar/ruby/metricfu/rules/RoodiSensor.java | 2 ++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java index 19c9c2a..aa309f4 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/InMemoryRuleStore.java @@ -32,10 +32,11 @@ public class InMemoryRuleStore { private StandardAnalyzer analyzer; private IndexWriterConfig config; private IndexWriter indexWriter; + private IndexReader reader; public InMemoryRuleStore(){ analyzer = new StandardAnalyzer(Version.LUCENE_43); - config = new IndexWriterConfig(Version.LUCENE_43, analyzer); + config = new IndexWriterConfig(Version.LUCENE_43 , analyzer); config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); ramDirectory = new RAMDirectory(); @@ -61,9 +62,10 @@ public void addRule(String ruleId, String discription){ } public String findRule(String searchForSimilar) { - IndexReader reader = null; try { - reader = DirectoryReader.open(ramDirectory); + if(reader ==null){ + reader = DirectoryReader.open(ramDirectory); + } IndexSearcher indexSearcher = new IndexSearcher(reader); MoreLikeThis mlt = new MoreLikeThis(reader); @@ -75,7 +77,6 @@ public String findRule(String searchForSimilar) { Reader sReader = new StringReader(searchForSimilar); Query query = mlt.like(sReader, null); TopDocs topDocs = indexSearcher.search(query, 1); - if(topDocs.scoreDocs.length > 0) return indexSearcher.doc(topDocs.scoreDocs[0].doc).get("ruleId"); @@ -86,5 +87,14 @@ public String findRule(String searchForSimilar) { return null; } + public void close() { + try { + reader.close(); + ramDirectory.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java index 8451d5d..4e82ce1 100644 --- a/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java +++ b/src/main/java/com/godaddy/sonar/ruby/metricfu/rules/RoodiSensor.java @@ -79,6 +79,8 @@ public void analyse(Project project, SensorContext sensorContext) { } catch (Exception e) { LOG.error("Can not analyze the file " + inputFile.absolutePath() + " for issues", e); + } finally { + inMemoryRuleStore.close(); } } } From b6ef3561656d58b02ff65a7c49d897cc75924240 Mon Sep 17 00:00:00 2001 From: AKASH V Date: Mon, 9 May 2016 15:20:00 +0530 Subject: [PATCH 08/10] adding .idea to gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index b9e6089..8be16ef 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ target/ META-INF/ bin/ build.properties - +.idea/ +*.iml From b8480538e5414755732d0b95dbb5a132a5c54433 Mon Sep 17 00:00:00 2001 From: AKASH V Date: Tue, 7 Jun 2016 18:56:33 +0530 Subject: [PATCH 09/10] updating credits --- README.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.md b/README.md index 014e524..af492aa 100644 --- a/README.md +++ b/README.md @@ -31,11 +31,7 @@ this will run all metrics. At the very least, Saikuro/Cane and Hotspots metrics * Code Violations ##Giving Credit -The github project [pica/ruby-sonar-plugin](https://github.com/pica/ruby-sonar-plugin), is where the ruby-sonar-plugin started, rather than reinvent the wheel, we thought it better to enhance it. -We used that plugin as a starting point for basic stats, then, updated the references to their latest versions and added additional metrics like line-by-line code coverage and code complexity. - -We referenced the [javascript sonar plugin](https://github.com/SonarCommunity/sonar-javascript) and the [php sonar plugin](https://github.com/SonarCommunity/sonar-php) for complexity and coverage implementation. -Our complexity sensor and code coverage sensor borrow heavily from the javascript plugin's equivalent sensors. +This is forked from GoDaddy-Hosting/ruby-sonar-plugin.git, enhanced it by adding sensors for design violations provides by roodi. ##Tool Versions This plugin has been tested with the following dependency versions From c7207dccad0817ff8d6a35d0623ea692a661b8fc Mon Sep 17 00:00:00 2001 From: AKASH V Date: Tue, 7 Jun 2016 19:03:27 +0530 Subject: [PATCH 10/10] updating readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af492aa..cf0db1b 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ this will run all metrics. At the very least, Saikuro/Cane and Hotspots metrics * Code Violations ##Giving Credit -This is forked from GoDaddy-Hosting/ruby-sonar-plugin.git, enhanced it by adding sensors for design violations provides by roodi. +This is forked from GoDaddy-Hosting/ruby-sonar-plugin.git, enhanced it by adding sensors for design violations provides by roodi. Fixed bugs to make it compatible with different types of simplecov-rcov reports, populate complexity. ##Tool Versions This plugin has been tested with the following dependency versions