Displaying differences for changeset
 
display as  

.hgtags

@@ -1,1 +1,2 @@
 4e4c3a75625cb24ee80556f49a68a76075bc47c9 0.1
+e225aaa0088fb0cb94331bb9a4cdf85c853815a4 0.2

nbproject/ant-deploy.xml

 

nbproject/build-impl.xml

 

nbproject/build-impl.xml~

 

nbproject/project.properties

 

nbproject/project.xml

 

src/java/c/PostGIS.java

@@ -27,7 +27,6 @@
     static final Logger logger = Logger.getLogger(PostGIS.class.getName());
 
     //private java.sql.Connection conn;
-
     private static PostGIS instance;
     private static int currentConnection = 0;
     private static java.sql.Connection[] connections;
@@ -39,13 +38,15 @@
         public String file_path;
         public String file_name;
 
+
         @Override
         public String toString() {
             return "{" + id + "|" + file_path + "|" + file_name + "}";
         }
     }
-    
+
     public static class Soil {
+
         public String coFips;
         public String muSym;
         public String muKey;
@@ -74,8 +75,9 @@
         public double perWater = 0.0;
         public String perWaterUnits = "ton/acre/year";
     }
-    
+
     public static class StationResult {
+
         public String country;
         public String state;
         public String name;
@@ -84,20 +86,23 @@
         public String stationY;
         public double distance;
         public String elevation;
-        
+
+
         @Override
         public String toString() {
             return "{" + state + "|" + stationId + "|" + stationX + "|" + stationY + "|" + elevation + "}";
         }
     }
-    
+
     public static class County {
+
         public String st_abbr;
         public String county_code;
         public String name;
         public String county_centroid_X;
         public String county_centroid_Y;
-        
+
+
         @Override
         public String toString() {
             return "{" + st_abbr + county_code + "|" + name + "|" + county_centroid_X + "|" + county_centroid_Y + "}";
@@ -116,6 +121,7 @@
         return instance;
     }
 
+
     PostGIS() throws Exception {
         Class.forName("org.postgresql.Driver");
         //conn = DriverManager.getConnection(PG_URL, "postgres", "postgres");
@@ -124,36 +130,28 @@
         int pgChunks = Config.getInt("pg.chunks", DEFAULT_PG_CHUNKS);
         int maxConnections = Config.getInt("pg.connpool", MAX_CONNECTIONS);
 
-        if (pgChunks == 0)
-        {
+        if (pgChunks == 0) {
             bUseChunks = false;
             logger.log(Level.INFO, "Not using postgresql database chunks.");
             logger.log(Level.INFO, "Initializing {0} db connections for connection pool.", maxConnections);
-            connections = new java.sql.Connection[maxConnections];
-            for (int i = 0;i< maxConnections;i++)
+            connections = new Connection[maxConnections];
+            for (int i = 0; i < maxConnections; i++) {
                 connections[i] = DriverManager.getConnection(PG_URL, "postgres", "postgres");
-        }
-        else
-        {
+            }
+        } else {
             bUseChunks = true;
             logger.log(Level.INFO, "Using postgresql database chunks!");
             logger.log(Level.INFO, "Initializing {0} db connections for each db chunk in the connection pool.", maxConnections);
             Collection<Config.PostgresChunk> coll = Config.getPostgresChunks();
-            for (Config.PostgresChunk pgc : coll)
-            {
+            for (Config.PostgresChunk pgc : coll) {
                 logger.log(Level.INFO, "Initializing db connection for pg db {0} for longitude " + pgc.getMinLong() + " to " + pgc.getMaxLong() + ".", pgc.getName());
-                
-                java.sql.Connection[] connections = new java.sql.Connection[maxConnections];
-                
-                for (int i = 0;i< maxConnections;i++)
-                {
-                    try
-                    {
+
+                Connection[] connections = new Connection[maxConnections];
+                for (int i = 0; i < maxConnections; i++) {
+                    try {
                         logger.info("default-db=" + PG_URL + " chunk-db=" + pgc.getName());
                         connections[i] = DriverManager.getConnection(pgc.getName(), "postgres", "postgres");
-                    }
-                    catch (SQLException sqle)
-                    {
+                    } catch (SQLException sqle) {
                         logger.log(Level.SEVERE, "Connection to db chunk " + i + " server has failed. Failing over to " + PG_URL);
                         // Failover to default db server
                         connections[i] = DriverManager.getConnection(PG_URL, "postgres", "postgres");
@@ -164,7 +162,7 @@
 
         }
     }
-    
+
 
     private FileQryResult findFile(String select, double lng) throws SQLException {
         // Statement s = createStatement(getConnection());
@@ -193,7 +191,8 @@
         return res;
     }
 
-    private double findDbl(String select, double lng, int colcnt) throws SQLException {
+
+    private String findCmzName(String select, double lng, int colcnt) throws SQLException {
         // Statement s = createStatement(getConnection());
         Statement s = createStatement(lng);
         logger.info("query sql=" + select);
@@ -207,14 +206,14 @@
         if (!r.next()) {
             //s.close();
             logger.severe("no result from find dbl query!");
-            return 0.0;
+            return "0";
         }
         logger.info("value=" + r.getDouble(1));
-        return r.getDouble(1);
+        return r.getString(1);
         //s.close();
     }
-    
-    
+
+
     private Collection<Soil> findPolygons(String select, double lng) throws SQLException {
         // Statement s = createStatement(getConnection());
         LinkedList<Soil> soilLst = new LinkedList<Soil>();
@@ -232,8 +231,7 @@
 //            logger.severe("no result from soil query!");
 //            return null;
 //        }
-        while (r.next())
-        {
+        while (r.next()) {
             Soil soil = new Soil();
             soil.coFips = r.getString(1);
             soil.muSym = r.getString(2);
@@ -244,7 +242,7 @@
             soil.compName = r.getString(7);
             soil.kffact = r.getString(8);
             soil.tfact = r.getDouble(9);
-            soil.slopeR= r.getDouble(10);
+            soil.slopeR = r.getDouble(10);
             soil.coKey = r.getString(11);
             soil.percentAoi = r.getDouble(12);
             soil.sizeAoi = r.getDouble(13);
@@ -258,7 +256,7 @@
         }
         r.close();
         s.close();
-        
+
 //        return findPolygon ("SELECT m.co_fips, m.musym, m.mukey, r2_path, r2_name, m.muname, " +
 //                            "m.compname, m.kffact, m.tfact, m.slope_r, m.cokey, " +
 //                            "st_area(st_intersection(" + polygon +
@@ -269,6 +267,7 @@
         return soilLst;
     }
 
+
     private Collection<Soil> findPolygonsWithSand(String select, double lng) throws SQLException {
         // Statement s = createStatement(getConnection());
         LinkedList<Soil> soilLst = new LinkedList<Soil>();
@@ -276,22 +275,18 @@
         logger.info("query sql=" + select);
         ResultSet r = s.executeQuery(select);
         SQLWarning warning = s.getWarnings();
-        
+
         //SQLWarning warning = r.getWarnings();
-        if (warning != null)
-        {
+        if (warning != null) {
             String sqlWarning = warning.getMessage();
             logger.info("**************************************************SQL WARNINGS! executing polygon with sand query");
             logger.info("**************************************************message=" + sqlWarning);
             logger.info("**************************************************sql-state=" + warning.getSQLState());
             logger.info("**************************************************error-code=" + warning.getErrorCode());
-            if ((sqlWarning != null) && (sqlWarning.length() > 0))
-            {
+            if ((sqlWarning != null) && (sqlWarning.length() > 0)) {
                 throw new SQLException(sqlWarning);
             }
-        }
-        else
-        {
+        } else {
             logger.info("**************************************************NO SQL WARNINGS! executing polygon with sand query");
         }
         int cols = r.getMetaData().getColumnCount();
@@ -305,8 +300,7 @@
 //            logger.severe("no result from soil query!");
 //            return null;
 //        }
-        while (r.next())
-        {
+        while (r.next()) {
             Soil soil = new Soil();
             soil.coFips = r.getString(1);
             soil.muSym = r.getString(2);
@@ -317,7 +311,7 @@
             soil.compName = r.getString(7);
             soil.kffact = r.getString(8);
             soil.tfact = r.getDouble(9);
-            soil.slopeR= r.getDouble(10);
+            soil.slopeR = r.getDouble(10);
             soil.coKey = r.getString(11);
             soil.sandtotalR = r.getDouble(12);
             soil.percentAoi = r.getDouble(13);
@@ -332,7 +326,7 @@
         }
         r.close();
         s.close();
-        
+
 //        return findPolygon ("SELECT m.co_fips, m.musym, m.mukey, r2_path, r2_name, m.muname, " +
 //                            "m.compname, m.kffact, m.tfact, m.slope_r, m.cokey, " +
 //                            "st_area(st_intersection(" + polygon +
@@ -343,7 +337,8 @@
         return soilLst;
     }
 
-        private Collection<Soil> findPolygonsWeps(String select, double lng) throws SQLException {
+
+    private Collection<Soil> findPolygonsWeps(String select, double lng) throws SQLException {
         // Statement s = createStatement(getConnection());
         LinkedList<Soil> soilLst = new LinkedList<Soil>();
         Statement s = createStatement(lng);
@@ -360,8 +355,7 @@
 //            logger.severe("no result from soil query!");
 //            return null;
 //        }
-        while (r.next())
-        {
+        while (r.next()) {
             Soil soil = new Soil();
             soil.coFips = r.getString(1);
             soil.muSym = r.getString(2);
@@ -372,7 +366,7 @@
             soil.compName = r.getString(7);
             soil.kffact = r.getString(8);
             soil.tfact = r.getDouble(9);
-            soil.slopeR= r.getDouble(10);
+            soil.slopeR = r.getDouble(10);
             soil.coKey = r.getString(11);
             //soil.sandtotalR = r.getDouble(12);
             soil.percentAoi = r.getDouble(12);
@@ -387,97 +381,85 @@
         }
         r.close();
         s.close();
-        
+
         return soilLst;
     }
 
-    
     // Look up table for slope length 
-    double[][] LightleWeesiesSlopeLength = {{0, .75, 100},
-                                            {.75,1.5,200},
-                                            {1.5,2.5,300},
-                                            {2.5,3.5,200},
-                                            {3.5,4.5,180},
-                                            {4.5,5.5,160},
-                                            {5.5,6.5,150},
-                                            {6.5,7.5,140},
-                                            {7.5,8.5,130},
-                                            {8.5,9.5,125},
-                                            {9.5,10.5,120},
-                                            {10.5,11.5,110},
-                                            {11.5,12.5,100},
-                                            {12.5,13.5,90},
-                                            {13.5,14.5,80},
-                                            {14.5,15.5,70},
-                                            {15.5,17.5,60},
-                                            {17.5,-1,50}};
-    double [][] PalouseSlopeLength = {{0,5.5,350},
-                                      {5.5,10.5,275},
-                                      {10.5,15.5,225},
-                                      {15.5,20.5,175},
-                                      {20.5,25.5,150},
-                                      {25.5,35.5,125},
-                                      {35.5,-1,100}};
+    static final double[][] LightleWeesiesSlopeLength = {{0, .75, 100},
+    {.75, 1.5, 200},
+    {1.5, 2.5, 300},
+    {2.5, 3.5, 200},
+    {3.5, 4.5, 180},
+    {4.5, 5.5, 160},
+    {5.5, 6.5, 150},
+    {6.5, 7.5, 140},
+    {7.5, 8.5, 130},
+    {8.5, 9.5, 125},
+    {9.5, 10.5, 120},
+    {10.5, 11.5, 110},
+    {11.5, 12.5, 100},
+    {12.5, 13.5, 90},
+    {13.5, 14.5, 80},
+    {14.5, 15.5, 70},
+    {15.5, 17.5, 60},
+    {17.5, -1, 50}};
+    static final double[][] PalouseSlopeLength = {{0, 5.5, 350},
+    {5.5, 10.5, 275},
+    {10.5, 15.5, 225},
+    {15.5, 20.5, 175},
+    {20.5, 25.5, 150},
+    {25.5, 35.5, 125},
+    {35.5, -1, 100}};
     static final List<String> PalouseAreas = Arrays.asList("ID607", "ID610", "OR021", "OR049", "OR055", "OR625",
-                                                           "OR667", "OR670", "OR673", "WA001", "WA021", "WA025",
-                                                           "WA043", "WA063", "WA071", "WA075", "WA603", "WA605",
-                                                           "WA613", "WA617", "WA623", "WA639", "WA676", "WA677");
-    
-    private double calculateSlopeR(double slope_r,
-                                   String areaSymbol)
-    {
-        double lengthR =0.0;
-        
+            "OR667", "OR670", "OR673", "WA001", "WA021", "WA025",
+            "WA043", "WA063", "WA071", "WA075", "WA603", "WA605",
+            "WA613", "WA617", "WA623", "WA639", "WA676", "WA677");
+
+
+    private double calculateSlopeR(double slope_r, String areaSymbol) {
+        double lengthR = 0.0;
+
         // Determines if the soil survey area is in the Palouse region
-        if (PalouseAreas.contains(areaSymbol))
-            // Use Palouse region slope length lookup table.
-            for (int i = 0; i < PalouseSlopeLength.length; i++)
-            {
-                if (PalouseSlopeLength[i][1] != -1)
-                    if ((slope_r >= PalouseSlopeLength[i][0]) && (slope_r < PalouseSlopeLength[i][1]))
-                    {
+        if (PalouseAreas.contains(areaSymbol)) // Use Palouse region slope length lookup table.
+        {
+            for (int i = 0; i < PalouseSlopeLength.length; i++) {
+                if (PalouseSlopeLength[i][1] != -1) {
+                    if ((slope_r >= PalouseSlopeLength[i][0]) && (slope_r < PalouseSlopeLength[i][1])) {
+                        lengthR = PalouseSlopeLength[i][2];
+                        break;
+                    } else if (slope_r >= PalouseSlopeLength[i][0]) {
                         lengthR = PalouseSlopeLength[i][2];
                         break;
                     }
-                else
-                    if (slope_r >= PalouseSlopeLength[i][0]) 
-                    {
-                        lengthR = PalouseSlopeLength[i][2];
-                        break;
-                    }
+                }
             }
-        else
-            // Uses Lightle and Weesies 10/1/1996 slope length lookup table (see documentation).
-            // Not for Palouse region
-            for (int i = 0; i < LightleWeesiesSlopeLength.length; i++)
-            {
+        } else // Uses Lightle and Weesies 10/1/1996 slope length lookup table (see documentation).
+        // Not for Palouse region
+        {
+            for (int i = 0; i < LightleWeesiesSlopeLength.length; i++) {
 //                logger.info("LightleWeesiesSlopeLength[" + i + "][0]=" + LightleWeesiesSlopeLength[i][0]);
 //                logger.info("LightleWeesiesSlopeLength[" + i + "][1]=" + LightleWeesiesSlopeLength[i][1]);
 //                logger.info("LightleWeesiesSlopeLength[" + i + "][2]=" + LightleWeesiesSlopeLength[i][2]);
 //                logger.info("slope_r=" + slope_r);
 //                logger.info("expr val=" + ((slope_r >= LightleWeesiesSlopeLength[i][0]) && (slope_r < LightleWeesiesSlopeLength[i][1])));
-                if (LightleWeesiesSlopeLength[i][1] != -1)
-                {
-                    if ((slope_r >= LightleWeesiesSlopeLength[i][0]) && (slope_r < LightleWeesiesSlopeLength[i][1]))
-                    {
+                if (LightleWeesiesSlopeLength[i][1] != -1) {
+                    if ((slope_r >= LightleWeesiesSlopeLength[i][0]) && (slope_r < LightleWeesiesSlopeLength[i][1])) {
                         lengthR = LightleWeesiesSlopeLength[i][2];
 //                        logger.info("grabbing value now from double check");
                         break;
                     }
-                }
-                else
-                {
-                    if (slope_r >= LightleWeesiesSlopeLength[i][0]) 
-                    {
-                        lengthR = LightleWeesiesSlopeLength[i][2];
+                } else if (slope_r >= LightleWeesiesSlopeLength[i][0]) {
+                    lengthR = LightleWeesiesSlopeLength[i][2];
 //                        logger.info("grabbing value now from SINGLE check");
-                        break;
-                    }
+                    break;
                 }
             }
+        }
         return lengthR;
     }
-    
+
+
     private boolean isValidCoord(String select, double lng) throws SQLException {
         //Statement s = createStatement(getConnection(lng));
         Statement s = createStatement(lng);
@@ -497,66 +479,76 @@
         return (sValidCoord.contains("t") ? true : false);
     }
 
+
     public boolean IsValidCliCoord(double lat, double lon) throws SQLException {
         return isValidCoord("SELECT IsValidCliCoord(" + lon + ", " + lat + ");", lon);
     }
 
+
     public boolean IsValidManCoord(double lat, double lon) throws SQLException {
         return isValidCoord("SELECT IsValidManCoord(" + lon + ", " + lat + ");", lon);
     }
 
+
     public boolean IsValidSoiCoord(double lat, double lon) throws SQLException {
         return isValidCoord("SELECT IsValidSoiCoord(" + lon + ", " + lat + ");", lon);
     }
 
+
     public boolean IsValidGisCoord(double lat, double lon) throws SQLException {
         return isValidCoord("SELECT IsValidGisCoord(" + lon + ", " + lat + ");", lon);
     }
-    
+
+
     public boolean IsValidRusle2Soil(double lat, double lon) throws SQLException {
-        FileQryResult fqr = findSoils(lat,lon);
-        if (fqr == null)
+        FileQryResult fqr = findSoils(lat, lon);
+        if (fqr == null) {
             return false;
-        else
+        } else {
             return true;
+        }
     }
-    
+
+
     public boolean IsValidWepsSoil(double lat, double lon) throws SQLException {
-        FileQryResult fqr = findSoilsWeps(lat,lon);
-        if (fqr == null)
+        FileQryResult fqr = findSoilsWeps(lat, lon);
+        if (fqr == null) {
             return false;
-        else
+        } else {
             return true;
+        }
     }
-    
-    
+
+
     // Determine if a point is within the wind station interpolation boundary for WEPS
     public boolean IsInInterpolateBoundary(double lat, double lon) throws SQLException {
         return isValidCoord("SELECT IsInInterpolateBoundary(" + lon + ", " + lat + ");", lon);
     }
 
+
     public FileQryResult findSoils(double lat, double lon) throws SQLException {
 // new query - mbound
-        return findFile ("SELECT m.musym, r2_path, r2_name FROM soil_geom AS g, map_soils AS m " +
-                     "WHERE ST_Within(ST_SetSRID(ST_Point(" + lon + "," + lat + "),4326), g.geometry) " +
-                     "AND g.mukey = m.mukey LIMIT 1;", lon);
+        return findFile("SELECT m.musym, r2_path, r2_name FROM soil_geom AS g, map_soils AS m "
+                + "WHERE ST_Within(ST_SetSRID(ST_Point(" + lon + "," + lat + "),4326), g.geometry) "
+                + "AND g.mukey = m.mukey LIMIT 1;", lon);
 // old query - had nasty join on a nested query - dbound
 //        return find("SELECT m.musym, r2_path, r2_name  FROM map_soils AS m, (SELECT musym FROM soil_geom  " +
 //                "WHERE Within(GeomFromText('POINT(" + lon + " " +
 //                lat + ")' ), geometry)) AS s WHERE m.musym = s.musym  LIMIT 1;");
     }
-    
-   
+
+
     //
     // fix me
     //
     // added string matching to fix a problem which requires us to regenerate r2 soils
     public FileQryResult findSoilsByCokey(String cokey, double lon) throws SQLException {
-        return findFile ("SELECT distinct m.musym, r2_path, r2_name FROM soil_geom AS g, map_soils AS m " +
-                     "WHERE m.cokey='" + cokey + "' " +
-                     "AND g.mukey = m.mukey and m.r2_name like '%' || m.compname || '%' limit 1; ", lon);
+        return findFile("SELECT distinct m.musym, r2_path, r2_name FROM soil_geom AS g, map_soils AS m "
+                + "WHERE m.cokey='" + cokey + "' "
+                + "AND g.mukey = m.mukey and m.r2_name like '%' || m.compname || '%' limit 1; ", lon);
     }
 
+
     // To calculate area in acres, we use the st_transform function to transform the intersection polygon into
     // a NAD83 Kansas projection which has units in feet (not degrees), which produces square feet.
     // We then divide by 43,560 sq ft to get acres.
@@ -564,58 +556,57 @@
         String polygon = "ST_PolygonFromText('POLYGON((-90.111 38.19,-90.110 38.19, -90.110 38.18,-90.111 38.18, -90.111 38.19))')";
         logger.info("The input polygon is=" + _polygon);
         logger.info("The input polygon len len =" + _polygon.length());
-        if ((_polygon == null) || (_polygon.length() < 1))
-        {
+        if ((_polygon == null) || (_polygon.length() < 1)) {
             _polygon = polygon;
             poly_longitude = -90.111;
         }
-        return findPolygons ("SELECT m.co_fips, m.musym, m.mukey, r2_path, r2_name, m.muname, " +
-                             "m.compname, m.kffact, m.tfact, m.slope_r, m.cokey, " +
-                             "st_area(st_intersection(" + _polygon +
-                             ", geometry)) / st_area(" + _polygon + 
-                             ")*100 as percentAoi," +
-                             "st_area(st_transform(st_intersection(" + _polygon + 
-                             ", geometry),3541))/43560 as sizeAoi " +
-                             "FROM soil_geom AS g, map_soils AS m " +
-                             "WHERE ST_Intersects(" + _polygon +  
-                             ", g.geometry) " +
-                             "AND g.mukey = m.mukey " +
-                             "and st_isvalid(geometry)='t' " +
-                             "and st_isvalid(" + _polygon + 
-                             ")='t';", poly_longitude);
+        return findPolygons("SELECT m.co_fips, m.musym, m.mukey, r2_path, r2_name, m.muname, "
+                + "m.compname, m.kffact, m.tfact, m.slope_r, m.cokey, "
+                + "st_area(st_intersection(" + _polygon
+                + ", geometry)) / st_area(" + _polygon
+                + ")*100 as percentAoi,"
+                + "st_area(st_transform(st_intersection(" + _polygon
+                + ", geometry),3541))/43560 as sizeAoi "
+                + "FROM soil_geom AS g, map_soils AS m "
+                + "WHERE ST_Intersects(" + _polygon
+                + ", g.geometry) "
+                + "AND g.mukey = m.mukey "
+                + "and st_isvalid(geometry)='t' "
+                + "and st_isvalid(" + _polygon
+                + ")='t';", poly_longitude);
     }
 
 // To calculate area in acres, we use the st_transform function to transform the intersection polygon into
     // a NAD83 Kansas projection which has units in feet (not degrees), which produces square feet.
     // We then divide by 43,560 sq ft to get acres.
+
     public Collection<Soil> findSoilsForPolygonWithSand(String _polygon, double poly_longitude) throws SQLException {
         String polygon = "ST_PolygonFromText('POLYGON((-90.111 38.19,-90.110 38.19, -90.110 38.18,-90.111 38.18, -90.111 38.19))')";
         logger.info("The input polygon is=" + _polygon);
         logger.info("The input polygon len len =" + _polygon.length());
-        if ((_polygon == null) || (_polygon.length() < 1))
-        {
+        if ((_polygon == null) || (_polygon.length() < 1)) {
             _polygon = polygon;
             poly_longitude = -90.111;
         }
         // added a fix "and m.r2_name like '%' || m.compname || '%'" to the end of this query because
         // soils have duplicate records presently, and need to be regenerated...
-        return findPolygonsWithSand ("SELECT m.co_fips, m.musym, m.mukey, r2_path, r2_name, m.muname, " +
-                             "m.compname, m.kffact, m.tfact, m.slope_r, m.cokey, m.sandtotal_r, " +
-                             "st_area(st_intersection(" + _polygon +
-                             ", geometry)) / st_area(" + _polygon + 
-                             ")*100 as percentAoi," +
-                             "st_area(st_transform(st_intersection(" + _polygon + 
-                             ", geometry),3541))/43560 as sizeAoi " +
-                             "FROM soil_geom AS g, map_soils AS m " +
-                             "WHERE ST_Intersects(" + _polygon +  
-                             ", g.geometry) " +
-                             "AND g.mukey = m.mukey " +
-                             "and st_isvalid(geometry)='t' " +
-                             "and st_isvalid(" + _polygon + 
-                             ")='t' and m.r2_name like '%' || m.compname || '%';", poly_longitude);
+        return findPolygonsWithSand("SELECT m.co_fips, m.musym, m.mukey, r2_path, r2_name, m.muname, "
+                + "m.compname, m.kffact, m.tfact, m.slope_r, m.cokey, m.sandtotal_r, "
+                + "st_area(st_intersection(" + _polygon
+                + ", geometry)) / st_area(" + _polygon
+                + ")*100 as percentAoi,"
+                + "st_area(st_transform(st_intersection(" + _polygon
+                + ", geometry),3541))/43560 as sizeAoi "
+                + "FROM soil_geom AS g, map_soils AS m "
+                + "WHERE ST_Intersects(" + _polygon
+                + ", g.geometry) "
+                + "AND g.mukey = m.mukey "
+                + "and st_isvalid(geometry)='t' "
+                + "and st_isvalid(" + _polygon
+                + ")='t' and m.r2_name like '%' || m.compname || '%';", poly_longitude);
     }
 
-    
+
 // To calculate area in acres, we use the st_transform function to transform the intersection polygon into
     // a NAD83 Kansas projection which has units in feet (not degrees), which produces square feet.
     // We then divide by 43,560 sq ft to get acres.
@@ -623,40 +614,41 @@
         String polygon = "ST_PolygonFromText('POLYGON((-90.111 38.19,-90.110 38.19, -90.110 38.18,-90.111 38.18, -90.111 38.19))')";
         logger.info("find weps soils - The input polygon is=" + _polygon);
         logger.info("The input polygon len len =" + _polygon.length());
-        if ((_polygon == null) || (_polygon.length() < 1))
-        {
+        if ((_polygon == null) || (_polygon.length() < 1)) {
             _polygon = polygon;
             poly_longitude = -90.111;
         }
-        return findPolygonsWeps("SELECT m.co_fips, m.musym, m.mukey, weps_path, weps_name, m.muname, " +
-                             "m.compname, m.kffact, m.tfact, m.slope_r, m.cokey, " +
-                             "st_area(st_intersection(" + _polygon +
-                             ", geometry)) / st_area(" + _polygon + 
-                             ")*100 as percentAoi," +
-                             "st_area(st_transform(st_intersection(" + _polygon + 
-                             ", geometry),3541))/43560 as sizeAoi " +
-                             "FROM soil_geom AS g, map_soils_weps AS m " +
-                             "WHERE ST_Intersects(" + _polygon +  
-                             ", g.geometry) " +
-                             "AND g.mukey = m.mukey " +
-                             "and st_isvalid(geometry)='t' " +
-                             "and st_isvalid(" + _polygon + 
-                             ")='t'", poly_longitude);
-    }
-    
-    
-    public FileQryResult findSoilsWeps(double lat, double lon) throws SQLException {
-        return findFile ("SELECT m.musym, weps_path, weps_name FROM soil_geom AS g, map_soils_weps AS m " +
-                     "WHERE ST_Within(ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326), g.geometry) " +
-                     "AND g.mukey = m.mukey LIMIT 1;", lon);
+        return findPolygonsWeps("SELECT m.co_fips, m.musym, m.mukey, weps_path, weps_name, m.muname, "
+                + "m.compname, m.kffact, m.tfact, m.slope_r, m.cokey, "
+                + "st_area(st_intersection(" + _polygon
+                + ", geometry)) / st_area(" + _polygon
+                + ")*100 as percentAoi,"
+                + "st_area(st_transform(st_intersection(" + _polygon
+                + ", geometry),3541))/43560 as sizeAoi "
+                + "FROM soil_geom AS g, map_soils_weps AS m "
+                + "WHERE ST_Intersects(" + _polygon
+                + ", g.geometry) "
+                + "AND g.mukey = m.mukey "
+                + "and st_isvalid(geometry)='t' "
+                + "and st_isvalid(" + _polygon
+                + ")='t'", poly_longitude);
     }
 
+
+    public FileQryResult findSoilsWeps(double lat, double lon) throws SQLException {
+        return findFile("SELECT m.musym, weps_path, weps_name FROM soil_geom AS g, map_soils_weps AS m "
+                + "WHERE ST_Within(ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326), g.geometry) "
+                + "AND g.mukey = m.mukey LIMIT 1;", lon);
+    }
+
+
     public FileQryResult findSoilsWepsByCokey(String cokey, double lon) throws SQLException {
-        return findFile ("SELECT m.musym, weps_path, weps_name FROM soil_geom AS g, map_soils_weps AS m " +
-                     "WHERE m.cokey='" + cokey + "' " +
-                     "AND g.mukey = m.mukey limit 1; ", lon);
+        return findFile("SELECT m.musym, weps_path, weps_name FROM soil_geom AS g, map_soils_weps AS m "
+                + "WHERE m.cokey='" + cokey + "' "
+                + "AND g.mukey = m.mukey limit 1; ", lon);
     }
-    
+
+
     //
     // 09-03-2013 WJL 
     // Added the "DESC" to sort values in order to favor REQ for IDAHO and RMOD for COLORADO
@@ -665,12 +657,12 @@
     public FileQryResult findClimate(double lat, double lon) throws SQLException {
 // new query - mbound
 // changed from using cnty_geom to cli_geom table
-        return findFile("SELECT m.co_fips, r2_path, r2_name  FROM cli_geom as g, map_climates AS m " +
-                    "WHERE ST_Within(ST_Point(" + lon + "," + lat + "), g.geometry) " +
-                    "AND g.co_fips = m.co_fips " + 
-                    "AND (g.ei_rang=m.ei_rang or g.ei_rang is null) " + 
-                    "ORDER BY m.r2_name desc " + 
-                    "LIMIT 1;", lon);
+        return findFile("SELECT m.co_fips, r2_path, r2_name  FROM cli_geom as g, map_climates AS m "
+                + "WHERE ST_Within(ST_Point(" + lon + "," + lat + "), g.geometry) "
+                + "AND g.co_fips = m.co_fips "
+                + "AND (g.ei_rang=m.ei_rang or g.ei_rang is null) "
+                + "ORDER BY m.r2_name desc "
+                + "LIMIT 1;", lon);
         // old
 //        return find("SELECT m.co_fips, r2_path, r2_name  FROM cli_geom as g, map_climates AS m " +
 //                    "WHERE ST_Within(ST_Point(" + lon + "," + lat + "), g.geometry) " +
@@ -681,11 +673,12 @@
 //                + "Within(GeomFromText( 'POINT(" + lon + " " + lat
 //                + ")' ), geometry)) AS g  WHERE m.co_fips = g.co_fips  LIMIT 1;");
     }
-    
+
+
     public County findCounty(double lat, double lon) throws SQLException {
-        String select = "SELECT m.st_abbr, m.co_numb, m.co_name FROM cnty_geom as g, cnty_data AS m " +
-                        "WHERE ST_Within(ST_Point(" + lon + "," + lat + "), g.geometry) " +
-                        "AND g.co_fips = m.co_fips;";
+        String select = "SELECT m.st_abbr, m.co_numb, m.co_name FROM cnty_geom as g, cnty_data AS m "
+                + "WHERE ST_Within(ST_Point(" + lon + "," + lat + "), g.geometry) "
+                + "AND g.co_fips = m.co_fips;";
         Statement s = createStatement(lon);
         logger.info("query sql=" + select);
         ResultSet r = s.executeQuery(select);
@@ -708,13 +701,14 @@
         logger.info("state abbr=" + cnty.st_abbr + " county code=" + cnty.county_code + " county name=" + cnty.name);
         return cnty;
     }
-    
+
+
     public StationResult findCligenStation(double lat, double lon) throws SQLException {
-        String select = "SELECT s.st_numb, s.station_id, st_x(point), st_y(point), s.elevation, ST_Distance(point, ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326)) as distance, s.name " +
-                        "FROM cligen_stations as s " +
-                        "order by distance " +
-                        "limit 1;";
-        
+        String select = "SELECT s.st_numb, s.station_id, st_x(point), st_y(point), s.elevation, ST_Distance(point, ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326)) as distance, s.name "
+                + "FROM cligen_stations as s "
+                + "order by distance "
+                + "limit 1;";
+
         Statement s = createStatement(lon);
         logger.info("query sql=" + select);
         ResultSet r = s.executeQuery(select);
@@ -734,18 +728,19 @@
         cligenst.stationY = r.getString(4);
         cligenst.elevation = r.getString(5);
         cligenst.distance = r.getDouble(6);
-        cligenst.name = (r.getString(7) != null ? r.getString(7): "NAME_UNAVAILABLE-LOOKUP-ID#" + r.getString(2));
+        cligenst.name = (r.getString(7) != null ? r.getString(7) : "NAME_UNAVAILABLE-LOOKUP-ID#" + r.getString(2));
         logger.info("state number=" + cligenst.state + " station id=" + cligenst.stationId + " station_X=" + cligenst.stationX + " stationY=" + cligenst.stationY + " name=" + cligenst.name);
         logger.info("distance in deg=" + cligenst.distance);
         return cligenst;
     }
-    
+
+
     public StationResult findWindgenStation(double lat, double lon) throws SQLException {
 
-        String select = "SELECT st_numb, station_id, ST_Distance(point, ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326)) as distance " +
-                        "FROM windgen_stations " +
-                        "order by distance " +
-                        "limit 1;";
+        String select = "SELECT st_numb, station_id, ST_Distance(point, ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326)) as distance "
+                + "FROM windgen_stations "
+                + "order by distance "
+                + "limit 1;";
         Statement s = createStatement(lon);
         logger.info("query sql=" + select);
         ResultSet r = s.executeQuery(select);
@@ -763,19 +758,20 @@
         StationResult windgenst = new StationResult();
         windgenst.state = r.getString(1);
         windgenst.stationId = r.getString(2);
-        windgenst.distance = r.getDouble(3);  
+        windgenst.distance = r.getDouble(3);
         //s.close(); 
         logger.info("state=" + windgenst.state);
         logger.info("station id=" + windgenst.stationId);
         logger.info("distance in deg=" + windgenst.distance);
         return windgenst;
-    }    
+    }
+
 
     public StationResult cliGeomIntersect(double lat, double lon) throws SQLException {
 
         String select = "select st, name, st_fips, c1, lat_dd, long_dd, elev_m "
-                      + "from weps_cli_geom "
-                      + "where ST_Intersects(geom,ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326));";
+                + "from weps_cli_geom "
+                + "where ST_Intersects(geom,ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326));";
         Statement s = createStatement(lon);
         logger.info("query sql=" + select);
         ResultSet r = s.executeQuery(select);
@@ -797,20 +793,19 @@
         clist.stationY = r.getString(5);
         clist.stationX = r.getString(6);
         clist.elevation = r.getString(7);
-         
+
         logger.info("state=" + clist.state);
         logger.info("cli station id=" + clist.stationId);
         logger.info("cli station name=" + clist.name);
         logger.info("cli station elev=" + clist.elevation);
         return clist;
-    }  
-    
-    
+    }
+
+
     public StationResult windGeomIntersect(double lat, double lon) throws SQLException {
-
         String select = "select lat_dd, long_dd, wban, cntry, st, name "
-                      + "from weps_wind_geom "
-                      + "where ST_Intersects(geom,ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326));";
+                + "from weps_wind_geom "
+                + "where ST_Intersects(geom,ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326));";
         Statement s = createStatement(lon);
         logger.info("query sql=" + select);
         ResultSet r = s.executeQuery(select);
@@ -832,19 +827,20 @@
         windgenst.country = r.getString(4);
         windgenst.state = r.getString(5);
         windgenst.name = r.getString(6);
-         
+
         logger.info("state=" + windgenst.state);
         logger.info("station id=" + windgenst.stationId);
         logger.info("station name=" + windgenst.name);
         return windgenst;
-    }  
-    
+    }
+
+
     // Uses a field lat long, to determine the county, then returns the county's centroid lat/long
     public County countyCentroid(double lat, double lon) throws SQLException {
 
         String select = "select state, county, name, ST_X(ST_Centroid(geom)) centroid_long, ST_Y(ST_Centroid(geom)) centroid_lat "
-                      + "from weps_county_geom "
-                      + "where ST_Intersects(geom,ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326));";
+                + "from weps_county_geom "
+                + "where ST_Intersects(geom,ST_GeomFromText('POINT(" + lon + " " + lat + ")',4326));";
         Statement s = createStatement(lon);
         logger.info("query sql=" + select);
         ResultSet r = s.executeQuery(select);
@@ -865,20 +861,21 @@
         county.name = r.getString(3);
         county.county_centroid_X = r.getString(4);
         county.county_centroid_Y = r.getString(5);
-         
+
         logger.info("county_fips_code=" + county.st_abbr + county.county_code);
         logger.info("name=" + county.name);
         logger.info("centroidX=" + county.county_centroid_X);
         logger.info("centroidY=" + county.county_centroid_Y);
         return county;
-    } 
-   
-    
-    public double findCmz(double lat, double lon) throws SQLException {
-        return findDbl("select distinct g.co_cmz from cmz_geom as g "
-                  + "where ST_Within(ST_Point(" + lon + "," + lat + "), g.geometry) LIMIT 1;", lon, 1);
     }
-    
+
+
+    public String findCmz(double lat, double lon) throws SQLException {
+        return findCmzName("select distinct g.co_cmz from cmz_geom as g "
+                + "where ST_Within(ST_Point(" + lon + "," + lat + "), g.geometry) LIMIT 1;", lon, 1);
+    }
+
+
     public List<FileQryResult> findManagements(double lat, double lon) throws SQLException {
         //Statement s = createStatement(getConnection());
         Statement s = createStatement(lon);
@@ -902,19 +899,22 @@
         //s.close();
         return l;
     }
-    
-        public List<FileQryResult> findManagementsFilter(double lat, double lon, String filter1, String filter2) throws SQLException {
+
+
+    public List<FileQryResult> findManagementsFilter(double lat, double lon, String filter1, String filter2) throws SQLException {
         //Statement s = createStatement(getConnection());
         Statement s = createStatement(lon);
         String sSql = "SELECT co_cmz, r2_path, r2_name FROM man_names WHERE co_cmz= (SELECT distinct co_cmz FROM cmz_geom "
                 + "WHERE Within(GeomFromText( 'POINT(" + lon + " "
                 + lat + ")' ), geometry) ) ";
-        
-        if (filter1.length() > 0)
-            sSql += " and (lower(r2_path) like '%" + filter1 + "%' or lower(r2_name) like '%" + filter1 + "%') ";            
-        if (filter2.length() > 0)
+
+        if (filter1.length() > 0) {
+            sSql += " and (lower(r2_path) like '%" + filter1 + "%' or lower(r2_name) like '%" + filter1 + "%') ";
+        }
+        if (filter2.length() > 0) {
             sSql += " and (lower(r2_path) like '%" + filter2 + "%' or lower(r2_name) like '%" + filter2 + "%') ";
-        
+        }
+
         sSql += " ORDER BY usage DESC  LIMIT 100;";
 
         ResultSet r = s.executeQuery(sSql);
@@ -935,27 +935,27 @@
         return l;
     }
 
+
     public void close() throws SQLException {
         // conn.close();
 //        for (int i = 0;i< MAX_CONNECTIONS;i++)
 //            connections[i].close();
     }
 
+
     //private Statement createStatement(java.sql.Connection conn) {
     private Statement createStatement(double lon) {
         try {
             java.sql.Connection conn = getConnection(lon);
             logger.info("db connection to use=" + conn + " with URL=" + conn.getMetaData().getURL());
-            if ((conn != null) && (!conn.isClosed()))
-            {
+            if ((conn != null) && (!conn.isClosed())) {
                 Statement st = conn.createStatement();
                 logger.info("statement created normally");
                 logger.info("connection is closed=" + conn.isClosed());
                 logger.info("connection is read only=" + conn.isReadOnly());
                 logger.info("st.connection is closed=" + st.getConnection().isClosed());
                 logger.info("st.connection is read only=" + st.getConnection().isReadOnly());
-                if (st.getConnection().isClosed())
-                {
+                if (st.getConnection().isClosed()) {
                     logger.warning("Reinitializing database connection! Connection obtained through connections pool was closed!  This should not happen.");
                     conn = DriverManager.getConnection(PG_URL, "postgres", "postgres");
                     st = conn.createStatement();
@@ -963,13 +963,11 @@
                 logger.info("db client info=" + st.getConnection().getClientInfo().toString());
                 logger.info("db url=" + conn.getMetaData().getURL());
                 return st;
-            }
-            else
-            {
-                if (conn != null)
+            } else {
+                if (conn != null) {
                     logger.severe("connection isClosed=" + conn.isClosed());
-                if ((conn == null) || ((conn != null) && (conn.isClosed())))
-                {
+                }
+                if ((conn == null) || ((conn != null) && (conn.isClosed()))) {
                     logger.warning("Database connection not obtained through connections pool!  This should not happen.");
                     conn = DriverManager.getConnection(PG_URL, "postgres", "postgres");
                 }
@@ -982,46 +980,37 @@
         return null;
     }
 
+
     // return a rotating connection...
-    private static synchronized java.sql.Connection getConnection(double lon)
-    {
-        if (PostGIS.bUseChunks)
-        {
+    private static synchronized java.sql.Connection getConnection(double lon) {
+        if (PostGIS.bUseChunks) {
             logger.info("using db chunks for query");
             // find the needed connection array based on the chunk
             int maxConnections = Config.getInt("pg.connpool", MAX_CONNECTIONS);
-            Collection<Config.PostgresChunk> coll = Config.getPostgresChunks();            
-            for (Config.PostgresChunk pgc : coll)
-            {
+            Collection<Config.PostgresChunk> coll = Config.getPostgresChunks();
+            for (Config.PostgresChunk pgc : coll) {
                 logger.info("checking for chunk for longitude=" + lon);
-                if ((pgc.getMinLong() > lon) && (pgc.getMaxLong() < lon))
-                {
+                if ((pgc.getMinLong() > lon) && (pgc.getMaxLong() < lon)) {
                     pgc.connectionInc();
-                    if (pgc.getCurrentConnectionIdx() < maxConnections)
-                    {
-                        try
-                        {
+                    if (pgc.getCurrentConnectionIdx() < maxConnections) {
+                        try {
                             Connection conn = pgc.getCurrentConnection();
-                            if (conn != null)
+                            if (conn != null) {
                                 logger.info("using chunk for query=" + pgc.getName() + " with the URL of=" + conn.getMetaData().getURL());
-                            else
+                            } else {
                                 logger.info("using chunk for query=" + pgc.getName() + " BUT CONNECTION IS NULL AND NEEDS TO BE REINITIALIZED");
-                        }
-                        catch (SQLException sqle)
-                        {
+                            }
+                        } catch (SQLException sqle) {
                             logger.severe("using chunk for query=" + pgc.getName() + " BUT ERROR WHILE GETTING THE DB URL!!!");
                         }
-                    }
-                    else
-                    {
+                    } else {
                         logger.info("resetting connection counter; using chunk for query=" + pgc.getName());
                         pgc.setCurrentConnectionIdx(0);
                     }
                     Connection conn = pgc.getCurrentConnection();
-                    if (conn != null)
+                    if (conn != null) {
                         return conn;
-                    else
-                    {
+                    } else {
                         logger.severe("NO AVAILABLE DATABASE CONNECTION WHEN GETTING THE CURRENT CONNECTION!");
                         return null;
                     }
@@ -1030,28 +1019,22 @@
             // if no chunk is found return standard chunk
             logger.warning("no db chunk found for longitude=" + lon);
             logger.warning("trying to use default postgresql db.");
-            currentConnection ++;
-            if (currentConnection < maxConnections)
+            currentConnection++;
+            if (currentConnection < maxConnections) {
                 return connections[currentConnection];
-            else
-            {
+            } else {
                 currentConnection = 0;
                 return connections[0];
             }
-        }
-        else
-        {
+        } else {
             // if chunks are not used, then lat lng coords can be ignored
-            logger.info ("Not using DB chunks for this query.");
+            logger.info("Not using DB chunks for this query.");
             int maxConnections = Config.getInt("pg.connpool", MAX_CONNECTIONS);
-            currentConnection ++;
-            if (currentConnection < maxConnections)
-            {
+            currentConnection++;
+            if (currentConnection < maxConnections) {
                 logger.info("Using DB connection #" + currentConnection);
                 return connections[currentConnection];
-            }
-            else
-            {
+            } else {
                 currentConnection = 0;
                 logger.info("Using DB connection #" + currentConnection);
                 return connections[0];

src/java/d/rusle2/CMZ1_0.java

@@ -50,6 +50,7 @@
     @Context
     HttpServletRequest inRequest;
 
+
     @Override
     protected void finalize() throws Throwable {
         super.finalize();
@@ -62,78 +63,55 @@
         }
     }
 
+
     public CMZ1_0() throws Exception {
         db = PostGIS.singleton();
     }
 
-//    @Override
-//    String describeJSON() {
-//        try {
-//            String tmpl = IOUtils.toString(V1_1.class.getResource("/src/d/rusle2/climate.json"));
-//            JSONObject model = new JSONObject(tmpl);
-//            return model.toString();
-//        } catch (IOException ex) {
-//            throw new RuntimeException("tmpl");
-//        }
-//    }
+    @Override
+    protected JSONArray createResults() throws Exception {
+        return outputObj;
+    }
+
 
     @Override
-    protected JSONArray createResults() throws Exception {
-            return outputObj;
+    protected String process() throws Exception {
+        outputObj = new JSONArray(getParam().toString());
+        JSONArray aOutput = new JSONArray();
+        org.json.JSONObject res = new org.json.JSONObject();
+        double start = System.currentTimeMillis();
+        double end = 0;
+        String status = "Finished";
+
+        log("get lat long from content input");
+        double latitude = JSONUtils.getDoubleParam(getParamMap(), "latitude", 0);
+        double longitude = JSONUtils.getDoubleParam(getParamMap(), "longitude", 0);
+
+        try {
+            String cmz = "0";
+
+            try {
+                log("find cmz for lat long");
+                cmz = db.findCmz(latitude, longitude);
+                log("found cmzfor lat lng");
+            } catch (SQLException ex) {
+                log("exception finding cmz for lat long");
+                Logger.getLogger(CMZ1_0.class.getName()).log(Level.SEVERE, null, ex);
+            }
+
+            log("build jsonobject to return");
+            outputObj.put(JSONUtils.data("tstamp", new Date()));
+            outputObj.put(JSONUtils.data("cmz", (String) cmz));
+            log("write response");
+            end = System.currentTimeMillis();
+        } catch (Exception ex) {
+            log("Exception: " + ex.toString());
+            status = "Failed";
+        }
+        log("JSON object returned is=" + outputObj.toString());
+        return EXEC_OK;
     }
 
-    /**
-     * POST method for retrieving climates for a specific lat/long
-     *
-     * @param req representation for the resource
-     * @return an HTTP response with content of the updated or created resource.
-     */
-    @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
-            @Override
-            public String call() throws Exception {
-                outputObj = new JSONArray(getParam().toString());
-                JSONArray aOutput = new JSONArray();
-                org.json.JSONObject res = new org.json.JSONObject();
-                double start = System.currentTimeMillis();
-                double end = 0;
-                String status = "Finished";
-
-                log("get lat long from content input");
-                double latitude = JSONUtils.getDoubleParam(getParamMap(), "latitude", 0);
-                double longitude = JSONUtils.getDoubleParam(getParamMap(), "longitude", 0);
-
-                try {
-                    double cmz = 0.0;
-
-                    try {
-                        log("find cmz for lat long");
-                        cmz = db.findCmz(latitude, longitude);
-                        log("found cmzfor lat lng");
-                    } catch (SQLException ex) {
-                        log("exception finding cmz for lat long");
-                        Logger.getLogger(CMZ1_0.class.getName()).log(Level.SEVERE, null, ex);
-                    }
-
-                    log("put cmz into string");
-                    String sCmz = Double.toString(cmz);
-
-                    log("build jsonobject to return");
-                    outputObj.put(JSONUtils.data("tstamp", new Date()));
-                    outputObj.put(JSONUtils.data("cmz", (String) sCmz));
-                    log("write response");
-                    end = System.currentTimeMillis();
-                } catch (Exception ex) {
-                    log("Exception: " + ex.toString());
-                    status = "Failed";
-                }
-
-                log("JSON object returned is=" + outputObj.toString());
-                return EXEC_OK;
-            }
-        };
-    }
 
     private void log(String text) {
         LOG.info(text);

src/java/d/rusle2/Climate1_0.java

@@ -6,11 +6,8 @@
 
 import c.PostGIS;
 import c.PostGIS.FileQryResult;
-import d.soils.V1_1;
-import java.io.IOException;
 import java.sql.SQLException;
 import java.util.Date;
-import java.util.concurrent.Callable;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import javax.servlet.http.HttpServletRequest;
@@ -20,14 +17,10 @@
 import oms3.annotations.Description;
 import oms3.annotations.Name;
 import oms3.annotations.VersionInfo;
-import org.apache.commons.io.IOUtils;
 import org.codehaus.jettison.json.JSONArray;
-import org.codehaus.jettison.json.JSONException;
-import org.codehaus.jettison.json.JSONObject;
 import csip.ModelDataService;
 import static csip.ModelDataService.EXEC_OK;
 import csip.utils.JSONUtils;
-import static m.weps.SciEnergyParser.LOG;
 
 /**
  * REST Web Service
@@ -47,10 +40,12 @@
 
     @Context
     private UriInfo context;
+
     PostGIS db;
     @Context
     HttpServletRequest inRequest;
 
+
     @Override
     protected void finalize() throws Throwable {
         super.finalize();
@@ -63,102 +58,73 @@
         }
     }
 
+
     public Climate1_0() throws Exception {
         db = PostGIS.singleton();
     }
 
-//    @Override
-//    String describeJSON() {
-//        try {
-//            String tmpl = IOUtils.toString(V1_1.class.getResource("/src/d/rusle2/climate.json"));
-//            JSONObject model = new JSONObject(tmpl);
-//            return model.toString();
-//        } catch (IOException ex) {
-//            throw new RuntimeException("tmpl");
-//        }
-//    }
 
     @Override
     protected JSONArray createResults() throws Exception {
-        //try {
-            //String tmpl = IOUtils.toString(V1_1.class.getResource("/src/d/soils/V1_1Res.json"));
-            //JSONArray results = new JSONArray(tmpl);
-            //return results;
-            return outputObj;
-        //} catch (IOException ex) {
-          //  throw new RuntimeException("tmpl");
-        //}
+        return outputObj;
     }
 
-    /**
-     * POST method for retrieving climates for a specific lat/long
-     *
-     * @param req representation for the resource
-     * @return an HTTP response with content of the updated or created resource.
-     */
-//    @POST
-//    @Produces("application/json")
-//    @Consumes("application/json")
-//    public String postJSON(String strreq) throws Exception {
+
     @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
-            @Override
-            public String call() throws Exception {
-                outputObj = new JSONArray(getParam().toString());
-                JSONArray aOutput = new JSONArray();
-                org.json.JSONObject res = new org.json.JSONObject();
-                double start = System.currentTimeMillis();
-                double end = 0;
-                String status = "Finished";
+    protected String process() throws Exception {
+        outputObj = new JSONArray(getParam().toString());
+        JSONArray aOutput = new JSONArray();
+        org.json.JSONObject res = new org.json.JSONObject();
+        double start = System.currentTimeMillis();
+        double end = 0;
+        String status = "Finished";
 
-                log("get lat long from content input");
-                double latitude = JSONUtils.getDoubleParam(getParamMap(), "latitude", 0);
-                double longitude = JSONUtils.getDoubleParam(getParamMap(), "longitude", 0);
+        log("get lat long from content input");
+        double latitude = JSONUtils.getDoubleParam(getParamMap(), "latitude", 0);
+        double longitude = JSONUtils.getDoubleParam(getParamMap(), "longitude", 0);
 
-                try {
-                    FileQryResult climate = null;
+        try {
+            FileQryResult climate = null;
 
-                    try {
-                        log("find climate for lat long");
-                        climate = db.findClimate(latitude, longitude);
-                        log("found climate for lat lng");
-                    } catch (SQLException ex) {
-                        log("exception finding climate for lat long");
-                        Logger.getLogger(Climate1_0.class.getName()).log(Level.SEVERE, null, ex);
-                    }
+            try {
+                log("find climate for lat long");
+                climate = db.findClimate(latitude, longitude);
+                log("found climate for lat lng");
+            } catch (SQLException ex) {
+                log("exception finding climate for lat long");
+                Logger.getLogger(Climate1_0.class.getName()).log(Level.SEVERE, null, ex);
+            }
 
-                    log("put climate into array list");
-                    String sClimate;
-                    sClimate = rusle2db + "/epa/" + climate.file_path + "/" + climate.file_name + CLIMATE_FILE_EXT;
-                    sClimate = fixClimateUrl(sClimate);
+            log("put climate into array list");
+            String sClimate;
+            sClimate = rusle2db + "/epa/" + climate.file_path + "/" + climate.file_name + CLIMATE_FILE_EXT;
+            sClimate = fixClimateUrl(sClimate);
 
-                    log("build jsonobject to return");
+            log("build jsonobject to return");
 
-                    aOutput.put(JSONUtils.data("tstamp", new Date()));
-                    aOutput.put(JSONUtils.data("climate", (String) sClimate));
+            aOutput.put(JSONUtils.data("tstamp", new Date()));
+            aOutput.put(JSONUtils.data("climate", (String) sClimate));
 //                    res.put("name", "climate");
 //                    res.put("value", (String) sClimate);
 //                    aOutput.put(res);  aOutput.
 
 //                    res.put("tstamp", new Date());
 //                    res.put("climate", (String) sClimate);
-                    log("JSON object returned is=" + res.toString());
-                    log("write response");
-                    end = System.currentTimeMillis();
-                } catch (Exception ex) {
-                    log("Exception: " + ex.toString());
-                    status = "Failed";
-                }
+            log("JSON object returned is=" + res.toString());
+            log("write response");
+            end = System.currentTimeMillis();
+        } catch (Exception ex) {
+            log("Exception: " + ex.toString());
+            status = "Failed";
+        }
 
-                //outputObj.put(res);
-                outputObj.put(aOutput);
-                //return res.toString();
-                return EXEC_OK;
-            }
-        };
+        //outputObj.put(res);
+        outputObj.put(aOutput);
+        //return res.toString();
+        return EXEC_OK;
     }
 
+
     private String fixClimateUrl(String text) {
         log("fixing string=" + text);
         // remove \/ 's
@@ -171,6 +137,7 @@
         return text;
     }
 
+
     private void log(String text) {
         LOG.info(text);
     }

src/java/d/rusle2/StateCounty1_0.java

@@ -5,9 +5,6 @@
 package d.rusle2;
 
 import c.PostGIS;
-import c.PostGIS.FileQryResult;
-import d.soils.V1_1;
-import java.io.IOException;
 import java.sql.SQLException;
 import java.util.Date;
 import java.util.concurrent.Callable;
@@ -20,14 +17,10 @@
 import oms3.annotations.Description;
 import oms3.annotations.Name;
 import oms3.annotations.VersionInfo;
-import org.apache.commons.io.IOUtils;
 import org.codehaus.jettison.json.JSONArray;
-import org.codehaus.jettison.json.JSONException;
-import org.codehaus.jettison.json.JSONObject;
 import csip.ModelDataService;
 import static csip.ModelDataService.EXEC_OK;
 import csip.utils.JSONUtils;
-import static m.weps.SciEnergyParser.LOG;
 
 /**
  * REST Web Service
@@ -50,6 +43,7 @@
     @Context
     HttpServletRequest inRequest;
 
+
     @Override
     protected void finalize() throws Throwable {
         super.finalize();
@@ -62,80 +56,56 @@
         }
     }
 
+
     public StateCounty1_0() throws Exception {
         db = PostGIS.singleton();
     }
 
-//    @Override
-//    String describeJSON() {
-//        try {
-//            String tmpl = IOUtils.toString(V1_1.class.getResource("/src/d/rusle2/climate.json"));
-//            JSONObject model = new JSONObject(tmpl);
-//            return model.toString();
-//        } catch (IOException ex) {
-//            throw new RuntimeException("tmpl");
-//        }
-//    }
 
     @Override
     protected JSONArray createResults() throws Exception {
-            return outputObj;
+        return outputObj;
     }
 
-    /**
-     * POST method for retrieving climates for a specific lat/long
-     *
-     * @param req representation for the resource
-     * @return an HTTP response with content of the updated or created resource.
-     */
+
     @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
-            @Override
-            public String call() throws Exception {
-                outputObj = new JSONArray(getParam().toString());
-                JSONArray aOutput = new JSONArray();
-                org.json.JSONObject res = new org.json.JSONObject();
-                double start = System.currentTimeMillis();
-                double end = 0;
-                String status = "Finished";
+    protected String process() throws Exception {
+        outputObj = new JSONArray(getParam().toString());
+        JSONArray aOutput = new JSONArray();
+        org.json.JSONObject res = new org.json.JSONObject();
 
-                log("get lat long from content input");
-                double latitude = JSONUtils.getDoubleParam(getParamMap(), "latitude", 0);
-                double longitude = JSONUtils.getDoubleParam(getParamMap(), "longitude", 0);
+        log("get lat long from content input");
+        double latitude = JSONUtils.getDoubleParam(getParamMap(), "latitude", 0);
+        double longitude = JSONUtils.getDoubleParam(getParamMap(), "longitude", 0);
 
-                try {
-                    PostGIS.County countystate = null;
+        try {
+            PostGIS.County countystate = null;
 
-                    try {
-                        log("find county for lat long");
-                        countystate = db.findCounty(latitude, longitude);
-                        log("found county for lat lng");
-                    } catch (SQLException ex) {
-                        log("exception finding county for lat long");
-                        Logger.getLogger(StateCounty1_0.class.getName()).log(Level.SEVERE, null, ex);
-                    }
+            try {
+                log("find county for lat long");
+                countystate = db.findCounty(latitude, longitude);
+                log("found county for lat lng");
+            } catch (SQLException ex) {
+                log("exception finding county for lat long");
+                Logger.getLogger(StateCounty1_0.class.getName()).log(Level.SEVERE, null, ex);
+            }
 
-                    log("put county name into string");
-                    String countyName = countystate.name;
-                    String stateAbbr = countystate.st_abbr;
+            log("put county name into string");
+            String countyName = countystate.name;
+            String stateAbbr = countystate.st_abbr;
 
-                    log("build jsonobject to return");
-                    outputObj.put(JSONUtils.data("tstamp", new Date()));
-                    outputObj.put(JSONUtils.data("county", (String) countyName));
-                    outputObj.put(JSONUtils.data("state", (String) stateAbbr));
-                    log("write response");
-                    end = System.currentTimeMillis();
-                } catch (Exception ex) {
-                    log("Exception: " + ex.toString());
-                    status = "Failed";
-                }
+            log("build jsonobject to return");
+            outputObj.put(JSONUtils.data("tstamp", new Date()));
+            outputObj.put(JSONUtils.data("county", (String) countyName));
+            outputObj.put(JSONUtils.data("state", (String) stateAbbr));
+            log("write response");
+        } catch (Exception ex) {
+            log("Exception: " + ex.toString());
+        }
+        log("JSON object returned is=" + outputObj.toString());
+        return EXEC_OK;
+    }
 
-                log("JSON object returned is=" + outputObj.toString());
-                return EXEC_OK;
-            }
-        };
-    }
 
     private void log(String text) {
         LOG.info(text);

src/java/d/soils/V1_1.java

@@ -5,13 +5,10 @@
 package d.soils;
 
 import c.PostGIS;
-import java.io.IOException;
 import java.util.Collection;
-import java.util.concurrent.Callable;
 import java.util.logging.Level;
 import javax.ws.rs.*;
 import oms3.annotations.*;
-import org.apache.commons.io.IOUtils;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONObject;
 import csip.ModelDataService;
@@ -30,109 +27,97 @@
 
     JSONArray outputObj;
 
+
     @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
-            @Override
-            public String call() throws Exception {
-                LOG.log(Level.INFO, "phacil soils input obj dump");
-                outputObj = new JSONArray(getParam().toString());
-                //outputObj = getParam();
-                //outputObj = createResults();
+    protected String process() throws Exception {
+        LOG.log(Level.INFO, "phacil soils input obj dump");
+        outputObj = new JSONArray(getParam().toString());
 
-                Collection<JSONObject> coll = getParamMap().values();
-                for (JSONObject jsonobj : coll) {
-                    LOG.log(Level.INFO, "json obj=" + jsonobj.toString());
-                    JSONObject aoiobj = jsonobj.optJSONObject("value");
-                    JSONArray features = aoiobj.optJSONArray("features");
-                    LOG.log(Level.INFO, "features obj=" + features.toString());
-                    for (int i = 0; i < features.length(); i++) {
-                        JSONObject poly = features.getJSONObject(i);
-                        LOG.log(Level.INFO, "poly obj #" + i + poly.toString());
-                        JSONObject geometry = poly.optJSONObject("geometry");
-                        LOG.log(Level.INFO, "geometry obj=" + geometry.toString());
-                        JSONArray coords = geometry.optJSONArray("coordinates");
-                        LOG.log(Level.INFO, "coords obj=" + coords.toString());
-                        JSONArray aCoord = new JSONArray();
-                        for (int j = 0; j < coords.length(); j++) {
-                            JSONArray shape = coords.getJSONArray(j);
-                            LOG.log(Level.INFO, "shape obj=" + shape.toString());
-                            JSONArray aPoly = new JSONArray();
-                            String newPolygon = "ST_PolygonFromText('POLYGON((";
-                            double firstLong = 0.0;
-                            for (int k = 0; k < shape.length(); k++) {
-                                JSONArray point = shape.getJSONArray(k);
-                                if (firstLong == 0) {
-                                    firstLong = point.getDouble(0);
-                                }
-                                LOG.log(Level.INFO, "point obj=" + point.toString());
-                                LOG.log(Level.INFO, "point 0 value=" + point.getDouble(0));
-                                LOG.log(Level.INFO, "point 1 value=" + point.getDouble(1));
-                                if (k > 0) {
-                                    newPolygon += ",";
-                                }
-                                newPolygon += point.getDouble(0) + " " + point.getDouble(1);
-                            }
-                            newPolygon += "))',4326)";
-                            LOG.log(Level.INFO, "Polygon of interest=" + newPolygon);
-                            Collection<PostGIS.Soil> soils = PostGIS.singleton().findSoilsForPolygon(newPolygon, firstLong);
-                            for (PostGIS.Soil soilObj : soils) {
-                                String sSoil = "SOIL INTERSECTION: cokey:" + soilObj.coKey;
-                                sSoil += ", mukey:" + soilObj.muKey;
-                                sSoil += " ,cofips:" + soilObj.coFips;
-                                sSoil += " ,compname:" + soilObj.compName;
-                                sSoil += " ,kffact:" + soilObj.kffact;
-                                sSoil += " ,tfact:" + soilObj.tfact + " " + soilObj.tfactUnits;
-                                sSoil += " ,muname:" + soilObj.muName;
-                                sSoil += " ,musym:" + soilObj.muSym;
-                                sSoil += " ,perwater:" + soilObj.perWater + " " + soilObj.perWaterUnits;
-                                sSoil += " ,perwind:" + soilObj.perWind + " " + soilObj.perWindUnits;
-                                sSoil += " ,r2name:" + soilObj.r2Name;
-                                sSoil += " ,r2path:" + soilObj.r2Path;
-                                sSoil += " ,lengthR:" + soilObj.lengthR + " " + soilObj.lengthRUnits;
-                                sSoil += " ,slopeR:" + soilObj.slopeR + " " + soilObj.slopeRUnits;
-                                sSoil += " ,%AOI:" + soilObj.percentAoi;
-                                sSoil += " ,sizeaoi:" + soilObj.sizeAoi + " " + soilObj.sizeAoiUnits;
-                                LOG.log(Level.INFO, sSoil);
-                                JSONArray aSoil = new JSONArray();
-                                aSoil.put(JSONUtils.data("ssurgo_cokey", soilObj.coKey));
-                                aSoil.put(JSONUtils.data("ssurgo_mukey", soilObj.muKey));
-                                aSoil.put(JSONUtils.data("ssurgo_areasymbol", soilObj.coFips));
-                                aSoil.put(JSONUtils.data("ssurgo_compname", soilObj.compName));
-                                aSoil.put(JSONUtils.data("ssurgo_kffact", soilObj.kffact));
-                                aSoil.put(JSONUtils.data("ssurgo_tfact", soilObj.tfact, soilObj.tfactUnits));
-                                aSoil.put(JSONUtils.data("ssurgo_muname", soilObj.muName));
-                                aSoil.put(JSONUtils.data("ssurgo_musym", soilObj.muSym));
-                                aSoil.put(JSONUtils.data("per_water", soilObj.perWater, soilObj.perWaterUnits));
-                                aSoil.put(JSONUtils.data("per_wind", soilObj.perWind, soilObj.perWindUnits));
-                                aSoil.put(JSONUtils.data("r2_r2name", soilObj.r2Name));
-                                aSoil.put(JSONUtils.data("r2_r2path", soilObj.r2Path));
-                                aSoil.put(JSONUtils.data("length_r", soilObj.lengthR, soilObj.lengthRUnits));
-                                aSoil.put(JSONUtils.data("ssurgo_slopeR", soilObj.slopeR, soilObj.slopeRUnits));
-                                aSoil.put(JSONUtils.data("percent_of_aoi", soilObj.percentAoi, soilObj.percentAoiUnits));
-                                aSoil.put(JSONUtils.data("acres_in_aoi", soilObj.sizeAoi, soilObj.sizeAoiUnits));
-                                aPoly.put(aSoil);
-                            }
-                            aCoord.put(aPoly);
+        Collection<JSONObject> coll = getParamMap().values();
+        for (JSONObject jsonobj : coll) {
+            LOG.log(Level.INFO, "json obj=" + jsonobj.toString());
+            JSONObject aoiobj = jsonobj.optJSONObject("value");
+            JSONArray features = aoiobj.optJSONArray("features");
+            LOG.log(Level.INFO, "features obj=" + features.toString());
+            for (int i = 0; i < features.length(); i++) {
+                JSONObject poly = features.getJSONObject(i);
+                LOG.log(Level.INFO, "poly obj #" + i + poly.toString());
+                JSONObject geometry = poly.optJSONObject("geometry");
+                LOG.log(Level.INFO, "geometry obj=" + geometry.toString());
+                JSONArray coords = geometry.optJSONArray("coordinates");
+                LOG.log(Level.INFO, "coords obj=" + coords.toString());
+                JSONArray aCoord = new JSONArray();
+                for (int j = 0; j < coords.length(); j++) {
+                    JSONArray shape = coords.getJSONArray(j);
+                    LOG.log(Level.INFO, "shape obj=" + shape.toString());
+                    JSONArray aPoly = new JSONArray();
+                    String newPolygon = "ST_PolygonFromText('POLYGON((";
+                    double firstLong = 0.0;
+                    for (int k = 0; k < shape.length(); k++) {
+                        JSONArray point = shape.getJSONArray(k);
+                        if (firstLong == 0) {
+                            firstLong = point.getDouble(0);
                         }
-                        outputObj.put(aCoord);
+                        LOG.log(Level.INFO, "point obj=" + point.toString());
+                        LOG.log(Level.INFO, "point 0 value=" + point.getDouble(0));
+                        LOG.log(Level.INFO, "point 1 value=" + point.getDouble(1));
+                        if (k > 0) {
+                            newPolygon += ",";
+                        }
+                        newPolygon += point.getDouble(0) + " " + point.getDouble(1);
                     }
+                    newPolygon += "))',4326)";
+                    LOG.log(Level.INFO, "Polygon of interest=" + newPolygon);
+                    Collection<PostGIS.Soil> soils = PostGIS.singleton().findSoilsForPolygon(newPolygon, firstLong);
+                    for (PostGIS.Soil soilObj : soils) {
+                        String sSoil = "SOIL INTERSECTION: cokey:" + soilObj.coKey;
+                        sSoil += ", mukey:" + soilObj.muKey;
+                        sSoil += " ,cofips:" + soilObj.coFips;
+                        sSoil += " ,compname:" + soilObj.compName;
+                        sSoil += " ,kffact:" + soilObj.kffact;
+                        sSoil += " ,tfact:" + soilObj.tfact + " " + soilObj.tfactUnits;
+                        sSoil += " ,muname:" + soilObj.muName;
+                        sSoil += " ,musym:" + soilObj.muSym;
+                        sSoil += " ,perwater:" + soilObj.perWater + " " + soilObj.perWaterUnits;
+                        sSoil += " ,perwind:" + soilObj.perWind + " " + soilObj.perWindUnits;
+                        sSoil += " ,r2name:" + soilObj.r2Name;
+                        sSoil += " ,r2path:" + soilObj.r2Path;
+                        sSoil += " ,lengthR:" + soilObj.lengthR + " " + soilObj.lengthRUnits;
+                        sSoil += " ,slopeR:" + soilObj.slopeR + " " + soilObj.slopeRUnits;
+                        sSoil += " ,%AOI:" + soilObj.percentAoi;
+                        sSoil += " ,sizeaoi:" + soilObj.sizeAoi + " " + soilObj.sizeAoiUnits;
+                        LOG.log(Level.INFO, sSoil);
+                        JSONArray aSoil = new JSONArray();
+                        aSoil.put(JSONUtils.data("ssurgo_cokey", soilObj.coKey));
+                        aSoil.put(JSONUtils.data("ssurgo_mukey", soilObj.muKey));
+                        aSoil.put(JSONUtils.data("ssurgo_areasymbol", soilObj.coFips));
+                        aSoil.put(JSONUtils.data("ssurgo_compname", soilObj.compName));
+                        aSoil.put(JSONUtils.data("ssurgo_kffact", soilObj.kffact));
+                        aSoil.put(JSONUtils.data("ssurgo_tfact", soilObj.tfact, soilObj.tfactUnits));
+                        aSoil.put(JSONUtils.data("ssurgo_muname", soilObj.muName));
+                        aSoil.put(JSONUtils.data("ssurgo_musym", soilObj.muSym));
+                        aSoil.put(JSONUtils.data("per_water", soilObj.perWater, soilObj.perWaterUnits));
+                        aSoil.put(JSONUtils.data("per_wind", soilObj.perWind, soilObj.perWindUnits));
+                        aSoil.put(JSONUtils.data("r2_r2name", soilObj.r2Name));
+                        aSoil.put(JSONUtils.data("r2_r2path", soilObj.r2Path));
+                        aSoil.put(JSONUtils.data("length_r", soilObj.lengthR, soilObj.lengthRUnits));
+                        aSoil.put(JSONUtils.data("ssurgo_slopeR", soilObj.slopeR, soilObj.slopeRUnits));
+                        aSoil.put(JSONUtils.data("percent_of_aoi", soilObj.percentAoi, soilObj.percentAoiUnits));
+                        aSoil.put(JSONUtils.data("acres_in_aoi", soilObj.sizeAoi, soilObj.sizeAoiUnits));
+                        aPoly.put(aSoil);
+                    }
+                    aCoord.put(aPoly);
                 }
-                return EXEC_OK;
+                outputObj.put(aCoord);
             }
-        };
+        }
+        return EXEC_OK;
     }
 
+
     @Override
     protected JSONArray createResults() throws Exception {
-//        try {
-            //String tmpl = IOUtils.toString(V1_1.class.getResource("/src/java/d/soils/V1_1Res.json"));
-            //JSONArray results = new JSONArray(tmpl);
-            //return results;
-            return outputObj;
-//        } catch (IOException ex) {
-//            throw new RuntimeException("tmpl");
-//        }
+        return outputObj;
     }
 
 }

src/java/m/ApplicationConfig.java

@@ -34,7 +34,6 @@
         resources.add(csip.ArchiveService.class);
         resources.add(csip.CatalogService.class);
         resources.add(csip.ControlService.class);
-        resources.add(csip.ModelDataService.class);
         resources.add(csip.QueryService.class);
         resources.add(csip.ReportService.class);
         resources.add(csip.UIService.class);
@@ -47,22 +46,11 @@
         resources.add(d.rusle2.StateCounty1_0.class);
         resources.add(d.soils.V1_1.class);
         resources.add(d.soils.V1_2.class);
-        resources.add(m.r2zedx.R2NonBranded.class);
-        resources.add(m.r2zedx.V1_0.class);
-        resources.add(m.rusle2.V1_2.class);
         resources.add(m.rusle2.V1_3.class);
         resources.add(m.rusle2.V2_0.class);
-        resources.add(m.rusle2.current.Rusle2Service.class);
         resources.add(m.rusle2.rusle2check.class);
-        resources.add(m.sci.V1_1.class);
-        resources.add(m.sci.V1_2.class);
         resources.add(m.sci.V1_3.class);
-        resources.add(m.stir.V1_1.class);
         resources.add(m.stir.V1_2.class);
-        resources.add(m.weps.V1_1.class);
-        resources.add(m.weps.V1_2.class);
         resources.add(m.weps.V1_3.class);
-        resources.add(m.weps.WEPSService.class);
-        resources.add(m.weps.WEPSServiceT.class);
     }
 }

src/java/m/rusle2/R2Run.java

@@ -14,7 +14,6 @@
 import java.net.HttpURLConnection;
 import java.net.URL;
 import java.net.UnknownHostException;
-import m.rusle2.current.XMLUtils;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.StringEscapeUtils;
 

src/java/m/rusle2/V1_3.java

@@ -10,7 +10,6 @@
 import java.io.File;
 import java.io.FileOutputStream;
 import java.util.*;
-import java.util.concurrent.Callable;
 import javax.ws.rs.*;
 import oms3.annotations.*;
 import org.apache.commons.io.FileUtils;
@@ -35,7 +34,6 @@
 import csip.utils.JSONUtils;
 import csip.utils.Services;
 import csip.annotations.Polling;
-import static m.rusle2.R2Run.LOG;
 
 /**
  * REST Web Service. Front end callable.
@@ -87,10 +85,11 @@
     List<String> operations;
     List<String> vegetations;
     List<String> residues;
+
     //
 
     @Override
-    protected void preprocess() throws Exception {
+    protected void preProcess() throws Exception {
         // check for requested output.
 
         try {
@@ -105,17 +104,20 @@
             params.add(RES_SLOPE_DELIVERY);
             params.add(RES_SLOPE_T_VALUE);
             params.add(RES_SLOPE_DEGRAD);
-            
+
             // check if these are being set
-        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_CONTOUR_SYSTEM_PTR))
-            params.add("CONTOUR_SYSTEM_PTR");
+            if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_CONTOUR_SYSTEM_PTR)) {
+                params.add("CONTOUR_SYSTEM_PTR");
+            }
 
-        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_STRIP_BARRIER_SYSTEM_PTR))
-            params.add("STRIP_BARRIER_SYSTEM_PTR");
+            if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_STRIP_BARRIER_SYSTEM_PTR)) {
+                params.add("STRIP_BARRIER_SYSTEM_PTR");
+            }
 
-        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_HYD_ELEM_SYSTEM_PTR))
-            params.add("HYD_ELEM_SYSTEM_PTR");
-            
+            if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_HYD_ELEM_SYSTEM_PTR)) {
+                params.add("HYD_ELEM_SYSTEM_PTR");
+            }
+
             getMetainfo().put(KEY_REQUEST_RESULTS, params);
         }
 
@@ -132,82 +134,70 @@
         createInputFile(r2script, getMetainfo(), getParamMap());
     }
 
+
     @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
+    protected String process() throws Exception {
+        int result = r2run.execute(new File(getWorkspaceDir(), R2_TMP_FILENAME + R2_TMP_FILEEXT));
+        if (result != 0) {
+            return EXEC_FAILED;
+        }
+        return EXEC_OK;
+    }
 
-            @Override
-            public String call() throws Exception {
-                
-                int result = r2run.execute(new File(getWorkspaceDir(), R2_TMP_FILENAME + R2_TMP_FILEEXT));
-                if (result != 0) {
-                    return EXEC_FAILED;
-                }
-                return EXEC_OK;
-            }
-        };
-    }
 
     @Override
     protected JSONArray createResults() throws Exception {
         JSONArray results = new JSONArray();
-        
+
         int errors = 0;
-        for (int i = 0; i < operations.size(); i++)
-        {
+        for (int i = 0; i < operations.size(); i++) {
             String op = operations.get(i);
-            if (r2run.isUrlReachable(op))
-                results.put(JSONUtils.dataDesc("OPERATION_" + (i+1), op, "operation is valid"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("OPERATION_INVALID_" + (i+1), op, "OPERATION IS MISSING!"));
-                errors ++;
+            if (r2run.isUrlReachable(op)) {
+                results.put(JSONUtils.dataDesc("OPERATION_" + (i + 1), op, "operation is valid"));
+            } else {
+                results.put(JSONUtils.dataDesc("OPERATION_INVALID_" + (i + 1), op, "OPERATION IS MISSING!"));
+                errors++;
             }
         }
-        for (int i = 0; i < vegetations.size(); i++)
-        {
+        for (int i = 0; i < vegetations.size(); i++) {
             String vege = vegetations.get(i);
-            if (r2run.isUrlReachable(vege))
-                results.put(JSONUtils.dataDesc("VEGETATION_" + (i+1), vege, "vegetation is valid"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("VEGETATION_INVALID_" + (i+1), vege, "VEGETATION IS MISSING"));
-                errors ++;
+            if (r2run.isUrlReachable(vege)) {
+                results.put(JSONUtils.dataDesc("VEGETATION_" + (i + 1), vege, "vegetation is valid"));
+            } else {
+                results.put(JSONUtils.dataDesc("VEGETATION_INVALID_" + (i + 1), vege, "VEGETATION IS MISSING"));
+                errors++;
             }
         }
-        for (int i = 0; i < residues.size(); i++)
-        {
+        for (int i = 0; i < residues.size(); i++) {
             String res = residues.get(i);
-            if (r2run.isUrlReachable(res))
-                results.put(JSONUtils.dataDesc("RESIDUE_" + (i+1), res, "RESIDUE IS VALID"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("RESIDUE_INVALID_" + (i+1), res, "RESIDUE IS MISSING"));
-                errors ++;
+            if (r2run.isUrlReachable(res)) {
+                results.put(JSONUtils.dataDesc("RESIDUE_" + (i + 1), res, "RESIDUE IS VALID"));
+            } else {
+                results.put(JSONUtils.dataDesc("RESIDUE_INVALID_" + (i + 1), res, "RESIDUE IS MISSING"));
+                errors++;
             }
         }
-        
+
 //      results.put(JSONUtils.data(KEY_SLOPE_DELIVERY, 3.0));
-        for (String r : JSONUtils.getRequestedResults(getMetainfo())) 
-        {
-            if ((errors > 0) && (r.equals(RES_SLOPE_DEGRAD)))
+        for (String r : JSONUtils.getRequestedResults(getMetainfo())) {
+            if ((errors > 0) && (r.equals(RES_SLOPE_DEGRAD))) {
                 results.put(JSONUtils.dataDesc(r, r2run.getResult(r), R2_MISSING_XML_FILES_WARNING_MSG));
-            else
+            } else {
                 results.put(JSONUtils.data(r, r2run.getResult(r)));
+            }
         }
-
-        if (errors > 0)
+        if (errors > 0) {
             appendMetainfoWarning(R2_MISSING_XML_FILES_WARNING_MSG);
+        }
 
         results.put(JSONUtils.data(KEY_CLIMATES, climate));
         results.put(JSONUtils.data(KEY_SOILS, soil));
         results.put(JSONUtils.data(KEY_MANAGEMENTS, mgmt));
 //      results.put(JSONUtils.data(KEY_ALT_R2DB, in_ALT_R2DB));
-        
-        
         return results;
     }
 
+
     private void createInputFile(File file, JSONObject metainfo, Map<String, JSONObject> param)
             throws Exception {
 
@@ -217,22 +207,22 @@
         double latitude = JSONUtils.getDoubleParam(param, KEY_LATITUDE, 0.0);
         double longitude = JSONUtils.getDoubleParam(param, KEY_LONGITUDE, 0.0);
         double simpleRockCoverPercent = JSONUtils.getDoubleParam(param, KEY_SIMPLE_ROCK_COVER, 0.0);
-        
+
         LOG.info("Rock cover read by service is=" + simpleRockCoverPercent);
 
         JSONArray aRockCover = JSONUtils.getJSONArrayParam(param, KEY_SIMPLE_ROCK_COVER);
-        for (int i=0; i<aRockCover.length(); i++)
-        {
+        for (int i = 0; i < aRockCover.length(); i++) {
             LOG.info("Rock cover [" + i + "]=" + aRockCover.getDouble(i));
             // this is temporary, since R2 will be using slope segments soon
-            if (i==0)
+            if (i == 0) {
                 simpleRockCoverPercent = aRockCover.getDouble(i);
+            }
         }
 
         String climatePtr = JSONUtils.getStringParam(param, KEY_CLIMATES, "");
         String soilPtr = JSONUtils.getStringParam(param, KEY_SOILS, "");
         String managementFormalName[] = new String[]{};
-        
+
         String contourSystem = JSONUtils.getStringParam(param, KEY_CONTOUR_SYSTEM_PTR, "");
         String stripBarrierSystem = JSONUtils.getStringParam(param, KEY_STRIP_BARRIER_SYSTEM_PTR, "");
         String hydElemSystem = JSONUtils.getStringParam(param, KEY_HYD_ELEM_SYSTEM_PTR, "");
@@ -246,7 +236,6 @@
         System.setProperty("line.separator", "\n");
         //
         JSONArray managements = JSONUtils.getJSONArrayParam(param, KEY_MGMTS);
-        
 
         LOG.info("managements array=" + managements.toString());
         managementFormalName = new String[managements.length()];
@@ -286,13 +275,16 @@
             operations = translator.getOperationFiles();
             vegetations = translator.getVegetationFiles();
             residues = translator.getResidueFiles();
-            
-            for (String operation : translator.getOperationFiles())
+
+            for (String operation : translator.getOperationFiles()) {
                 System.out.println("operation=" + operation);
-            for (String vege : translator.getVegetationFiles())
+            }
+            for (String vege : translator.getVegetationFiles()) {
                 System.out.println("vegetation=" + vege);
-            for (String residue : translator.getResidueFiles())
+            }
+            for (String residue : translator.getResidueFiles()) {
                 System.out.println("residue=" + residue);
+            }
         }
 
         String altR2db = null;
@@ -372,13 +364,11 @@
 
         // OLD VERSION, WHERE WE GOT CLIMATE DIRECTLY FROM NGINX AND DIDN'T MODIFY IT
         // fos.write(("RomeFileSetAttrValue CLIMATE_PTR \"" + climatePtr + "\"\n").getBytes());
-        
         // NEW VERSION, Where the climate file must be modified to work
         fos.write(("FilesOpen \"#XML:" + new File(getWorkspaceDir(), "cli_file" + 0 + ".xml" + "\"\n")).getBytes());
         fos.write(("RomeFileSetAttrValue CLIMATE_PTR \"climates\\aaa\"\n").getBytes());
-        
+
         // New version, where we have to process the nginx file so R2 reads it
-
         // climate stub if needed
         //fos.write("RomeFileSetAttrValue CLIMATE_PTR \"climates\\USA\\Idaho\\Power County\\ID_Power_R_11\"\n".getBytes());
         // soil stub if needed
@@ -400,19 +390,18 @@
 
         // to do 
         // commented out - using default for now
-        
         fos.write(("FilesOpen \"#XML:" + new File(getWorkspaceDir(), "soils_file0.xml" + "\"\n")).getBytes());
-        String soilHttpPtr = r2db + "/" + soilPtr.replace("\\","/") + ".xml";
+        String soilHttpPtr = r2db + "/" + soilPtr.replace("\\", "/") + ".xml";
         r2run.prepareSoilsFile(soilHttpPtr, new File(getWorkspaceDir(), "soils_file0.xml"), false, "0");
-        
+
         String cliHttpPtr = r2db + "/" + climatePtr.replace("\\", "/") + ".xml";
         r2run.prepareClimateFile(cliHttpPtr, new File(getWorkspaceDir(), "cli_file0.xml"));
-        
+
         fos.write(("RomeFileSetAttrValue SOIL_PTR \"" + soilPtr + ".xml\"\n").getBytes());
 
         fos.write(("RomeFileSetAttrValue SLOPE_HORIZ \"" + length + "\"\n").getBytes());
         fos.write(("RomeFileSetAttrValue SLOPE_STEEP \"" + steepness + "\"\n").getBytes());
-        
+
         if ((contourSystem != null) && (contourSystem.length() > 1)) {
             fos.write(("RomeFileSetAttrValue CONTOUR_SYSTEM_PTR \"" + contourSystem + "\"\n").getBytes());
         }
@@ -425,20 +414,18 @@
             fos.write(("RomeFileSetAttrValue HYD_ELEM_SYSTEM_PTR \"" + hydElemSystem + "\"\n").getBytes());
         }
 
-        if (JSONUtils.checkKeyExistsB(param, KEY_SIMPLE_ROCK_COVER)) 
-        { 
+        if (JSONUtils.checkKeyExistsB(param, KEY_SIMPLE_ROCK_COVER)) {
             fos.write(("RomeFileSetAttrValue SIMPLE_ROCK_COVER \"" + simpleRockCoverPercent + "\"\n").getBytes());
         }
-        
+
         fos.write("RomeEngineRun\n".getBytes());
         for (String r : JSONUtils.getRequestedResults(metainfo)) {
             fos.write(("RomeFileGetAttrValue " + r + "\n").getBytes());
         }
-        
+
 //        fos.write(("RomeFileGetAttrValue CONTOUR_SYSTEM_PTR\n").getBytes());
 //        fos.write(("RomeFileGetAttrValue STRIP_BARRIER_SYSTEM_PTR\n").getBytes());
 //        fos.write(("RomeFileGetAttrValue HYD_ELEMENT_SYSTEM_PTR\n").getBytes());
-
         // optionally only include this line when reporting is requested to save service execution time
         fos.write("READ \"rusle2_report.rsh\"\n".getBytes());
 
@@ -456,10 +443,12 @@
         LOG.info("R2 script: " + file.toString());
     }
 
+
     private String getFilenumber(String filename) {
         return filename.substring(R2_TMP_FILENAME.length(), filename.length() - R2_TMP_FILEEXT.length());
     }
 
+
     @Override
     protected JSONArray createReport() throws Exception {
         String sessionWorkDir = getWorkspaceDir().toString();
@@ -502,6 +491,7 @@
         //LOG.info("Rusle2 report output obj=" + reportObj.toString());        
     }
 
+
     private JSONObject processReportElement(JSONObject obj, String type, String value) throws Exception {
         if ((type.equals("TEXT")) || (type.equals("FILENAME")) || (type.equals("DATE"))) {
             // because the RomeShell returns escaped strings, and the JSONObject in Java re-escapes them

src/java/m/rusle2/V2_0.java

@@ -10,7 +10,6 @@
 import java.io.File;
 import java.io.FileOutputStream;
 import java.util.*;
-import java.util.concurrent.Callable;
 import javax.ws.rs.*;
 import oms3.annotations.*;
 import org.apache.commons.io.FileUtils;
@@ -85,10 +84,11 @@
     List<String> operations;
     List<String> vegetations;
     List<String> residues;
+
     //
 
     @Override
-    protected void preprocess() throws Exception {
+    protected void preProcess() throws Exception {
         // check for requested output.
 
         try {
@@ -103,21 +103,23 @@
             params.add(RES_SLOPE_DELIVERY);
             params.add(RES_SLOPE_T_VALUE);
             params.add(RES_SLOPE_DEGRAD);
-            
+
             // check if these are being set
-        
-        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_CONTOUR_SYSTEM_PTR))
-            params.add("CONTOUR_SYSTEM_PTR");
+            if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_CONTOUR_SYSTEM_PTR)) {
+                params.add("CONTOUR_SYSTEM_PTR");
+            }
 
-        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_STRIP_BARRIER_SYSTEM_PTR))
-            params.add("STRIP_BARRIER_SYSTEM_PTR");
+            if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_STRIP_BARRIER_SYSTEM_PTR)) {
+                params.add("STRIP_BARRIER_SYSTEM_PTR");
+            }
 
-        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_HYD_ELEM_SYSTEM_PTR))
-            params.add("HYD_ELEM_SYSTEM_PTR");
-            
+            if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_HYD_ELEM_SYSTEM_PTR)) {
+                params.add("HYD_ELEM_SYSTEM_PTR");
+            }
+
             getMetainfo().put(KEY_REQUEST_RESULTS, params);
         }
-        
+
 //        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_TOPO_LENGTH))
 //        {
 //            JSONArray aTopoLength = JSONUtils.getJSONArrayParam(param, KEY_TOPO_LENGTH);
@@ -126,7 +128,6 @@
 //                params.add("");
 //            }
 //        }
-
         // check if sufficient input is there.
         //JSONUtils.checkKeyExists(getParamMap(), KEY_CLIMATES);
         JSONUtils.checkKeyExists(getParamMap(), KEY_SOILS);
@@ -140,75 +141,62 @@
         createInputFile(r2script, getMetainfo(), getParamMap());
     }
 
+
     @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
+    protected String process() throws Exception {
+        int result = r2run.executePyrome(new File(getWorkspaceDir(), R2_TMP_FILENAME + R2_TMP_FILEEXT));
+        if (result != 0) {
+            return EXEC_FAILED;
+        }
+        return EXEC_OK;
+    }
 
-            @Override
-            public String call() throws Exception {
-                
-                int result = r2run.executePyrome(new File(getWorkspaceDir(), R2_TMP_FILENAME + R2_TMP_FILEEXT));
-                if (result != 0) {
-                    return EXEC_FAILED;
-                }
-                return EXEC_OK;
-            }
-        };
-    }
 
     @Override
     protected JSONArray createResults() throws Exception {
         JSONArray results = new JSONArray();
-        
         int errors = 0;
-        for (int i = 0; i < operations.size(); i++)
-        {
+        for (int i = 0; i < operations.size(); i++) {
             String op = operations.get(i);
-            if (r2run.isUrlReachable(op))
-                results.put(JSONUtils.dataDesc("OPERATION_" + (i+1), op, "operation is valid"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("OPERATION_INVALID_" + (i+1), op, "OPERATION IS MISSING!"));
-                errors ++;
+            if (r2run.isUrlReachable(op)) {
+                results.put(JSONUtils.dataDesc("OPERATION_" + (i + 1), op, "operation is valid"));
+            } else {
+                results.put(JSONUtils.dataDesc("OPERATION_INVALID_" + (i + 1), op, "OPERATION IS MISSING!"));
+                errors++;
             }
         }
-        for (int i = 0; i < vegetations.size(); i++)
-        {
+        for (int i = 0; i < vegetations.size(); i++) {
             String vege = vegetations.get(i);
-            if (r2run.isUrlReachable(vege))
-                results.put(JSONUtils.dataDesc("VEGETATION_" + (i+1), vege, "vegetation is valid"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("VEGETATION_INVALID_" + (i+1), vege, "VEGETATION IS MISSING"));
-                errors ++;
+            if (r2run.isUrlReachable(vege)) {
+                results.put(JSONUtils.dataDesc("VEGETATION_" + (i + 1), vege, "vegetation is valid"));
+            } else {
+                results.put(JSONUtils.dataDesc("VEGETATION_INVALID_" + (i + 1), vege, "VEGETATION IS MISSING"));
+                errors++;
             }
         }
-        for (int i = 0; i < residues.size(); i++)
-        {
+        for (int i = 0; i < residues.size(); i++) {
             String res = residues.get(i);
-            if (r2run.isUrlReachable(res))
-                results.put(JSONUtils.dataDesc("RESIDUE_" + (i+1), res, "RESIDUE IS VALID"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("RESIDUE_INVALID_" + (i+1), res, "RESIDUE IS MISSING"));
-                errors ++;
+            if (r2run.isUrlReachable(res)) {
+                results.put(JSONUtils.dataDesc("RESIDUE_" + (i + 1), res, "RESIDUE IS VALID"));
+            } else {
+                results.put(JSONUtils.dataDesc("RESIDUE_INVALID_" + (i + 1), res, "RESIDUE IS MISSING"));
+                errors++;
             }
         }
-        
+
 //      results.put(JSONUtils.data(KEY_SLOPE_DELIVERY, 3.0));
         for (String r : JSONUtils.getRequestedResults(getMetainfo())) {
-            if ((errors > 0) && (r.equals(RES_SLOPE_DEGRAD)))
+            if ((errors > 0) && (r.equals(RES_SLOPE_DEGRAD))) {
                 results.put(JSONUtils.dataDesc(r, r2run.getResultPyrome(r), R2_MISSING_XML_FILES_WARNING_MSG));
-            else
+            } else {
                 results.put(JSONUtils.data(r, r2run.getResultPyrome(r)));
+            }
         }
 
         // Get erosion for segments
-        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_TOPO_LENGTH))
-        {
+        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_TOPO_LENGTH)) {
             JSONArray aTopoLength = JSONUtils.getJSONArrayParam(getParamMap(), KEY_TOPO_LENGTH);
-            if (aTopoLength.length() > 0)
-            {
+            if (aTopoLength.length() > 0) {
                 JSONArray aSoilLoss = new JSONArray(r2run.getResultPyromeArray("SEG_SOIL_LOSS", false, false));
                 results.put(JSONUtils.data("SEG_SOIL_LOSS", aSoilLoss));
                 results.put(JSONUtils.data(KEY_CLIMATES, climate));
@@ -218,17 +206,32 @@
                 results.put(JSONUtils.data(KEY_SOILS, aSoil));
                 JSONArray aMgmt = new JSONArray(r2run.getResultPyromeArray("SEG_MAN", true, true));
                 results.put(JSONUtils.data(KEY_MANAGEMENTS, aMgmt));
+                if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_DIVERSIONS)) {
+                    JSONArray aHydElemSystems = new JSONArray(r2run.getResultPyromeArray("HYD_ELEM_SYS", true, true));
+                    results.put(JSONUtils.data(KEY_DIVERSIONS, aHydElemSystems));
+                }
+                if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_STRIP_BARRIER_SYSTEMS)) {
+                    JSONArray aStripBarrierSystems = new JSONArray(r2run.getResultPyromeArray("STRIP_BARRIER_SYS", true, true));
+                    results.put(JSONUtils.data(KEY_STRIP_BARRIER_SYSTEMS, aStripBarrierSystems));
+                }
+                if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_CONTOURSYSTEMS)) {
+                    JSONArray aContourSystems = new JSONArray(r2run.getResultPyromeArray("CONTOUR_SYS", true, true));
+                    results.put(JSONUtils.data(KEY_CONTOURSYSTEMS, aContourSystems));
+                }
             }
-        }    
-        else
-        {
+        } else {
             results.put(JSONUtils.data(KEY_CLIMATES, climate));
-            results.put(JSONUtils.data(KEY_SOILS, soil));
-            results.put(JSONUtils.data(KEY_MANAGEMENTS, mgmt));
+//            results.put(JSONUtils.data(KEY_SOILS, soil));
+//            results.put(JSONUtils.data(KEY_MANAGEMENTS, mgmt));
+            JSONArray aSoil = new JSONArray(r2run.getResultPyromeArray("SEG_SOIL", true, true));
+            results.put(JSONUtils.data(KEY_SOILS, aSoil));
+            JSONArray aMgmt = new JSONArray(r2run.getResultPyromeArray("SEG_MAN", true, true));
+            results.put(JSONUtils.data(KEY_MANAGEMENTS, aMgmt));
         }
         return results;
     }
 
+
     private void createInputFile(File file, JSONObject metainfo, Map<String, JSONObject> param)
             throws Exception {
 
@@ -238,91 +241,133 @@
         double latitude = JSONUtils.getDoubleParam(param, KEY_LATITUDE, 0.0);
         double longitude = JSONUtils.getDoubleParam(param, KEY_LONGITUDE, 0.0);
         double simpleRockCoverPercent = JSONUtils.getDoubleParam(param, KEY_SIMPLE_ROCK_COVER, 0.0);
-        
+
         LOG.info("Rock cover read by service is=" + simpleRockCoverPercent);
 
         JSONArray aRockCover = JSONUtils.getJSONArrayParam(param, KEY_SIMPLE_ROCK_COVER);
-        for (int i=0; i<aRockCover.length(); i++)
-        {
+        for (int i = 0; i < aRockCover.length(); i++) {
             LOG.info("Rock cover [" + i + "]=" + aRockCover.getDouble(i));
             // this is temporary, since R2 will be using slope segments soon
-            if (i==0)
+            if (i == 0) {
                 simpleRockCoverPercent = aRockCover.getDouble(i);
+            }
         }
 
         String climatePtr = JSONUtils.getStringParam(param, KEY_CLIMATES, "");
-        
+
         JSONArray aSoils = JSONUtils.getJSONArrayParam(param, KEY_SOILS);
         String soilPtr[] = new String[(aSoils.length())];
-        for (int i=0; i<aSoils.length(); i++)
-        {
+        for (int i = 0; i < aSoils.length(); i++) {
             LOG.info("soil [" + i + "]=" + aSoils.getInt(i));
             // this is temporary, since R2 will be using slope segments soon
 //            if (i==0)
 //                soilPtr = Integer.toString(aSoils.getInt(i));
         }
-        
+
+        JSONArray diversions = new JSONArray();
+        JSONArray contoursytems = new JSONArray();
+        JSONArray stripBarrrierSystems = new JSONArray();
+
+        // scalar variables for non-segmented runs
+        String contourSystem = "";
+        String stripBarrierSystem = "";
+        String hydElemSystem = "";
+        // Retrieve contourSystem, stripBarrierSystem, hydElemSystem elements:
+        if (JSONUtils.checkKeyExistsB(param, KEY_TOPO_LENGTH)) {   // for slope segments
+            if (JSONUtils.checkKeyExistsB(param, KEY_DIVERSIONS)) {
+                diversions = JSONUtils.getJSONArrayParam(param, KEY_DIVERSIONS);
+            }
+            if (JSONUtils.checkKeyExistsB(param, KEY_CONTOURSYSTEMS)) {
+                contoursytems = JSONUtils.getJSONArrayParam(param, KEY_CONTOURSYSTEMS);
+            }
+            if (JSONUtils.checkKeyExistsB(param, KEY_STRIP_BARRIER_SYSTEMS)) {
+                stripBarrrierSystems = JSONUtils.getJSONArrayParam(param, KEY_STRIP_BARRIER_SYSTEMS);
+            }
+        } else {   // for single slope segment
+            if (JSONUtils.checkKeyExistsB(param, KEY_CONTOUR_SYSTEM_PTR)) {
+                contourSystem = JSONUtils.getStringParam(param, KEY_CONTOUR_SYSTEM_PTR, "");
+            }
+            if (JSONUtils.checkKeyExistsB(param, KEY_STRIP_BARRIER_SYSTEM_PTR)) {
+                stripBarrierSystem = JSONUtils.getStringParam(param, KEY_STRIP_BARRIER_SYSTEM_PTR, "");
+            }
+            if (JSONUtils.checkKeyExistsB(param, KEY_HYD_ELEM_SYSTEM_PTR)) {
+                hydElemSystem = JSONUtils.getStringParam(param, KEY_HYD_ELEM_SYSTEM_PTR, "");
+            }
+        }
+
         JSONArray aTopoLength = new JSONArray();
         JSONArray aTopoSteepness = new JSONArray();
         JSONArray aSoilIdx = new JSONArray();
         JSONArray aManIdx = new JSONArray();
-        if (JSONUtils.checkKeyExistsB(param, KEY_TOPO_LENGTH))
-        {
+        JSONArray aDiversionIdx = new JSONArray();
+        JSONArray aContourIdx = new JSONArray();
+        JSONArray aStripBarrierIdx = new JSONArray();
+        if (JSONUtils.checkKeyExistsB(param, KEY_TOPO_LENGTH)) {
             aTopoLength = JSONUtils.getJSONArrayParam(param, KEY_TOPO_LENGTH);
-            for (int i=0; i<aTopoLength.length(); i++)
-            {
+            for (int i = 0; i < aTopoLength.length(); i++) {
                 LOG.info("Topo Length [" + i + "]=" + aTopoLength.getDouble(i));
                 // this is temporary, since R2 will be using slope segments soon
-                if (i==0)
+                if (i == 0) {
                     length = aTopoLength.getDouble(i);
+                }
             }
         }
 
-        if (JSONUtils.checkKeyExistsB(param, KEY_TOPO_STEEPNESS))
-        {
+        if (JSONUtils.checkKeyExistsB(param, KEY_TOPO_STEEPNESS)) {
             aTopoSteepness = JSONUtils.getJSONArrayParam(param, KEY_TOPO_STEEPNESS);
-            for (int i=0; i<aTopoSteepness.length(); i++)
-            {
+            for (int i = 0; i < aTopoSteepness.length(); i++) {
                 LOG.info("Topo Steepness [" + i + "]=" + aTopoSteepness.getDouble(i));
-                if (i==0)
+                if (i == 0) {
                     steepness = aTopoSteepness.getDouble(i);
+                }
             }
         }
 
-        if (JSONUtils.checkKeyExistsB(param, KEY_SOIL_INDEX))
-        {
+        if (JSONUtils.checkKeyExistsB(param, KEY_SOIL_INDEX)) {
             aSoilIdx = JSONUtils.getJSONArrayParam(param, KEY_SOIL_INDEX);
-            for (int i=0; i<aSoilIdx.length(); i++)
-            {
+            for (int i = 0; i < aSoilIdx.length(); i++) {
                 LOG.info("Soil Index [" + i + "]=" + aSoilIdx.getInt(i));
-    //            if (i==0)
-    //                steepness = aSoilIdx.getInt(i);
+                //            if (i==0)
+                //                steepness = aSoilIdx.getInt(i);
             }
         }
 
-        if (JSONUtils.checkKeyExistsB(param, KEY_MAN_INDEX))
-        {
+        if (JSONUtils.checkKeyExistsB(param, KEY_MAN_INDEX)) {
             aManIdx = JSONUtils.getJSONArrayParam(param, KEY_MAN_INDEX);
-            for (int i=0; i<aManIdx.length(); i++)
-            {
+            for (int i = 0; i < aManIdx.length(); i++) {
                 LOG.info("Man Index [" + i + "]=" + aManIdx.getInt(i));
-    //            if (i==0)
-    //                steepness = aTopoSteepness.getDouble(i);
+                //            if (i==0)
+                //                steepness = aTopoSteepness.getDouble(i);
             }
         }
-        
-        if (JSONUtils.checkKeyExistsB(param, KEY_TOPO_LENGTH))
-            if (!allEqual(aTopoLength.length(), aTopoSteepness.length(), aSoilIdx.length(), aManIdx.length()))
+
+        if (JSONUtils.checkKeyExistsB(param, KEY_DIVERSION_INDEX)) {
+            aDiversionIdx = JSONUtils.getJSONArrayParam(param, KEY_DIVERSION_INDEX);
+            for (int i = 0; i < aDiversionIdx.length(); i++) {
+                LOG.info("Diversion Index [" + i + "]=" + aDiversionIdx.getInt(i));
+            }
+        }
+        if (JSONUtils.checkKeyExistsB(param, KEY_CONTOUR_INDEX)) {
+            aContourIdx = JSONUtils.getJSONArrayParam(param, KEY_CONTOUR_INDEX);
+            for (int i = 0; i < aContourIdx.length(); i++) {
+                LOG.info("Contour Index [" + i + "]=" + aContourIdx.getInt(i));
+            }
+        }
+        if (JSONUtils.checkKeyExistsB(param, KEY_STRIP_BARRIER_INDEX)) {
+            aStripBarrierIdx = JSONUtils.getJSONArrayParam(param, KEY_STRIP_BARRIER_INDEX);
+            for (int i = 0; i < aStripBarrierIdx.length(); i++) {
+                LOG.info("Strip Barrier Index [" + i + "]=" + aStripBarrierIdx.getInt(i));
+            }
+        }
+
+        if (JSONUtils.checkKeyExistsB(param, KEY_TOPO_LENGTH)) {
+            if (!allEqual(aTopoLength.length(), aTopoSteepness.length(), aSoilIdx.length(), aManIdx.length())) {
                 throw new ServiceException("RUSLE2 SEGMENT RUN ERROR! SEGMENT ARRAYS FOR LENGTH, STEEPNESS, AND SOILS MUST BE OF EQUAL SIZE!");
-        
+            }
+        }
+
         //soilPtr = JSONUtils.getStringParam(param, KEY_SOILS, "");
         String managementFormalName[] = new String[]{};
-        
-        String contourSystem = JSONUtils.getStringParam(param, KEY_CONTOUR_SYSTEM_PTR, "");
-        String stripBarrierSystem = JSONUtils.getStringParam(param, KEY_STRIP_BARRIER_SYSTEM_PTR, "");
-        String hydElemSystem = JSONUtils.getStringParam(param, KEY_HYD_ELEM_SYSTEM_PTR, "");
-        
-        
 
 //        String mgmtPtr = JSONUtils.getStringParam(param, KEY_MANAGEMENTS, "");
 //        if (!mgmtPtr.startsWith("managements\\")) {
@@ -333,7 +378,6 @@
         System.setProperty("line.separator", "\n");
         //
         JSONArray managements = JSONUtils.getJSONArrayParam(param, KEY_MGMTS);
-        
 
         LOG.info("managements array=" + managements.toString());
         managementFormalName = new String[managements.length()];
@@ -373,13 +417,16 @@
             operations = translator.getOperationFiles();
             vegetations = translator.getVegetationFiles();
             residues = translator.getResidueFiles();
-            
-            for (String operation : translator.getOperationFiles())
+
+            for (String operation : translator.getOperationFiles()) {
                 System.out.println("operation=" + operation);
-            for (String vege : translator.getVegetationFiles())
+            }
+            for (String vege : translator.getVegetationFiles()) {
                 System.out.println("vegetation=" + vege);
-            for (String residue : translator.getResidueFiles())
-                System.out.println("residue=" + residue);            
+            }
+            for (String residue : translator.getResidueFiles()) {
+                System.out.println("residue=" + residue);
+            }
         }
 
         String altR2db = null;
@@ -417,9 +464,7 @@
 //                    lst.add(token);
 //                }
 //            }
-            
-            for (int i=0;i<aSoils.length();i++)
-            {
+            for (int i = 0; i < aSoils.length(); i++) {
                 String cokey = aSoils.getString(i);
                 //cokey = lst.get(0);  // first soil only for now
                 PostGIS.FileQryResult soil = db.findSoilsByCokey(cokey, longitude);
@@ -432,7 +477,7 @@
                     LOG.info("THE SOIL IS =" + soilPtr + "\n\n\n\n");
                 }
             }
-            
+
         } else {
             LOG.warning("WARNING: Unable to access database to resolve the climate and soil information for this lat/long driven rusle2 model run.  Using deafults.");
         }
@@ -442,7 +487,7 @@
 
         fos.write("import sys\n".getBytes());
         fos.write("sys.path.append('/tmp/csip/bin/bin/win-x86/')\n".getBytes());
-        
+
         fos.write("from pyrome import *\n".getBytes());
         fos.write("from time import sleep\n".getBytes());
 
@@ -453,41 +498,42 @@
         fos.write("    RomeEngineSetAutorun(engine,RX_FALSE)\n".getBytes());
 
         fos.write("    #Inputs\n".getBytes());
-        
-        
-        if (aTopoLength.length() > 1)
-        {
-            String text = "    slopes=[";  
-            for (int i=0; i<aTopoSteepness.length(); i++)
-            {
+
+        if (aTopoLength.length() > 1) {
+            String text = "    slopes=[";
+            for (int i = 0; i < aTopoSteepness.length(); i++) {
                 text += "'" + aTopoSteepness.getInt(i) + "'";
-                text += (i == aTopoSteepness.length()-1) ? "]\n" : ",";
+                text += (i == aTopoSteepness.length() - 1) ? "]\n" : ",";
             }
             fos.write(text.getBytes());
-            text = "    lengths=[";  
-            for (int i=0; i<aTopoLength.length(); i++)
-            {
+            text = "    lengths=[";
+            for (int i = 0; i < aTopoLength.length(); i++) {
                 text += "'" + aTopoLength.getInt(i) + "'";
-                text += (i == aTopoLength.length()-1) ? "]\n" : ",";
+                text += (i == aTopoLength.length() - 1) ? "]\n" : ",";
             }
             fos.write(text.getBytes());
-            text = "    soilIndex=[";  
-            for (int i=0; i<aSoilIdx.length(); i++)
-            {
+            text = "    soilIndex=[";
+            for (int i = 0; i < aSoilIdx.length(); i++) {
                 text += aSoilIdx.getInt(i) + "";
-                text += (i == aSoilIdx.length()-1) ? "]\n" : ",";
+                text += (i == aSoilIdx.length() - 1) ? "]\n" : ",";
             }
             fos.write(text.getBytes());
-            text = "    manIndex=[";  
-            for (int i=0; i<aManIdx.length(); i++)
-            {
+            text = "    manIndex=[";
+            for (int i = 0; i < aManIdx.length(); i++) {
                 text += aManIdx.getInt(i) + "";
-                text += (i == aManIdx.length()-1) ? "]\n" : ",";
+                text += (i == aManIdx.length() - 1) ? "]\n" : ",";
             }
             fos.write(text.getBytes());
-        }
-        else
-        {
+            if ((aDiversionIdx != null) && (aDiversionIdx.length() > 0)) {
+                text = "    diversionIndex=[";
+                for (int i = 0; i < aDiversionIdx.length(); i++) {
+                    text += aDiversionIdx.getInt(i) + "";
+                    text += (i == aDiversionIdx.length() - 1) ? "]\n" : ",";
+                }
+                fos.write(text.getBytes());
+            }
+
+        } else {
             String text = "    slopes=['" + steepness + "']\n";
             fos.write(text.getBytes());
             text = "    lengths=['" + length + "']\n";
@@ -495,73 +541,88 @@
             fos.write("    soilIndex=[0]\n".getBytes());
             fos.write("    manIndex=[0]\n".getBytes());
         }
-        
+
         fos.write("    results = list()\n".getBytes());
 
         fos.write("    #Run a simple profile\n".getBytes());
         fos.write("    profile = RomeFilesOpen(files,'profiles\\\\csippyrome',openFlags)\n".getBytes());
         fos.write("    mgmt = RomeFilesOpen(files, '#XML:lmod_file0.xml',0)\n".getBytes());
         fos.write("    cli = RomeFilesOpen(files, '#XML:cli_file0.xml',0)\n".getBytes());
-        
-        for (int i=0;i<aSoils.length();i++)
-        {
+
+        for (int i = 0; i < aSoils.length(); i++) {
             String text = "    soil" + i + " = RomeFilesOpen(files, '#XML:soils_file" + i + ".xml',0)\n";
             fos.write(text.getBytes());
         }
+        if ((contourSystem != null) && (contourSystem.length() > 1)) {
+            fos.write("    contour = RomeFilesOpen(files, '#XML:contour_file0.xml',0)\n".getBytes());
+            String text = "    RomeFileSetAttrValue(profile, 'CONTOUR_SYSTEM_PTR', 'contour-systems\\\\aaa', 0)\n";
+            fos.write(text.getBytes());
+        }
+
+        if ((stripBarrierSystem != null) && (stripBarrierSystem.length() > 1)) {
+            fos.write("    stripbarr = RomeFilesOpen(files, '#XML:stripbarr_file0.xml',0)\n".getBytes());
+            String text = "    RomeFileSetAttrValue(profile, 'STRIP_BARRIER_SYSTEM_PTR', 'strip-barrier-systems\\\\aaa', 0)\n";
+            fos.write(text.getBytes());
+        }
+
+        if ((hydElemSystem != null) && (hydElemSystem.length() > 1)) {
+            fos.write("    hydelem = RomeFilesOpen(files, '#XML:hydelem_file0.xml',0)\n".getBytes());
+            String text = "    RomeFileSetAttrValue(profile, 'HYD_ELEM_SYSTEM_PTR', 'hydraulic-element-systems\\\\aaa', 0)\n";
+            fos.write(text.getBytes());
+        }
+// need to set these elements based on array settings
+        for (int i = 0; i < aDiversionIdx.length(); i++) {
+            String text = "    hydelem = RomeFilesOpen(files, '#XML:hydelem_file" + i + ".xml',0)\n";
+            fos.write(text.getBytes());
+//            text = "    RomeFileSetAttrValue(profile, 'HYD_ELEM_SYSTEM_PTR', 'hydraulic-element-systems\\\\aaa" + i + "', 0)\n";
+//            fos.write(text.getBytes());
+        }
+
+        for (int i = 0; i < aStripBarrierIdx.length(); i++) {
+            String text = "    stripbarr = RomeFilesOpen(files, '#XML:stripbarr_file" + i + ".xml',0)\n";
+            fos.write(text.getBytes());
+//            text = "    RomeFileSetAttrValue(profile, 'STRIP_BARRIER_SYSTEM_PTR', 'strip-barrier-systems\\\\aaa" + i + "', 0)\n";
+//            fos.write(text.getBytes());
+        }
+
+        for (int i = 0; i < aContourIdx.length(); i++) {
+            String text = "    contour = RomeFilesOpen(files, '#XML:contour_file" + i + ".xml',0)\n";
+            fos.write(text.getBytes());
+//            text = "    RomeFileSetAttrValue(profile, 'CONTOUR_SYSTEM_PTR', 'contour-systems\\\\aaa" + i + "', 0)\n";
+//            fos.write(text.getBytes());
+
+        }
 
         String text = "    RomeFileSetAttrValue(profile, 'SLOPE_HORIZ', '" + length + "', 0)\n";
         fos.write(text.getBytes());
         text = "    RomeFileSetAttrValue(profile, 'SLOPE_STEEP', '" + steepness + "', 0)\n";
         fos.write(text.getBytes());
-        
-        if ((contourSystem != null) && (contourSystem.length() > 1)) {
-            fos.write("    contour = RomeFilesOpen(files, '#XML:contour_file0.xml',0)\n".getBytes());
-            text = "    RomeFileSetAttrValue(profile, 'CONTOUR_SYSTEM_PTR', 'contour-systems\\\\aaa', 0)\n";
-            fos.write(text.getBytes());
-        }
 
-        if ((stripBarrierSystem != null) && (stripBarrierSystem.length() > 1)) {
-            fos.write("    stripbarr = RomeFilesOpen(files, '#XML:stripbarr_file0.xml',0)\n".getBytes());
-            text = "    RomeFileSetAttrValue(profile, 'STRIP_BARRIER_SYSTEM_PTR', 'strip-barrier-systems\\\\aaa', 0)\n";
-            fos.write(text.getBytes());
-        }
-
-        if ((hydElemSystem != null) && (hydElemSystem.length() > 1)) {
-            fos.write("    hydelem = RomeFilesOpen(files, '#XML:hydelem_file0.xml',0)\n".getBytes());
-            text = "    RomeFileSetAttrValue(profile, 'HYD_ELEM_SYSTEM_PTR', 'hydraulic-element-systems\\\\aaa', 0)\n";
-            fos.write(text.getBytes());
-        }
-        
-        if (JSONUtils.checkKeyExistsB(param, KEY_SIMPLE_ROCK_COVER)) 
-        {   
+        if (JSONUtils.checkKeyExistsB(param, KEY_SIMPLE_ROCK_COVER)) {
             text = "    RomeFileSetAttrValue(profile, 'SIMPLE_ROCK_COVER', '" + simpleRockCoverPercent + "' ,0)\n";
             fos.write(text.getBytes());
         }
 
-        if (aTopoLength.length() > 1)
-        {
+        if (aTopoLength.length() > 1) {
             text = "    RomeFileSetAttrSize(profile, 'SEGMENT', " + aTopoLength.length() + ")\n";
             fos.write(text.getBytes());
             text = "    RomeFileSetAttrValue(profile, 'SOIL_LAYER', '#INSERT', 1)\n";
             fos.write(text.getBytes());
-            
-            for (int i=0;i<aSoilIdx.length();i++)
-            {
+
+            for (int i = 0; i < aSoilIdx.length(); i++) {
                 text = "    print('LOAD SOIL WITH SOIL IDX=%s' % " + aSoilIdx.getInt(i) + ", " + i + ")\n";
                 fos.write(text.getBytes());
                 text = "    RomeFileSetAttrValue(profile, 'SOIL_PTR', '" + StringEscapeUtils.escapeJava(soilPtr[aSoilIdx.getInt(i)]) + ".xml', " + i + ")\n";
                 fos.write(text.getBytes());
             }
-            for (int i=0;i<aManIdx.length();i++)
-            {
+            for (int i = 0; i < aManIdx.length(); i++) {
                 text = "    RomeFileSetAttrValue(profile, 'MAN_PTR', '" + StringEscapeUtils.escapeJava(managementFormalName[aManIdx.getInt(i)]) + "', " + i + ")\n";
                 fos.write(text.getBytes());
             }
-            for (int i=0;i<aTopoLength.length();i++)
-            {
+            for (int i = 0; i < aTopoLength.length(); i++) {
                 text = "    RomeFileSetAttrValue(profile, 'SEG_HORIZ', lengths[" + i + "], " + i + ")\n";
                 fos.write(text.getBytes());
-                text = "    RomeFileSetAttrValue(profile, 'SEG_STEEP', slopes[" + i + "], " +i +")\n";
+                text = "    RomeFileSetAttrValue(profile, 'SEG_STEEP', slopes[" + i + "], " + i + ")\n";
                 fos.write(text.getBytes());
                 text = "    RomeFileSetAttrValue(profile, 'SEG_MAN_LAYER', str(manIndex[" + i + "]), " + i + ")\n";
                 fos.write(text.getBytes());
@@ -571,17 +632,28 @@
                 fos.write(text.getBytes());
                 text = "    print('SEG_SOIL_LAYER=%s' % str(soilIndex[" + i + "]), " + i + ")\n";
                 fos.write(text.getBytes());
+
+                if ((diversions != null) && (diversions.length() > 0)) {
+                    text = "    RomeFileSetAttrValue(profile, 'HYD_ELEM_SYSTEM_PTR', 'hydraulic-element-systems\\\\aaa" + aDiversionIdx.getInt(i) + "', " + i + ")\n";
+                    fos.write(text.getBytes());
+                }
+                if ((stripBarrrierSystems != null) && (stripBarrrierSystems.length() > 0)) {
+                    text = "    RomeFileSetAttrValue(profile, 'STRIP_BARRIER_SYSTEM_PTR', 'strip-barrier-systems\\\\aaa" + aStripBarrierIdx.getInt(i) + "', " + i + ")\n";
+                    fos.write(text.getBytes());
+                }
+                if ((contoursytems != null) && (contoursytems.length() > 0)) {
+                    text = "    RomeFileSetAttrValue(profile, 'CONTOUR_SYSTEM_PTR', 'contour-systems\\\\aaa" + aContourIdx.getInt(i) + "', " + i + ")\n";
+                    fos.write(text.getBytes());
+                }
             }
-            
-        }
-        else
-        {
+
+        } else {
             text = "    RomeFileSetAttrValue(profile, 'SOIL_PTR', '" + StringEscapeUtils.escapeJava(soilPtr[0]) + ".xml', " + 0 + ")\n";
             fos.write(text.getBytes());
             text = "    RomeFileSetAttrValue(profile, 'MAN_PTR', '" + StringEscapeUtils.escapeJava(managementFormalName[0]) + "', " + 0 + ")\n";
             fos.write(text.getBytes());
         }
-        
+
         //fos.write("    # Set SOIL_PTR\n".getBytes());
         //text = "    RomeFileSetAttrValue(profile, 'SOIL_PTR', '" + StringEscapeUtils.escapeJava(soilPtr[0]) + ".xml',0)\n";
         //fos.write(text.getBytes());
@@ -591,16 +663,14 @@
 //        text = "    RomeFileSetAttrValue(profile, 'MAN_PTR', '" + StringEscapeUtils.escapeJava(managementFormalName[0]) + "',0)\n";
 //        fos.write(text.getBytes());
 //        fos.write("    print('MAN_PTR=%s' % RomeFileGetAttrValue(profile, 'MAN_PTR', 0))\n".getBytes());
-
         fos.write("    # SET CLIMATE_PTR\n".getBytes());
         fos.write("    RomeFileSetAttrValue(profile, 'CLIMATE_PTR','climates\\\\aaa',0)\n".getBytes());
         fos.write("    print('CLIMATE_PTR=%s' % RomeFileGetAttrValue(profile, 'CLIMATE_PTR', 0))\n".getBytes());
-        
+
 //        if ((contourSystem != null) && (contourSystem.length() > 1)) {
 //            text = "    RomeFileSetAttrValue(profile, 'CONTOUR_SYSTEM_PTR', '" + contourSystem + "',0)\n";
 //            fos.write(text.getBytes());
 //        }
-
         fos.write("    RomeFileSave(profile)\n".getBytes());
         fos.write("    RomeEngineRun(engine)\n".getBytes());
 //        fos.write("    results.append(RomeFileGetAttrValue(profile, 'SLOPE_SOIL_LOSS', 0))\n".getBytes());
@@ -616,10 +686,8 @@
         }
 
         // request erosion by segment, if a segmented run
-        if (aTopoLength.length() > 1)
-        {
-            for (int i=0; i<aTopoLength.length(); i++)
-            {
+        if (aTopoLength.length() > 1) {
+            for (int i = 0; i < aTopoLength.length(); i++) {
                 text = "    results.append(RomeFileGetAttrValue(profile, 'SEG_SOIL_LOSS', " + i + "))\n";
                 fos.write(text.getBytes());
                 text = "    print('SEG_SOIL_LOSS:" + i + "=%s' % (RomeFileGetAttrValue(profile, 'SEG_SOIL_LOSS', " + i + ")))\n";
@@ -636,15 +704,28 @@
 //                fos.write(text.getBytes());
 //                text = "    results.append(RomeFileGetAttrValue(profile, 'SLOPE_SOIL_LOSS', " + i + "))\n";
 //                fos.write(text.getBytes());
-                text = "    print('SEG_SOIL:" + i + "=%s' % RomeFileGetAttrValue(profile, 'SOIL_PTR', " + i  + "))\n";
+                text = "    print('SEG_SOIL:" + i + "=%s' % RomeFileGetAttrValue(profile, 'SOIL_PTR', " + i + "))\n";
                 fos.write(text.getBytes());
-                text = "    print('SEG_MAN:" + i + "=%s' % RomeFileGetAttrValue(profile, 'MAN_PTR', " + i  + "))\n";
+                text = "    print('SEG_MAN:" + i + "=%s' % RomeFileGetAttrValue(profile, 'MAN_PTR', " + i + "))\n";
                 fos.write(text.getBytes());
-                text = "    print('SEG_SOIL_LAYER " + i + "=%s' % (RomeFileGetAttrValue(profile, 'SEG_SOIL_LAYER', " + i  + ")))\n";
+                text = "    print('SEG_SOIL_LAYER " + i + "=%s' % (RomeFileGetAttrValue(profile, 'SEG_SOIL_LAYER', " + i + ")))\n";
                 fos.write(text.getBytes());
-                text = "    print('SEG_MAN_LAYER " + i + "=%s' % (RomeFileGetAttrValue(profile, 'SEG_MAN_LAYER', " + i  + ")))\n";
+                text = "    print('SEG_MAN_LAYER " + i + "=%s' % (RomeFileGetAttrValue(profile, 'SEG_MAN_LAYER', " + i + ")))\n";
+                fos.write(text.getBytes());
+                text = "    print('HYD_ELEM_SYS:" + i + "=%s' % (RomeFileGetAttrValue(profile, 'HYD_ELEM_SYSTEM_PTR', " + i + ")))\n";
+                fos.write(text.getBytes());
+                text = "    print('STRIP_BARRIER_SYS:" + i + "=%s' % (RomeFileGetAttrValue(profile, 'STRIP_BARRIER_SYSTEM_PTR', " + i + ")))\n";
+                fos.write(text.getBytes());
+                text = "    print('CONTOUR_SYS:" + i + "=%s' % (RomeFileGetAttrValue(profile, 'CONTOUR_SYSTEM_PTR', " + i + ")))\n";
                 fos.write(text.getBytes());
             }
+        } else {
+            // always return soil and man ptrs at index 0 - requested by Lucas for IET
+            text = "    print('SEG_SOIL:0" + "=%s' % RomeFileGetAttrValue(profile, 'SOIL_PTR', " + 0 + "))\n";
+            fos.write(text.getBytes());
+            text = "    print('SEG_MAN:0" + "=%s' % RomeFileGetAttrValue(profile, 'MAN_PTR', " + 0 + "))\n";
+            fos.write(text.getBytes());
+            // 
         }
 //        fos.write("    print('SLOPE_DELIVERY=%s' % RomeFileGetAttrValue(profile, 'SLOPE_DELIVERY', 0))\n".getBytes());
 //        fos.write("    print('SLOPE_T_VALUE=%s' % RomeFileGetAttrValue(profile, 'SLOPE_T_VALUE', 0))\n".getBytes());
@@ -674,43 +755,50 @@
         fos.write("    results = linearTest(save)\n".getBytes());
         fos.write("    RomeDatabaseClose(database)\n".getBytes());
         fos.write("    RomeExit(romeDLL)\n".getBytes());
-        
 
-// to do
-// Don't worry about multiple mgmts for now
-        
-
-//        if ((managements != null) && (managements.length() >= 1)) {
-//            fos.write(("FilesOpen \"#XML:" + new File(getWorkspaceDir(), "lmod_file" + 0 + ".xml" + "\"\n")).getBytes());
-//            // fos.write(("Activate \"" + managementFormalName[0] + "\"\n").getBytes());
-//            fos.write(("RomeFileSetAttrValue MAN_BASE_PTR \"" + managementFormalName[0] + "\"\n").getBytes());
-//            mgmt = managementFormalName[0];
-//        }
-
-        // to do 
-        // commented out - using default for now
-        
-        for (int i=0;i<aSoils.length();i++)
-        {
-            String soilHttpPtr = r2db + "/" + soilPtr[i].replace("\\","/") + ".xml";
+        // Prepare multiple soils, contour sys, strips barriers, and hydraulic element files
+        for (int i = 0; i < aSoils.length(); i++) {
+            String soilHttpPtr = r2db + "/" + soilPtr[i].replace("\\", "/") + ".xml";
             r2run.prepareSoilsFile(soilHttpPtr, new File(getWorkspaceDir(), "soils_file" + i + ".xml"), true, String.valueOf(i));
         }
-        
+        for (int i = 0; i < contoursytems.length(); i++) {
+            String contourSys = contoursytems.getString(i);
+            String contourHttpPtr = r2db + "/" + contourSys.replace("\\", "/") + ".xml";
+            r2run.prepareFile(contourHttpPtr, new File(getWorkspaceDir(), "contour_file" + i + ".xml"), "contour", "contour-systems", Integer.toString(i));
+        }
+        for (int i = 0; i < stripBarrrierSystems.length(); i++) {
+            String stripBarrierSys = stripBarrrierSystems.getString(i);
+            String stripbarrHttpPtr = r2db + "/" + stripBarrierSys.replace("\\", "/") + ".xml";
+            r2run.prepareFile(stripbarrHttpPtr, new File(getWorkspaceDir(), "stripbarr_file" + i + ".xml"), "strip-barrier", "strip-barrier-systems", Integer.toString(i));
+        }
+        for (int i = 0; i < diversions.length(); i++) {
+            String hydElemSys = diversions.getString(i);
+            String hydelemHttpPtr = r2db + "/" + hydElemSys.replace("\\", "/") + ".xml";
+            r2run.prepareFile(hydelemHttpPtr, new File(getWorkspaceDir(), "hydelem_file" + i + ".xml"), "hydraulic-element", "hydraulic-element-systems", Integer.toString(i));
+        }
+
+        // prepare individual contour system, strip barrier system, hyd elem sys, if not provided in an array
+        if (JSONUtils.checkKeyExistsB(param, KEY_CONTOUR_SYSTEM_PTR)) {
+            String contourHttpPtr = r2db + "/" + contourSystem.replace("\\", "/") + ".xml";
+            r2run.prepareFile(contourHttpPtr, new File(getWorkspaceDir(), "contour_file0.xml"), "contour", "contour-systems", "");
+        }
+        if (JSONUtils.checkKeyExistsB(param, KEY_STRIP_BARRIER_SYSTEM_PTR)) {
+            String stripbarrHttpPtr = r2db + "/" + stripBarrierSystem.replace("\\", "/") + ".xml";
+            r2run.prepareFile(stripbarrHttpPtr, new File(getWorkspaceDir(), "stripbarr_file0.xml"), "strip-barrier", "strip-barrier-systems", "");
+        }
+        if (JSONUtils.checkKeyExistsB(param, KEY_HYD_ELEM_SYSTEM_PTR)) {
+            String hydelemHttpPtr = r2db + "/" + hydElemSystem.replace("\\", "/") + ".xml";
+            r2run.prepareFile(hydelemHttpPtr, new File(getWorkspaceDir(), "hydelem_file0.xml"), "hydraulic-element", "hydraulic-element-systems", "");
+        }
+
+        // prepare climate file
         String cliHttpPtr = r2db + "/" + climatePtr.replace("\\", "/") + ".xml";
         r2run.prepareClimateFile(cliHttpPtr, new File(getWorkspaceDir(), "cli_file0.xml"));
 
-        String contourHttpPtr = r2db + "/" + contourSystem.replace("\\", "/") + ".xml";
-        r2run.prepareFile(contourHttpPtr, new File(getWorkspaceDir(), "contour_file0.xml"), "contour", "contour-systems", "");
-
-        String stripbarrHttpPtr = r2db + "/" + stripBarrierSystem.replace("\\", "/") + ".xml";
-        r2run.prepareFile(stripbarrHttpPtr, new File(getWorkspaceDir(), "stripbarr_file0.xml"), "strip-barrier", "strip-barrier-systems", "");
-
-        String hydelemHttpPtr = r2db + "/" + hydElemSystem.replace("\\", "/") + ".xml";
-        r2run.prepareFile(hydelemHttpPtr, new File(getWorkspaceDir(), "hydelem_file0.xml"), "hydraulic-element", "hydraulic-element-systems", "");
-        
+        // to do
+        // implement rusle 2 report in pyrome
         // Rusle2 report
         //fos.write("READ \"rusle2_report.rsh\"\n".getBytes());
-
         fos.close();
 
         // Unpack the report rsh file in the work space dir 
@@ -723,10 +811,12 @@
         LOG.info("R2 script: " + file.toString());
     }
 
+
     private String getFilenumber(String filename) {
         return filename.substring(R2_TMP_FILENAME.length(), filename.length() - R2_TMP_FILEEXT.length());
     }
 
+
     @Override
     protected JSONArray createReport() throws Exception {
         String sessionWorkDir = getWorkspaceDir().toString();
@@ -769,6 +859,7 @@
         //LOG.info("Rusle2 report output obj=" + reportObj.toString());        
     }
 
+
     private JSONObject processReportElement(JSONObject obj, String type, String value) throws Exception {
         if ((type.equals("TEXT")) || (type.equals("FILENAME")) || (type.equals("DATE"))) {
             // because the RomeShell returns escaped strings, and the JSONObject in Java re-escapes them
@@ -792,13 +883,18 @@
         }
         return obj;
     }
-    
-    private boolean allEqual(int... vals)
-    {
-        if (vals.length < 2) return true;
+
+
+    private boolean allEqual(int... vals) {
+        if (vals.length < 2) {
+            return true;
+        }
         int a = vals[0];
-        for (int i=0; i<vals.length; i++)
-            if (vals[i] != a) return false;
+        for (int i = 0; i < vals.length; i++) {
+            if (vals[i] != a) {
+                return false;
+            }
+        }
         return true;
     }
 }

src/java/m/rusle2/rusle2check.java

@@ -5,41 +5,28 @@
 package m.rusle2;
 
 import c.PostGIS;
-import csip.Config;
 import csip.ServiceException;
 import java.io.File;
-import java.io.FileOutputStream;
 import java.util.*;
-import java.util.concurrent.Callable;
 import javax.ws.rs.*;
 import oms3.annotations.*;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringEscapeUtils;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONObject;
-import org.codehaus.jettison.json.JSONException;
 import org.w3c.dom.Document;
 import org.w3c.dom.NodeList;
 import csip.ModelDataService;
-import static csip.ModelDataService.EXEC_FAILED;
 import static csip.ModelDataService.EXEC_OK;
 import static csip.ModelDataService.KEY_REQUEST_RESULTS;
-import static csip.ModelDataService.REPORT_DIM;
-import static csip.ModelDataService.REPORT_NAME;
-import static csip.ModelDataService.REPORT_TYPE;
-import static csip.ModelDataService.REPORT_VALUE;
 import static csip.ModelDataService.VALUE;
 import static util.ErosionConst.*;
 
-import csip.utils.Binaries;
 import csip.utils.JSONUtils;
-import csip.utils.Services;
 import csip.annotations.Polling;
-import static m.rusle2.R2Run.LOG;
 
 /**
- * REST Web Service. Check if Operations and vegetation files are in place on backend (nginx) to support R2 run
- *                     If files are missing Rusle2 runs without error using default operations and crops instead.
+ * REST Web Service. Check if Operations and vegetation files are in place on
+ * backend (nginx) to support R2 run If files are missing Rusle2 runs without
+ * error using default operations and crops instead.
  *
  * @author wlloyd, od
  */
@@ -89,10 +76,9 @@
     List<String> vegetations;
     List<String> residues;
 
+
     @Override
-    protected void preprocess() throws Exception {
-        // check for requested output.
-
+    protected void preProcess() throws Exception {
         // Validate that this is a Rulse 2 run
         try {
             LOG.info("\n\n\n\n\nMETAINFO:");
@@ -106,12 +92,12 @@
             params.add(RES_SLOPE_DELIVERY);
             params.add(RES_SLOPE_T_VALUE);
             params.add(RES_SLOPE_DEGRAD);
-            
+
             // check if these are being set
             params.add("CONTOUR_SYSTEM_PTR");
             params.add("STRIP_BARRIER_SYSTEM_PTR");
             params.add("HYD_ELEM_SYSTEM_PTR");
-            
+
             getMetainfo().put(KEY_REQUEST_RESULTS, params);
         }
 
@@ -127,68 +113,57 @@
         createInputFile(r2script, getMetainfo(), getParamMap());
     }
 
+
     @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
-
-            @Override
-            public String call() throws Exception {
-                
+    protected String process() throws Exception {
 //                int result = r2run.execute(new File(getWorkspaceDir(), R2_TMP_FILENAME + R2_TMP_FILEEXT));
 //                if (result != 0) {
 //                    return EXEC_FAILED;
 //                }
-                return EXEC_OK;
-            }
-        };
+        return EXEC_OK;
     }
 
+
     @Override
     protected JSONArray createResults() throws Exception {
         JSONArray results = new JSONArray();
-        
+
         int errors = 0;
-        for (int i = 0; i < operations.size(); i++)
-        {
+        for (int i = 0; i < operations.size(); i++) {
             String op = operations.get(i);
-            if (r2run.isUrlReachable(op))
-                results.put(JSONUtils.dataDesc("Operation_" + (i+1), op, "operation is valid"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("OPERATION_INVALID_" + (i+1), op, "OPERATION IS MISSING!"));
-                errors ++;
+            if (r2run.isUrlReachable(op)) {
+                results.put(JSONUtils.dataDesc("Operation_" + (i + 1), op, "operation is valid"));
+            } else {
+                results.put(JSONUtils.dataDesc("OPERATION_INVALID_" + (i + 1), op, "OPERATION IS MISSING!"));
+                errors++;
             }
         }
-        for (int i = 0; i < vegetations.size(); i++)
-        {
+        for (int i = 0; i < vegetations.size(); i++) {
             String vege = vegetations.get(i);
-            if (r2run.isUrlReachable(vege))
-                results.put(JSONUtils.dataDesc("Vegetation_" + (i+1), vege, "vegetation is valid"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("VEGETATION_INVALID_" + (i+1), vege, "VEGETATION IS MISSING"));
-                errors ++;
+            if (r2run.isUrlReachable(vege)) {
+                results.put(JSONUtils.dataDesc("Vegetation_" + (i + 1), vege, "vegetation is valid"));
+            } else {
+                results.put(JSONUtils.dataDesc("VEGETATION_INVALID_" + (i + 1), vege, "VEGETATION IS MISSING"));
+                errors++;
             }
         }
-        for (int i = 0; i < residues.size(); i++)
-        {
+        for (int i = 0; i < residues.size(); i++) {
             String res = residues.get(i);
-            if (r2run.isUrlReachable(res))
-                results.put(JSONUtils.dataDesc("Residue_" + (i+1), res, "residue is valid"));
-            else
-            {
-                results.put(JSONUtils.dataDesc("RESIDUE_INVALID_" + (i+1), res, "RESIDUE IS MISSING"));
-                errors ++;
+            if (r2run.isUrlReachable(res)) {
+                results.put(JSONUtils.dataDesc("Residue_" + (i + 1), res, "residue is valid"));
+            } else {
+                results.put(JSONUtils.dataDesc("RESIDUE_INVALID_" + (i + 1), res, "RESIDUE IS MISSING"));
+                errors++;
             }
         }
-        
+
 //        results.put(JSONUtils.data(KEY_CLIMATES, climate));
 //        results.put(JSONUtils.data(KEY_SOILS, soil));
 //        results.put(JSONUtils.data(KEY_MANAGEMENTS, mgmt));
-        
         return results;
     }
 
+
     private void createInputFile(File file, JSONObject metainfo, Map<String, JSONObject> param)
             throws Exception {
         boolean resolveLoc = JSONUtils.getBooleanParam(param, KEY_RESOLVE_LOCATION, false);
@@ -214,7 +189,6 @@
         System.setProperty("line.separator", "\n");
         //
         JSONArray managements = JSONUtils.getJSONArrayParam(param, KEY_MGMTS);
-        
 
         LOG.info("managements array=" + managements.toString());
         managementFormalName = new String[managements.length()];
@@ -247,14 +221,17 @@
             operations = translator.getOperationFiles();
             vegetations = translator.getVegetationFiles();
             residues = translator.getResidueFiles();
-            
-            for (String operation : translator.getOperationFiles())
+
+            for (String operation : translator.getOperationFiles()) {
                 System.out.println("operation=" + operation);
-            for (String vege : translator.getVegetationFiles())
+            }
+            for (String vege : translator.getVegetationFiles()) {
                 System.out.println("vegetation=" + vege);
-            for (String residue : translator.getResidueFiles())
+            }
+            for (String residue : translator.getResidueFiles()) {
                 System.out.println("residue=" + residue);
-            
+            }
+
         }
 
         String altR2db = null;
@@ -307,6 +284,7 @@
 
     }
 
+
     private String getFilenumber(String filename) {
         return filename.substring(R2_TMP_FILENAME.length(), filename.length() - R2_TMP_FILEEXT.length());
     }
@@ -316,7 +294,6 @@
 //        JSONArray reportItemsOutput = new JSONArray();
 //        return reportItemsOutput;
 //    }
-
 //    private JSONObject processReportElement(JSONObject obj, String type, String value) throws Exception {
 //        if ((type.equals("TEXT")) || (type.equals("FILENAME")) || (type.equals("DATE"))) {
 //            // because the RomeShell returns escaped strings, and the JSONObject in Java re-escapes them

src/java/m/sci/SCITest.java

@@ -4,6 +4,9 @@
  */
 package m.sci;
 
+// THIS CODE COULD BE OF USE AS AN SCI REFERENCE
+// OR DELETED
+// WJL 3/29/2016
 /**
  *
  * @author od

src/java/m/sci/V1_3.java

@@ -72,14 +72,15 @@
 
     // this is the 0.2 / 2.54 conversion, where 2.54 is ER-renner
     static final Double SCI_CONVERSION_FACTOR = .078740157;
-    
+
     String scitotal = "0.0";
     String sci_om = "0.0";
     String sci_fo = "0.0";
     String sci_er = "0.0";
 
+
     @Override
-    protected void preprocess() throws Exception {
+    protected void preProcess() throws Exception {
         // check if sufficient input is there.
         if (!((JSONUtils.checkKeyExistsB(getParamMap(), KEY_SOILS))
                 || (JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_SOIL)))) {
@@ -91,149 +92,141 @@
             throw new ServiceException("Key not found :SCI MANAGEMENT");
         }
     }
-    
+
 
     @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
+    protected String process() throws Exception {
+        double r2erosion = 0.0;
+        double r2sci = 0.0;
+        double r2sci_om = 0.0;
+        double r2sci_fo = 0.0;
+        double r2sci_er = 0.0;
 
-            @Override
-            public String call() throws Exception {
-                double r2erosion = 0.0;
-                double r2sci = 0.0;
-                double r2sci_om = 0.0;
-                double r2sci_fo = 0.0;
-                double r2sci_er = 0.0;
+        File[] dummy = new File[0]; // the client function should check for null array.
+        JSONObject syncRequest = JSONUtils.clone(getRequest());
+        String status;
+        String error;
+        if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_LENGTH)
+                && JSONUtils.checkKeyExistsB(getParamMap(), KEY_STEEPNESS)) {
+            // do a r2 call >>>
+            JSONArray req_results = new JSONArray();
+            req_results.put(RES_SOIL_COND_INDEX_RESULT);
+            req_results.put(RES_SOIL_COND_INDEX_OM_SUBFACTOR);
+            req_results.put(RES_SOIL_COND_INDEX_FO_SUBFACTOR);
+            req_results.put(RES_SOIL_COND_INDEX_ER_SUBFACTOR);
+            req_results.put(RES_SLOPE_DELIVERY);
+            req_results.put(RES_SLOPE_T_VALUE);
+            req_results.put(RES_SLOPE_DEGRAD);
+            syncRequest.getJSONObject(KEY_METAINFO).put(KEY_MODE, SYNC);
+            syncRequest.getJSONObject(KEY_METAINFO).put(KEY_REQUEST_RESULTS, req_results);
+            //LOG.info("This is the request =) : "+getRequest().toString());
+            //String url = Config.getString("codebase.url", "bad")+"/csip-erosion/m/rusle2/1.2";
+            //LOG.info(url);
+            LOG.info("STARTING RUSLE2");
+            LOG.info("R2 Request" + syncRequest);
+            //JSONObject r2Response = new Client(LOG).doPOST("http://localhost:8080/csip-erosion/m/rusle2/1.2", getRequest(), dummy);
+            JSONObject r2Response = new Client(LOG).doPOST("http://localhost:8080/csip-erosion/m/rusle2/1.3", syncRequest);
+            LOG.info("R2 Response " + syncRequest);
 
-                File[] dummy = new File[0]; // the client function should check for null array.
-                JSONObject syncRequest = JSONUtils.clone(getRequest());
-                String status;
-                String error;
-                if (JSONUtils.checkKeyExistsB(getParamMap(), KEY_LENGTH)
-                        && JSONUtils.checkKeyExistsB(getParamMap(), KEY_STEEPNESS)) {
-                    // do a r2 call >>>
-                    JSONArray req_results = new JSONArray();
-                    req_results.put(RES_SOIL_COND_INDEX_RESULT);
-                    req_results.put(RES_SOIL_COND_INDEX_OM_SUBFACTOR);
-                    req_results.put(RES_SOIL_COND_INDEX_FO_SUBFACTOR);
-                    req_results.put(RES_SOIL_COND_INDEX_ER_SUBFACTOR);
-                    req_results.put(RES_SLOPE_DELIVERY);
-                    req_results.put(RES_SLOPE_T_VALUE);
-                    req_results.put(RES_SLOPE_DEGRAD);
-                    syncRequest.getJSONObject(KEY_METAINFO).put(KEY_MODE, SYNC);
-                    syncRequest.getJSONObject(KEY_METAINFO).put(KEY_REQUEST_RESULTS, req_results);
-                    //LOG.info("This is the request =) : "+getRequest().toString());
-                    //String url = Config.getString("codebase.url", "bad")+"/csip-erosion/m/rusle2/1.2";
-                    //LOG.info(url);
-                    LOG.info("STARTING RUSLE2");
-                    LOG.info("R2 Request" + syncRequest);
-                    //JSONObject r2Response = new Client(LOG).doPOST("http://localhost:8080/csip-erosion/m/rusle2/1.2", getRequest(), dummy);
-                    JSONObject r2Response = new Client(LOG).doPOST("http://localhost:8080/csip-erosion/m/rusle2/1.3", syncRequest);
-                    LOG.info("R2 Response "+ syncRequest);
+            status = r2Response.getJSONObject(KEY_METAINFO).getString(KEY_STATUS);
 
-                    status = r2Response.getJSONObject(KEY_METAINFO).getString(KEY_STATUS);
-                    
-                    if(status.equals(FAILED)){
-                        error = r2Response.getJSONObject(KEY_METAINFO).getString(ERROR);
-                        return error;
-                    }
-                        
-                    
-                    Map<String, JSONObject> r2Results = JSONUtils.preprocess(r2Response.getJSONArray(KEY_RESULT));
+            if (status.equals(FAILED)) {
+                error = r2Response.getJSONObject(KEY_METAINFO).getString(ERROR);
+                return error;
+            }
 
-                    r2erosion = Double.parseDouble(r2Results.get(RES_SLOPE_DEGRAD).getString(VALUE));
-                    r2sci = Double.parseDouble(r2Results.get(RES_SOIL_COND_INDEX_RESULT).getString(VALUE));
-                    r2sci_om = Double.parseDouble(r2Results.get(RES_SOIL_COND_INDEX_OM_SUBFACTOR).getString(VALUE));
-                    r2sci_fo = Double.parseDouble(r2Results.get(RES_SOIL_COND_INDEX_FO_SUBFACTOR).getString(VALUE));
-                    r2sci_er = Double.parseDouble(r2Results.get(RES_SOIL_COND_INDEX_ER_SUBFACTOR).getString(VALUE));
+            Map<String, JSONObject> r2Results = JSONUtils.preprocess(r2Response.getJSONArray(KEY_RESULT));
 
-                    scitotal = Double.toString(r2sci);
-                    sci_om = Double.toString(r2sci_om);
-                    sci_fo = Double.toString(r2sci_fo);
-                    sci_er = Double.toString(r2sci_er);
-                }
-                // Check if wind barriers (WEPS) tag exists, if so run weps, otherwise return...
-                if (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_BARRIERS)) {
-                    return EXEC_FAILED;
-                }
-                // only add if the weps soil has not been specified natively
-                if (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_SOIL)) {
-                    LOG.info("There is not soil");
-                    JSONObject wepsSoil = new JSONObject();
-                    wepsSoil.put("name", WEPS_KEY_SOIL);
-                    wepsSoil.put("value", getParamMap().get(KEY_SOILS).getJSONArray("value").get(0));
+            r2erosion = Double.parseDouble(r2Results.get(RES_SLOPE_DEGRAD).getString(VALUE));
+            r2sci = Double.parseDouble(r2Results.get(RES_SOIL_COND_INDEX_RESULT).getString(VALUE));
+            r2sci_om = Double.parseDouble(r2Results.get(RES_SOIL_COND_INDEX_OM_SUBFACTOR).getString(VALUE));
+            r2sci_fo = Double.parseDouble(r2Results.get(RES_SOIL_COND_INDEX_FO_SUBFACTOR).getString(VALUE));
+            r2sci_er = Double.parseDouble(r2Results.get(RES_SOIL_COND_INDEX_ER_SUBFACTOR).getString(VALUE));
 
-                    LOG.info("The soil is: " + wepsSoil.toString());
-                    //getParamMap().put(WEPS_KEY_SOIL, wepsSoil);
-                    syncRequest.getJSONArray(KEY_PARAMETER).put(wepsSoil);
-                }
-                if (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_MANAGEMENT)) {
+            scitotal = Double.toString(r2sci);
+            sci_om = Double.toString(r2sci_om);
+            sci_fo = Double.toString(r2sci_fo);
+            sci_er = Double.toString(r2sci_er);
+        }
+        // Check if wind barriers (WEPS) tag exists, if so run weps, otherwise return...
+        if (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_BARRIERS)) {
+            return EXEC_FAILED;
+        }
+        // only add if the weps soil has not been specified natively
+        if (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_SOIL)) {
+            LOG.info("There is not soil");
+            JSONObject wepsSoil = new JSONObject();
+            wepsSoil.put("name", WEPS_KEY_SOIL);
+            wepsSoil.put("value", getParamMap().get(KEY_SOILS).getJSONArray("value").get(0));
 
-                    JSONObject lmodweps = (JSONObject) JSONUtils.getJSONArrayParam(getParamMap(), KEY_MGMTS).get(0);
-                    JSONObject lmodwepsobj = JSONUtils.data(WEPS_KEY_MANAGEMENT, lmodweps);
-                    //getParamMap().put(WEPS_KEY_MANAGEMENT, lmodwepsobj);
-                    syncRequest.getJSONArray(KEY_PARAMETER).put(lmodwepsobj);
-                }
+            LOG.info("The soil is: " + wepsSoil.toString());
+            //getParamMap().put(WEPS_KEY_SOIL, wepsSoil);
+            syncRequest.getJSONArray(KEY_PARAMETER).put(wepsSoil);
+        }
+        if (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_MANAGEMENT)) {
 
-                LOG.info("Trying to invoke WEPS for SCI");
+            JSONObject lmodweps = (JSONObject) JSONUtils.getJSONArrayParam(getParamMap(), KEY_MGMTS).get(0);
+            JSONObject lmodwepsobj = JSONUtils.data(WEPS_KEY_MANAGEMENT, lmodweps);
+            //getParamMap().put(WEPS_KEY_MANAGEMENT, lmodwepsobj);
+            syncRequest.getJSONArray(KEY_PARAMETER).put(lmodwepsobj);
+        }
 
-                //JSONObject wepsResponse = new Client(LOG).doPOST("http://localhost:8080/csip-erosion/m/weps/1.2", getRequest(), dummy);
-                JSONObject wepsResponse = new Client(LOG).doPOST("http://localhost:8080/csip-erosion/m/weps/1.3", syncRequest);
-                status = wepsResponse.getJSONObject(KEY_METAINFO).getString(KEY_STATUS);
-                
-                
-                if(status.equals(FAILED))
-                {
-                    error = wepsResponse.getJSONObject(KEY_METAINFO).getString(ERROR);
-                    return error;
-                }
-                
-                Map<String, JSONObject> wepsResults = JSONUtils.preprocess(wepsResponse.getJSONArray(KEY_RESULT));
+        LOG.info("Trying to invoke WEPS for SCI");
 
-                double wepserosion = (Double.parseDouble(wepsResults.get(WEPS_RES_WIND_EROS).getString(VALUE)));
-                    double wepssci = Double.parseDouble(wepsResults.get(WEPS_RES_SOIL_COND_INDEX).getString(VALUE));
-                double wepssci_om = Double.parseDouble(wepsResults.get(WEPS_RES_SCI_OM_FACTOR).getString(VALUE));
-                double wepssci_fo = Double.parseDouble(wepsResults.get(WEPS_RES_SCI_FO_FACTOR).getString(VALUE));
-                double wepssci_er = Double.parseDouble(wepsResults.get(WEPS_RES_SCI_ER_FACTOR).getString(VALUE));
+        //JSONObject wepsResponse = new Client(LOG).doPOST("http://localhost:8080/csip-erosion/m/weps/1.2", getRequest(), dummy);
+        JSONObject wepsResponse = new Client(LOG).doPOST("http://localhost:8080/csip-erosion/m/weps/1.3", syncRequest);
+        status = wepsResponse.getJSONObject(KEY_METAINFO).getString(KEY_STATUS);
 
-                LOG.info("r2 erosion=" + r2erosion);
-                LOG.info("r2 sci=" + r2sci);
-                LOG.info("r2 sci_om=" + r2sci_om);
-                LOG.info("r2 sci_fo=" + r2sci_fo);
-                LOG.info("r2 sci_er=" + r2sci_er);
-                LOG.info("weps erosion=" + wepserosion);
-                LOG.info("weps sci=" + wepssci);
-                LOG.info("weps sci_om=" + wepssci_om);
-                LOG.info("weps sci_fo=" + wepssci_fo);
-                LOG.info("weps sci_er=" + wepssci_er);
+        if (status.equals(FAILED)) {
+            error = wepsResponse.getJSONObject(KEY_METAINFO).getString(ERROR);
+            return error;
+        }
 
-                // if weps only
-                if (!((JSONUtils.checkKeyExistsB(getParamMap(), KEY_LENGTH))
-                        && (JSONUtils.checkKeyExistsB(getParamMap(), KEY_STEEPNESS)))) {
-                    scitotal = Double.toString(wepssci);
-                    sci_om = Double.toString(wepssci_om);
-                    sci_fo = Double.toString(wepssci_fo);
-                    sci_er = Double.toString(wepssci_er);
-                    return EXEC_OK;
-                }
-                if (wepserosion > r2erosion) // if weps wind erosion is more than rusle2 soil erosion
-                {
-                    scitotal = Double.toString(wepssci - SCI_CONVERSION_FACTOR * r2erosion);
-                    sci_er = Double.toString(wepssci_er + r2sci_er - 1);
-                    sci_om = Double.toString(wepssci_om);
-                    sci_fo = Double.toString(wepssci_fo);
-                } else // if rusle2 soil erosion is more than weps wind erosion
-                {
-                    scitotal = Double.toString(r2sci - SCI_CONVERSION_FACTOR * wepserosion);
-                    sci_om = Double.toString(r2sci_om);
-                    sci_fo = Double.toString(r2sci_fo);
-                    sci_er = Double.toString(wepssci_er + r2sci_er - 1);
-                }
-                return EXEC_OK;
-            }
-        };
+        Map<String, JSONObject> wepsResults = JSONUtils.preprocess(wepsResponse.getJSONArray(KEY_RESULT));
+
+        double wepserosion = (Double.parseDouble(wepsResults.get(WEPS_RES_WIND_EROS).getString(VALUE)));
+        double wepssci = Double.parseDouble(wepsResults.get(WEPS_RES_SOIL_COND_INDEX).getString(VALUE));
+        double wepssci_om = Double.parseDouble(wepsResults.get(WEPS_RES_SCI_OM_FACTOR).getString(VALUE));
+        double wepssci_fo = Double.parseDouble(wepsResults.get(WEPS_RES_SCI_FO_FACTOR).getString(VALUE));
+        double wepssci_er = Double.parseDouble(wepsResults.get(WEPS_RES_SCI_ER_FACTOR).getString(VALUE));
+
+        LOG.info("r2 erosion=" + r2erosion);
+        LOG.info("r2 sci=" + r2sci);
+        LOG.info("r2 sci_om=" + r2sci_om);
+        LOG.info("r2 sci_fo=" + r2sci_fo);
+        LOG.info("r2 sci_er=" + r2sci_er);
+        LOG.info("weps erosion=" + wepserosion);
+        LOG.info("weps sci=" + wepssci);
+        LOG.info("weps sci_om=" + wepssci_om);
+        LOG.info("weps sci_fo=" + wepssci_fo);
+        LOG.info("weps sci_er=" + wepssci_er);
+
+        // if weps only
+        if (!((JSONUtils.checkKeyExistsB(getParamMap(), KEY_LENGTH))
+                && (JSONUtils.checkKeyExistsB(getParamMap(), KEY_STEEPNESS)))) {
+            scitotal = Double.toString(wepssci);
+            sci_om = Double.toString(wepssci_om);
+            sci_fo = Double.toString(wepssci_fo);
+            sci_er = Double.toString(wepssci_er);
+            return EXEC_OK;
+        }
+        if (wepserosion > r2erosion) // if weps wind erosion is more than rusle2 soil erosion
+        {
+            scitotal = Double.toString(wepssci - SCI_CONVERSION_FACTOR * r2erosion);
+            sci_er = Double.toString(wepssci_er + r2sci_er - 1);
+            sci_om = Double.toString(wepssci_om);
+            sci_fo = Double.toString(wepssci_fo);
+        } else // if rusle2 soil erosion is more than weps wind erosion
+        {
+            scitotal = Double.toString(r2sci - SCI_CONVERSION_FACTOR * wepserosion);
+            sci_om = Double.toString(r2sci_om);
+            sci_fo = Double.toString(r2sci_fo);
+            sci_er = Double.toString(wepssci_er + r2sci_er - 1);
+        }
+        return EXEC_OK;
     }
 
+
     @Override
     protected JSONArray createResults() throws Exception {
         JSONArray results = new JSONArray();
@@ -246,23 +239,12 @@
         return results;
     }
 
-//    @Override
-//    protected JSONObject describe() throws JSONException {
-//        try {
-//            // use this from version 1.1
-//            String tmpl = IOUtils.toString(V1_2.class.getResource("/src/m/sci/V1_2Req.json"));
-//            JSONObject model = new JSONObject(tmpl);
-//            return model;
-//        } catch (IOException ex) {
-//            throw new RuntimeException("tmpl");
-//        }
-//    }
-
     @Override
     protected long getNextPoll() {
         return 1000;
     }
 
+
     @Override
     protected long getFirstPoll() {
         return 1000;

src/java/m/stir/V1_2.java

@@ -9,16 +9,13 @@
 import csip.ServiceException;
 import java.io.File;
 import java.io.FileOutputStream;
-import java.io.IOException;
 import java.util.*;
 import java.util.concurrent.Callable;
 import javax.ws.rs.*;
 import oms3.annotations.*;
-import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONObject;
-import org.codehaus.jettison.json.JSONException;
 import org.w3c.dom.Document;
 import org.w3c.dom.NodeList;
 import csip.ModelDataService;
@@ -58,10 +55,11 @@
 
     // number of OP_PTR items
     int sizeOfOpPtr = 0;
+
     //
 
     @Override
-    protected void preprocess() throws Exception {
+    protected void preProcess() throws Exception {
         // check for requested output.
 // no required output params implemented yet for STIR ouput
         try {
@@ -85,20 +83,13 @@
         createInputFile(r2script, getMetainfo(), getParamMap());
     }
 
+
     @Override
-    protected Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
+    protected String process() throws Exception {
+        int result = r2run.execute(new File(getWorkspaceDir(), R2_TMP_FILENAME + R2_TMP_FILEEXT));
+        return result == 0 ? EXEC_OK : EXEC_FAILED;
+    }
 
-            @Override
-            public String call() throws Exception {
-                int result = r2run.execute(new File(getWorkspaceDir(), R2_TMP_FILENAME + R2_TMP_FILEEXT));
-//                if (result != 0) {
-//                    throw new ServiceException("Error executing model.");
-//                }
-                return result == 0 ? EXEC_OK : EXEC_FAILED;
-            }
-        };
-    }
 
     @Override
     protected JSONArray createResults() throws Exception {
@@ -152,32 +143,6 @@
         return results;
     }
 
-//    @Override
-//    protected JSONObject describe() throws JSONException {
-//        try {
-//            // use this from version 1.1
-//            String tmpl = IOUtils.toString(V1_2.class.getResource("/src/m/stir/V1_2Req.json"));
-//            JSONObject model = new JSONObject(tmpl);
-//            return model;
-//        } catch (IOException ex) {
-//            throw new RuntimeException("tmpl");
-//        }
-//    }
-
-    @Override
-    protected long getNextPoll() {
-        return 1000;
-    }
-
-    @Override
-    protected long getFirstPoll() {
-        return 1000;
-    }
-
-//    @Override
-//    public String getModelName() {
-//        return "stir/1.2";
-//    }
     private void createInputFile(File file, JSONObject metainfo, Map<String, JSONObject> param)
             throws Exception {
 
@@ -314,9 +279,9 @@
         LOG.info("R2 script: " + file.toString());
     }
 
+
     private String getFilenumber(String filename) {
         return filename.substring(R2_TMP_FILENAME.length(), filename.length() - R2_TMP_FILEEXT.length());
     }
 
-   
 }

src/java/m/weps/V1_3.java

@@ -9,6 +9,7 @@
 import csip.Config;
 import csip.ModelDataService;
 import csip.ServiceException;
+import csip.annotations.Polling;
 import csip.utils.Binaries;
 import csip.utils.JSONUtils;
 import java.io.*;
@@ -20,7 +21,6 @@
 import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.Map;
-import java.util.concurrent.Callable;
 import java.util.logging.Level;
 import javax.ws.rs.Path;
 import man2weps.WepsTranslator;
@@ -53,6 +53,7 @@
 @Description("WEPS")
 @VersionInfo("1.3")
 @Path("m/weps/1.3")
+@Polling(first = 25000, next = 2000)
 public class V1_3 extends ModelDataService {
 
     String sessionWorkDir = "";
@@ -81,30 +82,27 @@
     private String sWindgenStation = "";
     private boolean cropCalibrationMode = false;
 
+
     @Override
-    public void preprocess() throws Exception {
+    public void preProcess() throws Exception {
         JSONUtils.checkKeyExists(getParamMap(), WEPS_KEY_MANAGEMENT);
         JSONUtils.checkKeyExists(getParamMap(), WEPS_KEY_FIELD_LENGTH);
         JSONUtils.checkKeyExists(getParamMap(), WEPS_KEY_FIELD_WIDTH);
         JSONUtils.checkKeyExists(getParamMap(), WEPS_KEY_LATITUDE);
         JSONUtils.checkKeyExists(getParamMap(), WEPS_KEY_LONGITUDE);
 
-        if (JSONUtils.checkKeyExistsB(getParamMap(), WEPS_FIELD_BOUNDARY))
-        {
+        if (JSONUtils.checkKeyExistsB(getParamMap(), WEPS_FIELD_BOUNDARY)) {
             appendMetainfoWarning(WEPS_FIELD_BOUNDARY_IGNORED);
         }
 
-        if (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_ELEVATION))
-        {
+        if (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_ELEVATION)) {
             appendMetainfoWarning(WEPS_ELEVATION_DEFAULT_USED);
         }
-        if ((!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_SOIL)) &&
-            (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_SOIL_FILE)))
-        {
+        if ((!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_SOIL))
+                && (!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_SOIL_FILE))) {
             throw new ServiceException("No SOIL component key or soil file pointer provided!  Cannot run WEPS.");
         }
 
-        
 //        if ((!JSONUtils.checkKeyExistsB(getParamMap(), WEPS_FIELD_BOUNDARY))
 //                && !((JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_LATITUDE))
 //                && (JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_LONGITUDE))
@@ -114,120 +112,97 @@
 //        }
     }
 
+
     @Override
-    public Callable<String> createCallable() throws Exception {
-        return new Callable<String>() {
+    protected String process() throws Exception {
+        String error = null;
+        ProcessComponent pc = new ProcessComponent();
+        try {
+            db = PostGIS.singleton();
+        } catch (Exception e) {
+            LOG.severe("Error obtaining DB connection in WEPS run!");
+            throw new ServiceException("WEPS error: Cannot obtain geospatial db connection");
+        }
 
-            // to do
-            // refactor & make smaller
-            @Override
-            public String call() throws Exception {
-                String error = null;
-                ProcessComponent pc = new ProcessComponent();
+        LOG.info("The default CISP WEPS user dir is=" + System.getProperty("user.dir"));
+
+        try {
+            File workDir = getWorkspaceDir();
+            sessionWorkDir = workDir.toString();
+            binDir = Config.getString("m.bin.dir", "/tmp/csip/bin");
+
+            // check that required parameters exist. populate them in wmr data object
+            loadRequiredParameters();
+
+            // get the mgmt as a json obj and create a WEPS man file using Jim's parser
+            error = loadWepsMgmt();
+            LOG.info("ERROR: " + error);
+            if (error == null) {
+                // Get field geometry
+                getFieldGeometry();
+
+                // get wind barriers
+                getWindBarriers();
+
+                // Get climate info
+                getClimate();
+
+                // Get wind info
+                generateWindData();
+
+                // Get soils data
+                getSoilIfc();
+
+                // run WEPS model
                 try {
-                    db = PostGIS.singleton();
+                    // The WEPS GUI requires an empty notes.txt file per LEW to run
+                    String emptyString = "";
+                    File notes_txt = new File(sessionWorkDir + "/notes.txt");
+                    FileUtils.writeStringToFile(notes_txt, emptyString);
+
+                    // Always generate Weps Run file from JSON parameters (it is never provided in the model srvc signature)
+                    LOG.log(Level.INFO, "wepsrun file does not exist, creating it.");
+                    String wepsrunFile = "weps.run";
+                    WepsRunFileGenerator.GenerateWepsRunFile(wmr, sessionWorkDir, wepsrunFile);
+
+                    // Our WEPS model call uses the following cmd line args
+                    // /weps -W1 -u0 -I2 -t1 -P./ >stdout.txt 2>stderr.txt
+                    LOG.info("starting process");
+                    pc = new ProcessComponent();
+
+                    // linux based WEPS
+                    pc.exe = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/weps", new File(binDir)).toString();
+                    // C15 tells WEPS to perform up to 15 calibration cycles for convergence, could do fewer cycles
+                    // Z50 is required with calibration flag
+                    String[] wepsArgs = (cropCalibrationMode ? new String[]{"-W1", "-u0", "-I2", "-t1", "-T1", "-P./", "-C15", "-Z50"}
+                            : new String[]{"-W1", "-u0", "-I2", "-t1", "-T1", "-P./"});
+                    pc.args = wepsArgs;
+                    pc.working_dir = sessionWorkDir;
+                    pc.execute();
+
+                    // Check standard out for "inpsub" error - occurs when no soil file is available
+                    if (pc.stdout.contains("inpsub error")) {
+                        throw new Exception("ERROR RUNNING WEPS--Standard output:" + pc.stdout);
+                    }
+
+                    FileUtils.write(new File(workDir, "stdout.txt"), pc.stdout);
+                    FileUtils.write(new File(workDir, "stderr.txt"), pc.stderr);
+
+                    // Generate report output
+                    String reportJSON = Binaries.unpackResourceAbsolute("/bin/" + Binaries.getArch() + "/" + REPORT_JSON_FILENAME, sessionWorkDir + "/" + REPORT_JSON_FILENAME).toString();
                 } catch (Exception e) {
-                    LOG.severe("Error obtaining DB connection in WEPS run!");
-                    throw new ServiceException("WEPS error: Cannot obtain geospatial db connection");
+                    throw new ServiceException("WEPS error: error running WEPS model binary:", e);
                 }
+                return pc.exitValue == 0 ? EXEC_OK : EXEC_FAILED;
+            } else {
+                return error;
+            }
+        } catch (Exception e) {
+            LOG.log(Level.SEVERE, "ERROR EXECUTING WEPS", e);
+            throw new ServiceException("WEPS error: unknown error executing WEPS model>", e);
+        }
+    }
 
-                LOG.info("The default CISP WEPS user dir is=" + System.getProperty("user.dir"));
-
-                try {
-                    File workDir = getWorkspaceDir();
-                    sessionWorkDir = workDir.toString();
-                    binDir = Config.getString("m.bin.dir", "/tmp/csip/bin");
-
-                    // check that required parameters exist. populate them in wmr data object
-                    loadRequiredParameters();
-
-                    // get the mgmt as a json obj and create a WEPS man file using Jim's parser
-                    error = loadWepsMgmt();
-                    LOG.info("ERROR: "+ error);
-                    if(error == null){
-                        // Get field geometry
-                        getFieldGeometry();
-
-                        // get wind barriers
-                        getWindBarriers();
-
-                        // Get climate info
-                        getClimate();
-
-                        // Get wind info
-                        generateWindData();
-
-                        // Get soils data
-                        getSoilIfc();
-
-                        // run WEPS model
-                        try {
-                            // The WEPS GUI requires an empty notes.txt file per LEW to run
-                            String emptyString="";
-                            File notes_txt = new File(sessionWorkDir + "/notes.txt");
-                            FileUtils.writeStringToFile(notes_txt, emptyString);
-
-                            // Always generate Weps Run file from JSON parameters (it is never provided in the model srvc signature)
-                            LOG.log(Level.INFO, "wepsrun file does not exist, creating it.");
-                            String wepsrunFile = "weps.run";
-                            WepsRunFileGenerator.GenerateWepsRunFile(wmr, sessionWorkDir, wepsrunFile);
-
-                            // Our WEPS model call uses the following cmd line args
-                            // /weps -W1 -u0 -I2 -t1 -P./ >stdout.txt 2>stderr.txt
-                            LOG.info("starting process");
-                            pc = new ProcessComponent();
-
-                            // linux based WEPS
-                            pc.exe = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/weps", new File(binDir)).toString();
-                            // C15 tells WEPS to perform up to 15 calibration cycles for convergence, could do fewer cycles
-                            // Z50 is required with calibration flag
-                            String[] wepsArgs = (cropCalibrationMode ? new String[]{"-W1", "-u0", "-I2", "-t1", "-T1", "-P./", "-C15", "-Z50"} :
-                                                                      new String[]{"-W1", "-u0", "-I2", "-t1", "-T1", "-P./"});
-                            pc.args = wepsArgs;
-                            pc.working_dir = sessionWorkDir;
-                            pc.execute();
-
-                            // windows 32-bit WEPS - WARNING Runs much slower
-    //                        pc.exe = Binaries.unpackResource("/bin/win-x86/weps.exe", new File(binDir)).toString();
-    //                        File wepssh = new File(sessionWorkDir + "/runweps.sh");
-    //                        String invokeWeps = "wine " + pc.exe + " -W1 -u0 -I2 -t1 -T1 -P./";
-    //                        FileUtils.writeStringToFile(wepssh, invokeWeps);
-    //                        wepssh.setExecutable(true);
-    //
-    //                        pc.working_dir = sessionWorkDir;
-    //                        pc.exe = "./runweps.sh";
-    //                        pc.args = new String[]{};  
-    //                        pc.execute();
-
-                            // Check standard out for "inpsub" error - occurs when no soil file is available
-                            if (pc.stdout.contains("inpsub error"))
-                                throw new Exception("ERROR RUNNING WEPS--Standard output:" + pc.stdout);
-
-                            FileUtils.write(new File(workDir, "stdout.txt"), pc.stdout);
-                            FileUtils.write(new File(workDir, "stderr.txt"), pc.stderr);
-
-                            // Generate report output
-                            String reportJSON = Binaries.unpackResourceAbsolute("/bin/" + Binaries.getArch() + "/" + REPORT_JSON_FILENAME, sessionWorkDir + "/" + REPORT_JSON_FILENAME).toString();
-                        } catch (Exception e) {
-                            throw new ServiceException("WEPS error: error running WEPS model binary:" + e.toString());
-                        }
-
-                        return pc.exitValue == 0 ? EXEC_OK : EXEC_FAILED;
-                    }else{
-                        return error;
-                    }
-                } catch (Exception e) {
-                    LOG.log(Level.SEVERE, "ERROR EXECUTING WEPS!!!");
-//                    LOG.log(Level.SEVERE, e.getStackTrace().toString());
-                    for (StackTraceElement ste : e.getStackTrace()) {
-                        LOG.log(Level.SEVERE, "class=" + ste.getClassName() + " method=" + ste.getMethodName() + " |" + ste.toString());
-                    }
-                    throw new ServiceException("WEPS error: unknown error executing WEPS model>" + e.toString());
-                    
-                }
-            }
-        };
-    }
 
     /*
      * Checks for the existence of required WEPS parameters.
@@ -259,16 +234,18 @@
             LOG.info("SET_LENGTH");
             if (JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_FIELD_LENGTH)) {
                 double fieldLengthInM = Double.parseDouble(JSONUtils.getValue(getParamMap().get(WEPS_KEY_FIELD_LENGTH))) * CONV_FT_TO_M;
-                if (fieldLengthInM <= 0)
+                if (fieldLengthInM <= 0) {
                     appendMetainfoWarning(ErosionConst.WEPS_FIELD_LENGTH_IS_INVALID);
+                }
                 wmr.setSimYLen(String.valueOf(fieldLengthInM));
             }
             LOG.info("WIDTH");
             if (JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_FIELD_WIDTH)) {
                 double fieldWidthInM = Double.parseDouble(JSONUtils.getValue(getParamMap().get(WEPS_KEY_FIELD_WIDTH))) * CONV_FT_TO_M;
-                if (fieldWidthInM <= 0)
+                if (fieldWidthInM <= 0) {
                     appendMetainfoWarning(ErosionConst.WEPS_FIELD_WIDTH_IS_INVALID);
-                
+                }
+
                 wmr.setSimXLen(String.valueOf(fieldWidthInM));
             }
             LOG.info("EROSION_LOSS");
@@ -287,18 +264,18 @@
                 double rockFragments = Double.parseDouble(JSONUtils.getValue(getParamMap().get(WEPS_KEY_SOIL_ROCK_FRAGMENTS)));
                 wmr.setSoilRockFragments(String.valueOf(rockFragments));
             }
-            
+
             LOG.info("WEPS Crop Calibration Mode");
             if (JSONUtils.checkKeyExistsB(getParamMap(), WEPS_KEY_CROP_CALIBRATION_MODE)) {
                 cropCalibrationMode = Boolean.parseBoolean(JSONUtils.getValue(getParamMap().get(WEPS_KEY_CROP_CALIBRATION_MODE)));
             }
-                    
-            
+
         } catch (Exception e) {
-            throw new ServiceException("WEPS error: error processing model run parameters.");
+            throw new ServiceException("WEPS error: error processing model run parameters.", e);
         }
     }
 
+
     /*
      * Uses's Jim Lyon's LMOD to WEPS mgmt translator to create a WEPS mgmt file
      */
@@ -338,64 +315,39 @@
                 org.json.JSONObject mgmtObj = new org.json.JSONObject(mgmt.toString());
                 translator.setInputJSONObject(mgmtObj);
                 translator.setOutputFilename(getWorkspaceDir().toString() + "/" + WEPS_MGMT);
-                if (translator != null) {
-                    LOG.log(Level.INFO, "input filename =" + translator.getInputFilename());
-                    LOG.log(Level.INFO, "output filename =" + translator.getOutputFilename());
-                    LOG.log(Level.INFO, "rotation years =" + translator.getRotationYears());
-                    LOG.log(Level.INFO, "JSON to translate=" + translator.getInputJSONObject());
-                }
-                try 
-                {
+                LOG.log(Level.INFO, "input filename =" + translator.getInputFilename());
+                LOG.log(Level.INFO, "output filename =" + translator.getOutputFilename());
+                LOG.log(Level.INFO, "rotation years =" + translator.getRotationYears());
+                LOG.log(Level.INFO, "JSON to translate=" + translator.getInputJSONObject());
+                try {
                     error = translator.Translate();
                     LOG.log(Level.INFO, "OUTPUT FROM THE TRANSLATOR ='" + error + "'");
-                    if(error != null)
-                    {
-                        try
-                        {
-                            if (Integer.parseInt(error) != 1)
-                            {
+                    if (error != null) {
+                        try {
+                            if (Integer.parseInt(error) != 1) {
                                 LOG.log(Level.SEVERE, "THERE IS AN ERROR CODE RETURNED FROM THE MAN2WEPS TRANSLATOR. Code=" + error);
                             }
-                        }
-                        catch(NumberFormatException ex)
-                        { // I want to transition the numeric errors to string errors like this
+                        } catch (NumberFormatException ex) { // I want to transition the numeric errors to string errors like this
                             LOG.log(Level.SEVERE, "THERE IS AN ERROR: " + error);
                         }
                     }
-                } 
-                catch (Exception e) 
-                {
-                    LOG.log(Level.SEVERE, "FLAT UP EXPLOSION FROM THE WEPS TRANSLATOR:" + e.toString());
-                    if (translator != null) 
-                    {
-                        //LOG.log(Level.INFO, translator.)
-                    }
-                    else
-                    {
-                        LOG.log(Level.INFO, "TRANSLATOR IS NULL!");
-                    }
-                    for (StackTraceElement ste : e.getStackTrace()) 
-                    {
-                        LOG.log(Level.SEVERE, "class=" + ste.getClassName() + " method=" + ste.getMethodName() + " |" + ste.toString());
-                    }
-                    throw new ServiceException("LMOD management translation error executing WEPS");
+                } catch (Exception e) {
+                    LOG.log(Level.SEVERE, "FLAT UP EXPLOSION FROM THE WEPS TRANSLATOR:", e);
+                    throw new ServiceException("LMOD management translation error executing WEPS", e);
                     //return WEPS_ERROR_LMOD_TRANSLATION_ERROR;
                 }
 //                if (error != null)
 //                {
                 // Set these values no matter what
-                    wmr.setRunCycle(Integer.toString(translator.getRotationYears()));
-                    LOG.log(Level.INFO, "*****************************************************set run cycle=" + wmr.getRunCycle());
-                    simulationYears = Integer.parseInt(wmr.getRunCycle()) * NRCS_CYCLE_COUNT;
-                    wmr.setNumYears(Integer.toString(simulationYears));
+                wmr.setRunCycle(Integer.toString(translator.getRotationYears()));
+                LOG.log(Level.INFO, "*****************************************************set run cycle=" + wmr.getRunCycle());
+                simulationYears = Integer.parseInt(wmr.getRunCycle()) * NRCS_CYCLE_COUNT;
+                wmr.setNumYears(Integer.toString(simulationYears));
 //                }
             }
         } catch (Exception e) {
-            LOG.log(Level.SEVERE, "STACK TRACE FROM LMOD TRANSLATOR ERROR:");
-            for (StackTraceElement ste : e.getStackTrace()) {
-                LOG.log(Level.SEVERE, "class=" + ste.getClassName() + " method=" + ste.getMethodName() + " |" + ste.toString());
-            }
-            throw new ServiceException("WEPS error: error translating WEPS mgmt from LMOD.",e);
+            LOG.log(Level.SEVERE, "LMOD TRANSLATOR ERROR:", e);
+            throw new ServiceException("WEPS error: error translating WEPS mgmt from LMOD.", e);
         }
         LOG.log(Level.INFO, "*****************************************************LEAVING loadWepsMgmt");
         LOG.log(Level.INFO, "*****************************************************set run cycle=" + wmr.getRunCycle());
@@ -403,6 +355,7 @@
         return error;
     }
 
+
     private void getFieldGeometry() throws ServiceException {
 //        try {
 //            if (JSONUtils.checkKeyExistsB(getParamMap(), WEPS_FIELD_BOUNDARY)) {
@@ -425,6 +378,7 @@
 //        }
     }
 
+
     private void getWindBarriers() throws ServiceException {
         try {
             String barrierdir = "";
@@ -523,51 +477,40 @@
                         Barrier b = new Barrier();
                         lstBarriers.add(b);
                     }
-                    wmr.setBarriers(lstBarriers); 
+                    wmr.setBarriers(lstBarriers);
                 }
             }
         } catch (Exception e) {
             // Handle error in processing barriers
-            LOG.severe("Error with wind barriers: " + e.toString());
-            String stackTrace = "";
-            for (StackTraceElement ste : e.getStackTrace()) {
-                stackTrace += ste.toString();
-            }
-            LOG.severe("stack trace=" + stackTrace);
-            throw new ServiceException("WEPS error: error processing wind barriers information: " + e.toString());
+            LOG.log(Level.SEVERE, "Error with wind barriers: ", e);
+            throw new ServiceException("WEPS error: error processing wind barriers information: ", e);
         }
     }
 
+
     private void getClimate() throws ServiceException {
         try {
-            if (db != null) 
-            {
+            if (db != null) {
                 double latitude = Double.parseDouble(wmr.getLat());
                 double longitude = Double.parseDouble(wmr.getLongitude());
                 PostGIS.StationResult cligenStation = null;
-                
+
                 // check if the field lat/long intersects any cli station geometries first- and use it if so
                 PostGIS.StationResult cliStation = db.cliGeomIntersect(latitude, longitude);
-                if (cliStation != null)
-                {
+                if (cliStation != null) {
                     LOG.info("The cliStation name is '" + cliStation.name + "'");
-                    if (cliStation.name.contentEquals("Out"))
-                    {
+                    if (cliStation.name.contentEquals("Out")) {
                         // in the mountain west polygon - use the nearest cligen station
                         cligenStation = db.findCligenStation(latitude, longitude);
                         LOG.info("***************************************************************set cligen station 1=" + cligenStation.name);
-                        
-                    }
-                    else
-                    {
+
+                    } else {
                         // use the cli station found by intersecting the climate station geometries
                         cligenStation = cliStation;
                         LOG.info("***************************************************************set cligen station 2=" + cligenStation.name);
-                        
+
                     }
-                }
-                else
-                {
+                } else {
                     // get climate station for this lat / long
                     LOG.info("FIND NEAREST CLIGEN STATION!");
                     LOG.info("lat=" + wmr.getLat());
@@ -579,11 +522,10 @@
                 }
                 // generate cli file using this station
                 LOG.info("***************************************************************using cligen station=" + cligenStation.name);
-                if  (wmr.getElevation().equals(WepsModelRun.UNSET_ELEVATION))                 
-                {
+                if (wmr.getElevation().equals(WepsModelRun.UNSET_ELEVATION)) {
                     wmr.setElevation(cligenStation.elevation);
                 }
-                
+
                 // populate cli gen station parameters in weps.run file
                 wmr.setCliStationLong(cligenStation.stationX);
                 wmr.setCliStationLat(cligenStation.stationY);
@@ -606,11 +548,12 @@
                 //wmr.cliFile = "cligen.cli";
             }
         } catch (Exception e) {
-            e.printStackTrace();
+            LOG.log(Level.SEVERE, "Error", e);
             throw new ServiceException("WEPS error: error generating climate data:" + e.toString());
         }
     }
 
+
     private void generateWindData() throws ServiceException {
         try {
             boolean bInterpolatedWind = false;
@@ -625,16 +568,12 @@
 
                 // check if the field lat/long intersects any wind station geometries first- and use it if so
                 PostGIS.StationResult windStation = db.windGeomIntersect(latitude, longitude);
-                if (windStation != null)
-                {
+                if (windStation != null) {
                     LOG.info("The intersected windStation name is '" + windStation.name + "'");
                     // Check for Out or INT polygons - these are not wind stations, just filler polygons
-                    if ((windStation.name.contentEquals("Out")) || (windStation.name.contentEquals("INT")))
-                    {
+                    if ((windStation.name.contentEquals("Out")) || (windStation.name.contentEquals("INT"))) {
                         sWindgenStation = null;
-                    }
-                    else
-                    {  
+                    } else {
                         sWindgenStation = windStation.stationId.trim();
                         windStationForWepsRunFile = windStation;
                         windDbPath = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/" + DEFAULT_WIND_STATION_DB, new File(binDir)).toString();
@@ -642,44 +581,38 @@
                 }
 
                 // Do we still need to populate the windgen station???
-                if (sWindgenStation == null)
-                {
+                if (sWindgenStation == null) {
                     // next check if in the interpolation boundary shape, if so, interpolate 3 nearest wind stations
                     // to generate an interpolated station
                     LOG.log(Level.INFO, "Check if lat/long is in interpolation boundary");
                     if (db.IsInInterpolateBoundary(latitude, longitude)) {
                         LOG.log(Level.INFO, "YES! lat/long is in interpolation boundary");
-                        
+
                         // Generate wind station interpolation
                         wmr.setWinFile("interpolate.win");
 
                         // Generate weights file
                         ProcessComponent pcInterpolate = new ProcessComponent();
-                        
-                        // windows
-                        //String exepath = Binaries.unpackResource("/bin/win-x86/interpolate.exe", new File(binDir)).toString();
-                        
+
                         // linux
                         String exepath = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/interpolate", new File(binDir)).toString();
-                        
+
                         String dbpath = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/wind_gen_his_upper_US_NRCS.idx", new File(binDir)).toString();
                         String polygon = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/interpolation_boundary.pol", new File(binDir)).toString();
 
                         // Get the county centroid for wind interpolation
                         wepsCounty = db.countyCentroid(latitude, longitude);
-                        
+
                         // Generate shell script to invoke interpolate
                         File interpolatesh = new File(sessionWorkDir + "/interpolate.sh");
                         NumberFormat nf = DecimalFormat.getInstance();
-                        int windInterpolationDecimalDigits  = Config.getInt("weps.wind_interpolate_precision", 2);
+                        int windInterpolationDecimalDigits = Config.getInt("weps.wind_interpolate_precision", 2);
                         nf.setMaximumFractionDigits(windInterpolationDecimalDigits);
                         nf.setMinimumFractionDigits(windInterpolationDecimalDigits);
                         nf.setRoundingMode(RoundingMode.HALF_UP);
                         double countyCentroidLat = Double.parseDouble(wepsCounty.county_centroid_Y);
                         double countyCentroidLon = Double.parseDouble(wepsCounty.county_centroid_X);
                         LOG.log(Level.INFO, "***county centroid lat=" + countyCentroidLat + " lon=" + countyCentroidLon);
-                        // windows
-                        //String invokeInterpolate = "wine " + exepath + " -f " + dbpath + " -p " + polygon + " -lat " + nf.format(countyCentroidLat) + " -long " + nf.format(countyCentroidLon);
                         // linux
                         String invokeInterpolate = exepath + " -f " + dbpath + " -p " + polygon + " -lat " + nf.format(countyCentroidLat) + " -long " + nf.format(countyCentroidLon);
                         FileUtils.writeStringToFile(interpolatesh, invokeInterpolate);
@@ -687,7 +620,7 @@
 
                         pcInterpolate.working_dir = sessionWorkDir;
                         pcInterpolate.exe = "./interpolate.sh";
-                        pcInterpolate.args = new String[]{};  
+                        pcInterpolate.args = new String[]{};
                         pcInterpolate.execute();
 
                         // Added small delay because occasionally the stdout was incomplete upon parsing
@@ -709,15 +642,13 @@
                             // therefore everything has to be extracted to the workdir and done locally there.
                             // This is BAD (inefficient) because it is extra work to always extract wind station wdb's for every model run!
                             ProcessComponent pcInterpWdb = new ProcessComponent();
-                            
-                            // windows
-                            //exepath = Binaries.unpackResource("/bin/win-x86/interp_wdb.exe", new File(binDir)).toString();
+
                             // linux
                             exepath = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/interp_wdb", new File(binDir)).toString();
-                            
-    //                        String station1Db = BinUtils.unpackResourceAbsolute("/bin/" + BinUtils.getArch() + "/windstations/" + wp.station1 + ".wdb", sessionWorkDir + "/" + wp.station1 + ".wdb").toString();
-    //                        String station2Db = BinUtils.unpackResourceAbsolute("/bin/" + BinUtils.getArch() + "/windstations/" + wp.station2 + ".wdb", sessionWorkDir + "/" + wp.station2 + ".wdb").toString();
-    //                        String station3Db = BinUtils.unpackResourceAbsolute("/bin/" + BinUtils.getArch() + "/windstations/" + wp.station3 + ".wdb", sessionWorkDir + "/" + wp.station3 + ".wdb").toString();
+
+                            //                        String station1Db = BinUtils.unpackResourceAbsolute("/bin/" + BinUtils.getArch() + "/windstations/" + wp.station1 + ".wdb", sessionWorkDir + "/" + wp.station1 + ".wdb").toString();
+                            //                        String station2Db = BinUtils.unpackResourceAbsolute("/bin/" + BinUtils.getArch() + "/windstations/" + wp.station2 + ".wdb", sessionWorkDir + "/" + wp.station2 + ".wdb").toString();
+                            //                        String station3Db = BinUtils.unpackResourceAbsolute("/bin/" + BinUtils.getArch() + "/windstations/" + wp.station3 + ".wdb", sessionWorkDir + "/" + wp.station3 + ".wdb").toString();
                             String station1Db = getWindStationFile(wp.station1);
                             String station2Db = getWindStationFile(wp.station2);
                             String station3Db = getWindStationFile(wp.station3);
@@ -738,7 +669,7 @@
                             windDbPath = "test.wdb";
                             sWindgenStation = "999999";  // this is the magic number indicating its an interpolated wind station!
                         }
-                        
+
                         // for wind interpolation, report the nearest wind gen station in the weps.run file for now
                         // check with Fred to verify if this is correct behavior for the weps gui
                         windStationForWepsRunFile = db.findWindgenStation(Double.parseDouble(wmr.getLat()), Double.parseDouble(wmr.getLongitude()));
@@ -750,8 +681,6 @@
                         windStationForWepsRunFile.stationY = wmr.getLat();
                     }
 
-                    
-                    
                     // otherwise, just use data from nearest wind station:
                     // If this is not using an interpolated wind station, then use the default closest one...
                     if (windDbPath.length() == 0) {
@@ -775,7 +704,7 @@
                         windDbPath = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/" + DEFAULT_WIND_STATION_DB, new File(binDir)).toString();
                     }
                 }
-                
+
                 // populate wind gen station parameters in the weps.run file 
                 wmr.setWinWindLat(windStationForWepsRunFile.stationY);
                 wmr.setWinWindLong(windStationForWepsRunFile.stationX);
@@ -784,37 +713,34 @@
                 wmr.setWinWindState(windStationForWepsRunFile.state);
                 wmr.setWinWindStationName(windStationForWepsRunFile.name);
                 wmr.setWinWindDescriptionString("|" + wmr.getWinWindStation() + "|" + wmr.getWinWindCountry() + "|" + wmr.getWinWindState() + "|" + wmr.getWinWindStationName());
-                
+
                 // make adjustments if wind is interpolated in weps.run
-                if (bInterpolatedWind)
-                {
+                if (bInterpolatedWind) {
                     wmr.setWinWindGenProgram("interpolated");
-                    if (wepsCounty != null)
-                    {
+                    if (wepsCounty != null) {
                         wmr.setWinWindLat(wepsCounty.county_centroid_Y);
                         wmr.setWinWindLong(wepsCounty.county_centroid_X);
                     }
                     LOG.log(Level.INFO, "*******************************************WIND IS INTERPOLATED-SETTING DESC STRING TO EMPTY!");
                     wmr.setWinWindDescriptionString("");
                 }
-                
+
                 // populate state and county code params in the weps.run file
                 PostGIS.County cnty = db.findCounty(latitude, longitude);
                 wmr.setStateSite(cnty.st_abbr);
                 wmr.setCountySite(cnty.county_code);
                 LOG.log(Level.INFO, "*******************************************AS SET IN WMR county site=" + wmr.getCountySite());
                 LOG.log(Level.INFO, "*******************************************AS SET IN WMR state site=" + wmr.getStateSite());
-                        
+
                 // generate win file using this station (or interpolated one)
                 ProcessComponent pcWindGen = new ProcessComponent();
-                //String exepath = Binaries.unpackResource("/bin/" + Binaries.getArch() + "/wind_gen4", new File(binDir)).toString();
                 String winexepath = Binaries.unpackResource("/bin/win-x86/wind_gen4.exe", new File(binDir)).toString();
                 LOG.log(Level.INFO, "Using wind database:" + windDbPath);
 
                 // Generate shell script to invoke windgen
                 File windgensh = new File(sessionWorkDir + "/windgen.sh");
                 //String invokeWinGen = exepath + " -f " + windDbPath + " -b 01 -y " + simulationYears + " -o thewind.win -s " + sWindgenStation;
-                String invokeWinGen = "wine " + winexepath + " -f " + windDbPath + " -b 01 -y " + simulationYears + " -o " + wmr.getWinFile() +" -s " + sWindgenStation;
+                String invokeWinGen = "wine " + winexepath + " -f " + windDbPath + " -b 01 -y " + simulationYears + " -o " + wmr.getWinFile() + " -s " + sWindgenStation;
                 FileUtils.writeStringToFile(windgensh, invokeWinGen);
                 windgensh.setExecutable(true);
 
@@ -827,10 +753,11 @@
                 //wmr.winFile = "thewind.win";
             }
         } catch (Exception e) {
-            throw new ServiceException("WEPS error: error generating wind data");
+            throw new ServiceException("WEPS error: error generating wind data", e);
         }
     }
 
+
     private String getWindStationFile(int windStationId) throws ServiceException {
         String wepsdb = Config.getString("weps.db", "http://oms-db.engr.colostate.edu/weps");
         String windStation = WIND_STATIONS_DIR + "/" + windStationId + WIND_STATION_FILE_EXT;
@@ -846,33 +773,27 @@
         return wmr.getSoilFile();
     }
 
+
     private void getSoilIfc() throws ServiceException {
         String wepsdb = Config.getString("weps.db", "http://oms-db.engr.colostate.edu/weps");
         PostGIS.FileQryResult soil = null;
-        
+
         try {
             // Use user provided soil key to look up and acquire soils file
             LOG.log(Level.INFO, "WEPS soilkey=" + soilkey);
             LOG.log(Level.INFO, "WEPS soilfile=" + soilfile);
-            if ((soilfile == null) || ((soilfile != null) && (soilfile.length() < 1)))
-            {
+            if ((soilfile == null) || ((soilfile != null) && (soilfile.length() < 1))) {
                 LOG.log(Level.INFO, "Not using WEPS soilfile pointer for soil");
-                if (db != null) 
-                {
+                if (db != null) {
                     LOG.log(Level.INFO, "Get WEPS soils using database");
-                    if ((soilkey != null) && (soilkey.length() > 0))
-                    {
+                    if ((soilkey != null) && (soilkey.length() > 0)) {
                         LOG.log(Level.INFO, "USING provided WEPS soil component key=" + soilkey);
                         soil = db.findSoilsWepsByCokey(soilkey, Double.parseDouble(wmr.getLongitude()));
-                    }
-                    else
-                    {
+                    } else {
                         LOG.log(Level.INFO, "Attempting to resolve WEPS soil by lat=" + wmr.getLat() + " and long=" + wmr.getLongitude());
                         soil = db.findSoilsWeps(Double.parseDouble(wmr.getLat()), Double.parseDouble(wmr.getLongitude()));
                     }
-
-                    if (soil == null) 
-                    {
+                    if (soil == null) {
                         LOG.log(Level.WARNING, "No soil for lat=" + wmr.getLat() + "\nfor long=" + wmr.getLongitude() + "\n");
                         soilPtr = "";
                         if ((soilkey != null) && (soilkey.length() > 0)) {
@@ -880,13 +801,11 @@
                         } else {
                             throw new ServiceException("WEPS error: no soil available for provided lat/long coordinates");
                         }
-                    } 
-                    else
+                    } else {
                         soilPtr = soil.file_path + "/" + soil.file_name + SOIL_FILE_EXT;
+                    }
                 }
-            }
-            else
-            {
+            } else {
                 // use provided soil file pointer
                 LOG.log(Level.INFO, "USING provided WEPS soil ptr=" + soilPtr);
                 soilPtr = soilfile + SOIL_FILE_EXT;
@@ -904,12 +823,12 @@
             // Prefer lat/long retrieved soils file 
             wmr.setSoilFile(soil.file_name + SOIL_FILE_EXT);
         } catch (Exception e) {
-            throw new ServiceException("WEPS error: error retrieiving soil data");
+            throw new ServiceException("WEPS error: error retrieiving soil data", e);
         }
     }
 
+
     private void getFile(String url, String destDir, String filename) {
-
         FileOutputStream fos = null;
         try {
 
@@ -933,21 +852,21 @@
         }
     }
 
+
     private String trimBrackets(String sText) {
         return sText.substring(1, sText.length() - 1);
     }
 
+
     @Override
-    protected File[] postprocess() throws Exception {
-        File simDir = getWorkspaceDir();
-        return new File[] {
-            new File(simDir, "stir_energy.out"),
-            new File(simDir, "sci_energy.out"),
-            new File(simDir, "stdout.txt"),
-            new File(simDir, "stderr.txt")
-        };
+    protected void postProcess() throws Exception {
+        putResult(new File(getWorkspaceDir(), "stir_energy.out"));
+        putResult(new File(getWorkspaceDir(), "sci_energy.out"));
+        putResult(new File(getWorkspaceDir(), "stdout.txt"));
+        putResult(new File(getWorkspaceDir(), "stderr.txt"));
     }
 
+
     @Override
     public JSONArray createResults() throws Exception {
         LOG.info("Create the WEPS results...");
@@ -964,9 +883,10 @@
         bfr.close();
         fr.close();
         wo = SciEnergyParser.parseSciEnergyFile(sciEnergyOut);
-        
-        if (wo.bNaN)
+
+        if (wo.bNaN) {
             appendMetainfoWarning(ErosionConst.WEPS_FOUND_NAN_IN_OUTPUT);
+        }
 
         getAdvancedOutput(wo);
 
@@ -989,75 +909,43 @@
         results.put(JSONUtils.data(WEPS_SUSPENSION, wo.suspension));
         results.put(JSONUtils.data(WEPS_PM10, wo.pm10));
 
-//        results.put(JSONUtils.data("sci", baseUrl + "/sci_energy.out"));
-//        results.put(JSONUtils.data("stir", baseUrl + "/strir_energy.out"));
-//        results.put(JSONUtils.data("stdout", baseUrl + "/stdout.txt"));
-//        results.put(JSONUtils.data("stderr", baseUrl + "/stderr.txt"));
         return results;
     }
 
-    private void getAdvancedOutput(WepsOutput wOutput) throws JSONException, Exception{
+
+    private void getAdvancedOutput(WepsOutput wOutput) throws JSONException, Exception {
         JSONArray reportItems = new JSONArray();
         JSONObject item = new JSONObject();
         JSONArray report;
-        Map<String,JSONObject> reportValues;
+        Map<String, JSONObject> reportValues;
         JSONArray suspen;
         JSONArray salt;
         JSONArray pm10;
-        
-        item.put("name","output.suspen");
+
+        item.put("name", "output.suspen");
         reportItems.put(item);
-        
+
         item = new JSONObject();
         item.put("name", "output.crp_salt");
         reportItems.put(item);
-        
+
         item = new JSONObject();
         item.put("name", "output.pm10");
         reportItems.put(item);
-        
+
         report = createReport(reportItems);
-        
+
         reportValues = JSONUtils.preprocess(report);
-        
+
         suspen = JSONUtils.getJSONArrayParam(reportValues, "output.suspen");
         salt = JSONUtils.getJSONArrayParam(reportValues, "output.crp_salt");
         pm10 = JSONUtils.getJSONArrayParam(reportValues, "output.pm10");
-        
-        wo.suspension = suspen.getString(suspen.length()-1);
-        wo.saltation = salt.getString(salt.length() -1);
+
+        wo.suspension = suspen.getString(suspen.length() - 1);
+        wo.saltation = salt.getString(salt.length() - 1);
         wo.pm10 = pm10.getString(pm10.length() - 1);
     }
-            
-//    @Override
-//    public String getModelName() {
-//        return "weps/1.2";
-//    }
-    @Override
-    public long getNextPoll() {
-        return 2000;  // poll every 2 seconds after the first poll
-    }
 
-    @Override
-    protected long getFirstPoll() {
-        // to do
-        // this should be based on the number of years of the weps run
-        return 25000; // wait 25 seconds for the first poll.
-    }
-
-//    @Override
-//    protected JSONObject describe() throws JSONException {
-//
-//        JSONArray p = new JSONArray();
-//
-//        JSONObject metainfo = new JSONObject();
-//////        metainfo.put(KEY_REQUEST_RESULTS, new JSONArray(potResults));
-//
-//        JSONObject model = new JSONObject();
-//        model.put(KEY_PARAMETER, p);
-//        model.put(KEY_METAINFO, metainfo);
-//        return model;
-//    }
 
     @Override
     protected JSONArray createReport() throws Exception {
@@ -1085,8 +973,8 @@
         reportdata.m_sUnits = "US";
 
         // Load the file data.
-        LOG.info("WorkingDir: "+ getWorkspaceDir().toString());
-        
+        LOG.info("WorkingDir: " + getWorkspaceDir().toString());
+
         reportdata.loadFiles(getWorkspaceDir().toString());
 
 //        // Dump the loaded data as text for debugging purposes.
@@ -1134,23 +1022,25 @@
         //LOG.info("Updated Report JSON obj=" + reportObj.toString());
         return reportItems;
     }
-    
+
+
     /**
-     * This is an overloaded method for createReport that allows you to only query a set of item in a report
+     * This is an overloaded method for createReport that allows you to only
+     * query a set of item in a report
      * @param reportItems items you want returned in the report
      * @return The report data
-     * @throws Exception 
+     * @throws Exception
      */
     private JSONArray createReport(JSONArray reportItems) throws Exception {
-        
-        
+
         String workDir = getWorkspaceDir().toString();
         File reportTemplate = new File(workDir + "/" + REPORT_JSON_FILENAME);
         String sReportJSON = FileUtils.readFileToString(reportTemplate);
         //JSONObject reportObj = new JSONObject(sReportJSON);
         //JSONArray reportItems = reportObj.getJSONArray("WEPSreport");
-        if(reportItems == null || reportItems.length() == 0)
+        if (reportItems == null || reportItems.length() == 0) {
             reportItems = new JSONArray(sReportJSON);
+        }
 
         WepsConnection con = new WepsConnection();
 
@@ -1169,14 +1059,14 @@
         reportdata.m_sUnits = "US";
 
         // Load the file data.
-        LOG.info("WorkingDir: "+ getWorkspaceDir().toString());
+        LOG.info("WorkingDir: " + getWorkspaceDir().toString());
 
         reportdata.loadFiles(getWorkspaceDir().toString());
 
-    //        // Dump the loaded data as text for debugging purposes.
-    //        LOG.info("hash map output=" + con.toString());
-    //        
-    //        LOG.info("Original Report JSON obj=" + reportObj.toString());
+        //        // Dump the loaded data as text for debugging purposes.
+        //        LOG.info("hash map output=" + con.toString());
+        //        
+        //        LOG.info("Original Report JSON obj=" + reportObj.toString());
         HashMap<String, ArrayList<Object>> m_reportdata = con.getParamValues();
         for (int i = 0; i < reportItems.length(); i++) {
             JSONObject obj = (JSONObject) reportItems.get(i);

src/java/m/weps/WeightsParser.java

@@ -3,6 +3,7 @@
  * and open the template in the editor.
  */
 package m.weps;
+
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import oms3.annotations.*;
@@ -14,11 +15,14 @@
 public class WeightsParser {
 
     static final Logger log = Logger.getLogger(WeightsParser.class.getName());
-    
-    @In public String weightsFile;
-    @In public String weightsErr;
-    @In public int exitValue;
-    
+
+    @In
+    public String weightsFile;
+    @In
+    public String weightsErr;
+    @In
+    public int exitValue;
+
     public int station1 = 0;
     public double weight1 = 0.0;
     public int station2 = 0;
@@ -26,58 +30,64 @@
     public int station3 = 0;
     public double weight3 = 0.0;
 
+
     @Execute
     public void parse() {
         if (log.isLoggable(Level.INFO)) {
             log.info("weights file: " + weightsFile);
             log.info("weights err: " + weightsErr);
         }
-        if (exitValue == 0) 
-        {
-        
+        if (exitValue == 0) {
+
             // Find where point is described
             String sPattern = "point:";
             int start = weightsFile.lastIndexOf(sPattern);
             int end = weightsFile.indexOf('\n', start) + 1;
             // skip this line
             weightsFile = weightsFile.substring(end);
-            if (log.isLoggable(Level.INFO))  log.info("new filesubset=" +weightsFile);
+            if (log.isLoggable(Level.INFO)) {
+                log.info("new filesubset=" + weightsFile);
+            }
             end = weightsFile.indexOf('\n') + 1;
             // skip next line
             weightsFile = weightsFile.substring(end);
             end = weightsFile.indexOf('\n') + 1;
             // skip all comment lines
             String line = "#";
-            do 
-            {
+            do {
                 weightsFile = weightsFile.substring(end);
                 end = weightsFile.indexOf('\n') + 1;
-                line = weightsFile.substring(0,end).trim();
+                line = weightsFile.substring(0, end).trim();
             } while (line.charAt(0) == '#');
             // waste an extra line
             weightsFile = weightsFile.substring(end);
             end = weightsFile.indexOf('\n') + 1;
-            line = weightsFile.substring(0,end).trim();
-            if (log.isLoggable(Level.INFO)) log.info("line=" + line);
-            station1 = Integer.parseInt(line.substring(0,line.indexOf(' ')));
+            line = weightsFile.substring(0, end).trim();
+            if (log.isLoggable(Level.INFO)) {
+                log.info("line=" + line);
+            }
+            station1 = Integer.parseInt(line.substring(0, line.indexOf(' ')));
             weight1 = Double.parseDouble(line.substring(line.indexOf(' ')));
             // next line
             weightsFile = weightsFile.substring(end);
             end = weightsFile.indexOf('\n') + 1;
-            line = weightsFile.substring(0,end).trim();
-            if (log.isLoggable(Level.INFO)) log.info("line=" + line);
-            station2 = Integer.parseInt(line.substring(0,line.indexOf(' ')));
+            line = weightsFile.substring(0, end).trim();
+            if (log.isLoggable(Level.INFO)) {
+                log.info("line=" + line);
+            }
+            station2 = Integer.parseInt(line.substring(0, line.indexOf(' ')));
             weight2 = Double.parseDouble(line.substring(line.indexOf(' ')));
             // last line
             weightsFile = weightsFile.substring(end);
             end = weightsFile.indexOf('\n') + 1;
-            line = weightsFile.substring(0,end).trim();
-            if (log.isLoggable(Level.INFO)) log.info("line=" + line);
-            station3 = Integer.parseInt(line.substring(0,line.indexOf(' ')));
+            line = weightsFile.substring(0, end).trim();
+            if (log.isLoggable(Level.INFO)) {
+                log.info("line=" + line);
+            }
+            station3 = Integer.parseInt(line.substring(0, line.indexOf(' ')));
             weight3 = Double.parseDouble(line.substring(line.indexOf(' ')));
 
-            if (log.isLoggable(Level.INFO)) 
-            {   
+            if (log.isLoggable(Level.INFO)) {
                 log.info("station1=" + station1 + " weight1=" + weight1);
                 log.info("station2=" + station2 + " weight2=" + weight2);
                 log.info("station3=" + station3 + " weight3=" + weight3);
@@ -85,5 +95,3 @@
         }
     }
 }
-
-    

src/java/m/weps/WepsModelRun.java

@@ -13,8 +13,8 @@
  *
  * @author wlloyd
  */
-public class WepsModelRun 
-{
+public class WepsModelRun {
+
     // Fixed Values - these values are fixed in the weps.run, and typically do not change
     private final String runMode = "NRCS";
     private final String rotationCycle = "50";
@@ -28,7 +28,7 @@
     private final String radius = "1.00";
     static final NumberFormat latlongFormat = new DecimalFormat("+0.00000;-0.00000");
     static final String UNSET_ELEVATION = "-9999.999";
-    
+
     // Dynamic Values - changable by the service
     private String stateSite = "XX";
     private String countySite = "000";
@@ -57,124 +57,380 @@
     private String simRegionAngle = "0.00000";
     private String simXLen = "0.00";            // meters
     private String simYLen = "0.00";            // meters
-    private String numBarriers = "0";  
+    private String numBarriers = "0";
     private List<Barrier> barriers = new LinkedList<Barrier>();
     private String waterErosionLoss = "0.0000";
-    private String soilRockFragments = "-1";  
-    
-    public WepsModelRun()
-    {
+    private String soilRockFragments = "-1";
+
+
+    public WepsModelRun() {
         barriers.add(new Barrier());
     }
 
-    public void setStateSite(String stateSite) { this.stateSite = stateSite; } 
-    public void setCountySite(String countySite) { this.countySite = countySite; }
-    public void setCliFile(String clifile) { this.cliFile = clifile; }
-    public void setCliStationLat(String cliStationLat) { this.cliStationLat = cliStationLat; }
-    public void setCliStationLong(String cliStationLong) { this.cliStationLong = cliStationLong; }
-    public void setCliStationStateFips(String cliStationStateFips) { this.cliStationStateFips = cliStationStateFips; }
-    public void setCliStationC1(String cliStationC1) { this.cliStationc1 = cliStationC1; }
-    public void setCliStationName(String cliStationName) { this.cliStationName = cliStationName; }
-    public void setCliStationEleM(String cliStationEleM) { this.cliStationEleM = cliStationEleM; }
-    public void setWinFile(String windfile) { this.winFile = windfile; }
-    public void setWinWindGenProgram(String winWindGenProgram) { this.winWindGenProgram = winWindGenProgram; }
-    public void setWinWindLat(String winWindLat) { this.winWindLat = winWindLat; }
-    public void setWinWindLong(String winWindLong) { this.winWindLong = winWindLong; }
-    public void setWinWindStation(String winWindStation) { this.winWindStation = winWindStation; }
-    public void setWinWindCountry(String winWindCountry) { this.winWindCountry = winWindCountry; }
-    public void setWinWindState(String winWindState) { this.winWindState = winWindState; }
-    public void setWinWindStationName(String winWindStationName) { this.winWindStationName = winWindStationName; }
-    public void setWinWindDescriptionString(String winWindDescriptionString) { this.winWindDescriptionString = winWindDescriptionString; }
-    public void setRunCycle(String runcycle) { this.runCycle = runcycle; }
-    public void setLat(String latitude) { this.lat = latitude; }
-    public void setLongitude(String longitude)  { this.longitude = longitude; }
-    public void setElevation(String ele) { this.elevation = ele; }
-    public void setNumYears(String numYears) { this.numYears = numYears; }
-    public void setSoilFile(String soilFile) { this.soilFile = soilFile; }
-    public void setSimRegionAngle(String simRegionAngle) { this.simRegionAngle = simRegionAngle; }
-    public void setSimXLen(String X) { this.simXLen = X; }
-    public void setSimYLen(String Y) { this.simYLen = Y; }
-    public void setNumBarriers(String numbarriers) { this.numBarriers = numbarriers; }
-    public void setBarriers(List<Barrier> barriers) { this.barriers = barriers; }
-    public void setWaterErosionLoss(String waterErosionLoss) { this.waterErosionLoss = waterErosionLoss; }
-    public void setSoilRockFragments(String soilRockFragments ) { this.soilRockFragments = soilRockFragments; }
 
-    
-    public String getRunMode() { return runMode; }
-    public String getRunCycle() { return runCycle; }
-    public String getRotationCycle() { return rotationCycle; }
-    public String getStateSite() { return this.stateSite; }
-    public String getCountySite() { return this.countySite; }
+    public void setStateSite(String stateSite) {
+        this.stateSite = stateSite;
+    }
+
+
+    public void setCountySite(String countySite) {
+        this.countySite = countySite;
+    }
+
+
+    public void setCliFile(String clifile) {
+        this.cliFile = clifile;
+    }
+
+
+    public void setCliStationLat(String cliStationLat) {
+        this.cliStationLat = cliStationLat;
+    }
+
+
+    public void setCliStationLong(String cliStationLong) {
+        this.cliStationLong = cliStationLong;
+    }
+
+
+    public void setCliStationStateFips(String cliStationStateFips) {
+        this.cliStationStateFips = cliStationStateFips;
+    }
+
+
+    public void setCliStationC1(String cliStationC1) {
+        this.cliStationc1 = cliStationC1;
+    }
+
+
+    public void setCliStationName(String cliStationName) {
+        this.cliStationName = cliStationName;
+    }
+
+
+    public void setCliStationEleM(String cliStationEleM) {
+        this.cliStationEleM = cliStationEleM;
+    }
+
+
+    public void setWinFile(String windfile) {
+        this.winFile = windfile;
+    }
+
+
+    public void setWinWindGenProgram(String winWindGenProgram) {
+        this.winWindGenProgram = winWindGenProgram;
+    }
+
+
+    public void setWinWindLat(String winWindLat) {
+        this.winWindLat = winWindLat;
+    }
+
+
+    public void setWinWindLong(String winWindLong) {
+        this.winWindLong = winWindLong;
+    }
+
+
+    public void setWinWindStation(String winWindStation) {
+        this.winWindStation = winWindStation;
+    }
+
+
+    public void setWinWindCountry(String winWindCountry) {
+        this.winWindCountry = winWindCountry;
+    }
+
+
+    public void setWinWindState(String winWindState) {
+        this.winWindState = winWindState;
+    }
+
+
+    public void setWinWindStationName(String winWindStationName) {
+        this.winWindStationName = winWindStationName;
+    }
+
+
+    public void setWinWindDescriptionString(String winWindDescriptionString) {
+        this.winWindDescriptionString = winWindDescriptionString;
+    }
+
+
+    public void setRunCycle(String runcycle) {
+        this.runCycle = runcycle;
+    }
+
+
+    public void setLat(String latitude) {
+        this.lat = latitude;
+    }
+
+
+    public void setLongitude(String longitude) {
+        this.longitude = longitude;
+    }
+
+
+    public void setElevation(String ele) {
+        this.elevation = ele;
+    }
+
+
+    public void setNumYears(String numYears) {
+        this.numYears = numYears;
+    }
+
+
+    public void setSoilFile(String soilFile) {
+        this.soilFile = soilFile;
+    }
+
+
+    public void setSimRegionAngle(String simRegionAngle) {
+        this.simRegionAngle = simRegionAngle;
+    }
+
+
+    public void setSimXLen(String X) {
+        this.simXLen = X;
+    }
+
+
+    public void setSimYLen(String Y) {
+        this.simYLen = Y;
+    }
+
+
+    public void setNumBarriers(String numbarriers) {
+        this.numBarriers = numbarriers;
+    }
+
+
+    public void setBarriers(List<Barrier> barriers) {
+        this.barriers = barriers;
+    }
+
+
+    public void setWaterErosionLoss(String waterErosionLoss) {
+        this.waterErosionLoss = waterErosionLoss;
+    }
+
+
+    public void setSoilRockFragments(String soilRockFragments) {
+        this.soilRockFragments = soilRockFragments;
+    }
+
+
+    public String getRunMode() {
+        return runMode;
+    }
+
+
+    public String getRunCycle() {
+        return runCycle;
+    }
+
+
+    public String getRotationCycle() {
+        return rotationCycle;
+    }
+
+
+    public String getStateSite() {
+        return this.stateSite;
+    }
+
+
+    public String getCountySite() {
+        return this.countySite;
+    }
+
+
     public String getLat() {
         return latlongFormat.format(Double.parseDouble(lat));
     }
-    public String getLongitude() { 
+
+
+    public String getLongitude() {
         return latlongFormat.format(Double.parseDouble(longitude));
     }
-    public String getElevation() { 
+
+
+    public String getElevation() {
         NumberFormat elevationFormat = new DecimalFormat("0.000");
         return elevationFormat.format(Double.parseDouble(elevation));
     }
-    public String getNumYears () { return numYears; }
-    public String getTimeSteps () { return timeSteps; }
-    public String getCliFile() { return cliFile; }
-    
+
+
+    public String getNumYears() {
+        return numYears;
+    }
+
+
+    public String getTimeSteps() {
+        return timeSteps;
+    }
+
+
+    public String getCliFile() {
+        return cliFile;
+    }
+
+
     public String getCliStationLat() {
         return latlongFormat.format(Double.parseDouble(this.cliStationLat));
     }
+
+
     public String getCliStationLong() {
-        return latlongFormat.format(Double.parseDouble(this.cliStationLong)); 
+        return latlongFormat.format(Double.parseDouble(this.cliStationLong));
     }
-    public String getCliStationStateFips() { return this.cliStationStateFips; }
-    public String getCliStationC1() { return this.cliStationc1; }
-    public String getCliStationName() { return this.cliStationName; }
-    public String getCliStationEleM() { 
+
+
+    public String getCliStationStateFips() {
+        return this.cliStationStateFips;
+    }
+
+
+    public String getCliStationC1() {
+        return this.cliStationc1;
+    }
+
+
+    public String getCliStationName() {
+        return this.cliStationName;
+    }
+
+
+    public String getCliStationEleM() {
         NumberFormat elevationFormat = new DecimalFormat("0.0");
-        return elevationFormat.format(Double.parseDouble(this.cliStationEleM)); 
+        return elevationFormat.format(Double.parseDouble(this.cliStationEleM));
     }
-    
-    public String getWinFile() { return winFile; }
-    public String getWinWindGenProgram() { return this.winWindGenProgram; }
-    public String getWinWindLat() { 
+
+
+    public String getWinFile() {
+        return winFile;
+    }
+
+
+    public String getWinWindGenProgram() {
+        return this.winWindGenProgram;
+    }
+
+
+    public String getWinWindLat() {
         return latlongFormat.format(Double.parseDouble(this.winWindLat));
     }
-    public String getWinWindLong() { 
-        return latlongFormat.format(Double.parseDouble(this.winWindLong)); 
+
+
+    public String getWinWindLong() {
+        return latlongFormat.format(Double.parseDouble(this.winWindLong));
     }
-    public String getWinWindStation() { return this.winWindStation; }
-    public String getWinWindCountry() { return this.winWindCountry; }
-    public String getWinWindState() { return this.winWindState; }
-    public String getWinWindStationName() { return this.winWindStationName; }
-    public String getWinWindDescriptionString() { return this.winWindDescriptionString; }    
-    
-    public String getSoilFile() { return soilFile; }
-    public String getSimRegionAngle() { 
+
+
+    public String getWinWindStation() {
+        return this.winWindStation;
+    }
+
+
+    public String getWinWindCountry() {
+        return this.winWindCountry;
+    }
+
+
+    public String getWinWindState() {
+        return this.winWindState;
+    }
+
+
+    public String getWinWindStationName() {
+        return this.winWindStationName;
+    }
+
+
+    public String getWinWindDescriptionString() {
+        return this.winWindDescriptionString;
+    }
+
+
+    public String getSoilFile() {
+        return soilFile;
+    }
+
+
+    public String getSimRegionAngle() {
         NumberFormat simRegionAngleFormat = new DecimalFormat("0.00000");
         return simRegionAngleFormat.format(Double.parseDouble(simRegionAngle));
     }
-    public String getSimCoord1() { return simCoord1; }
-    public String getSimCoord2() { return simCoord2; }
-    public String getSimXLen() { 
+
+
+    public String getSimCoord1() {
+        return simCoord1;
+    }
+
+
+    public String getSimCoord2() {
+        return simCoord2;
+    }
+
+
+    public String getSimXLen() {
         NumberFormat simXLenFormat = new DecimalFormat("0.0");
         return simXLenFormat.format(Double.parseDouble(simXLen));
     }
-    public String getSimYLen() { 
+
+
+    public String getSimYLen() {
         NumberFormat simYLenFormat = new DecimalFormat("0.0");
         return simYLenFormat.format(Double.parseDouble(simYLen));
     }
-    public String getSimScale1() { return simScale1; }
-    public String getSimScale2() { return simScale2; }
-    public String getAvgSlope() { return avgSlope; }
-    public String getNumBarriers() { return numBarriers; }
-    public List<Barrier> getBarriers() { return barriers; }
-    public String getShape() { return shape; }
-    public String getRadius() { return radius; }
-    public String getWaterErosionLoss() { 
+
+
+    public String getSimScale1() {
+        return simScale1;
+    }
+
+
+    public String getSimScale2() {
+        return simScale2;
+    }
+
+
+    public String getAvgSlope() {
+        return avgSlope;
+    }
+
+
+    public String getNumBarriers() {
+        return numBarriers;
+    }
+
+
+    public List<Barrier> getBarriers() {
+        return barriers;
+    }
+
+
+    public String getShape() {
+        return shape;
+    }
+
+
+    public String getRadius() {
+        return radius;
+    }
+
+
+    public String getWaterErosionLoss() {
         NumberFormat waterErosionLossFormat = new DecimalFormat("0.0000");
         return waterErosionLossFormat.format(Double.parseDouble(waterErosionLoss));
     }
-    public String getSoilRockFragments() { return soilRockFragments; }
-    
-    
-    
+
+
+    public String getSoilRockFragments() {
+        return soilRockFragments;
+    }
+
 }

src/java/util/ErosionConst.java

@@ -28,10 +28,16 @@
     public static final String KEY_SOILS = "soilPtr";
     public static final String KEY_MANAGEMENTS = "mgmtPtr";
     public static final String KEY_CLIMATES = "climatePtr";
+    public static final String KEY_DIVERSIONS = "diversionPtr";
+    public static final String KEY_CONTOURSYSTEMS = "contourPtr";
+    public static final String KEY_STRIP_BARRIER_SYSTEMS = "strip_barrierPtr";
     public static final String KEY_TOPO_LENGTH = "topo_length";
     public static final String KEY_TOPO_STEEPNESS = "topo_steepness";
     public static final String KEY_SOIL_INDEX = "soil_index";
     public static final String KEY_MAN_INDEX = "man_index";
+    public static final String KEY_DIVERSION_INDEX = "diversion_index";
+    public static final String KEY_CONTOUR_INDEX = "contour_index"; 
+    public static final String KEY_STRIP_BARRIER_INDEX = "strip_barrier_index";
     // new R2 (Phacil)
     public static final String KEY_MGMTS = "managements";
     public static final String KEY_MGMT = "management";