Ejemplo n.º 1
0
 private void setJsonTree(List<String> path, JSONArray parent, GadgetSpec gadgetSpec)
     throws JSONException {
   String tempId = "root"; // Temp variable to keep track of parent ID.
   for (int i = 0; i < path.size(); i++) {
     JSONObject newNode = new JSONObject();
     if (!this.isNodeExisting(path.get(i), parent)) {
       // If node is a GadgetSpec (last in path)
       if (i == path.size() - 1) {
         newNode.put("name", StringUtils.capitalize(gadgetSpec.getTitle()));
         newNode.put("hasChildren", false);
         newNode.put("isDefault", gadgetSpec.isDefault());
         newNode.put("id", gadgetSpec.getId());
       }
       // Id node is a unique folder
       else {
         newNode.put("name", StringUtils.capitalize(path.get(i)));
         newNode.put("hasChildren", true);
         newNode.put("isDefault", false);
         newNode.put("id", getFolderId(path.get(i)));
       }
       newNode.put("parent", tempId);
       parent.put(newNode);
     }
     tempId = getFolderId(path.get(i));
   }
 }
 private void initializeJSON() throws JSONException {
   rulesArray = new JSONArray();
   jsonGroupObject.put("rules", rulesArray);
   JSONObject modelInfo = new JSONObject();
   modelArray = new JSONArray();
   modelInfo.put("modelgroups", modelArray);
   jsonGroupObject.put("groups", modelInfo);
 }
Ejemplo n.º 3
0
 private boolean isNodeExisting(String node, JSONArray array) throws JSONException {
   for (int i = 0; i < array.length(); i++) {
     JSONObject temp = array.getJSONObject(i);
     String tempName = temp.getString("name");
     if (tempName.equalsIgnoreCase(node)) {
       return true;
     }
   }
   return false;
 }
 @Override
 public void settingFromJSON(JSONObject json) {
   int k;
   try {
     k = json.getInt(K_BEACONS_KEY);
     doNormalize = json.getBoolean(DO_NORMALIZE_KEY);
     kBeacons = k;
     System.out.println(this.toString());
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
 static JSONArray parseFeatures(JSONObject json) {
   try {
     String type = json.getString("type");
     if (type.equals("FeatureCollection")) {
       JSONArray features = json.getJSONArray("features");
       return features;
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return null;
 }
 Map<Integer, String> parseIndexes(JSONObject header, String indexesName) throws JSONException {
   Map<Integer, String> map = new HashMap<Integer, String>();
   if (header.has(indexesName)) {
     JSONObject json = header.getJSONObject(indexesName);
     @SuppressWarnings("unchecked")
     Iterator<String> it = json.keys();
     while (it.hasNext()) {
       String name = it.next();
       map.put(json.getInt(name), name);
     }
   }
   return map;
 }
Ejemplo n.º 7
0
 private static String getImageURL(JSONObject activity) {
   String result = null;
   try {
     Object image_url = activity.get("image_large_url");
     if (image_url instanceof String
         && !image_url.toString().endsWith("/no_image.gif")
         && activity.containsKey("member")) {
       result = (String) image_url;
       if (!result.matches("^https?://.*")) {
         result = Config.PORTAL_ROOT + result;
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return result;
 }
Ejemplo n.º 8
0
 /**
  * This treats the supplied string as a JSON object and looks for the message attribute inside it.
  * If it is not valid JSON or does not contain a message the original string is returned.
  *
  * @param errorObject
  * @return
  */
 private String parseErrorObject(String errorObject) {
   if (errorObject == null) {
     return null;
   }
   try {
     // Just use JSONObject parse directly instead of Wibblifier as we only want one attribute
     JSONObject json = new JSONObject(errorObject);
     Object errorMessage = json.get("message");
     if (errorMessage != null
         && errorMessage instanceof String
         && !((String) errorMessage).isEmpty()) {
       return (String) errorMessage;
     } else {
       return errorObject;
     }
   } catch (JSONException e) {
     return errorObject;
   }
 }
  JSONObject jsonFormatter(String content, Boolean isCategorie) throws JSONException {

    JSONObject mData = new JSONObject(content);

    JSONObject header = new JSONObject(mData.opt("header"));
    Map<Integer, String> propertyIndexes, elementIndexes;
    Map<String, Object> itemsObject;
    List<Map<String, Object>> items = new ArrayList<>();

    elementIndexes = parseIndexes(header, "elementIndex");
    propertyIndexes = parseIndexes(header, "propertyIndex");

    JSONArray values = mData.optJSONArray("values");

    for (int i = 0; i < values.length(); i++) {
      JSONArray value = values.getJSONArray(i);

      itemsObject = new HashMap<String, Object>();

      Map<String, Object> propertiesObject = new HashMap<String, Object>();

      for (int j = 0; j < value.length(); j++) {

        if (propertyIndexes.containsKey(j)) {
          itemsObject.put(propertyIndexes.get(j), value.optString(j));

        } else if (elementIndexes.containsKey(j)) {

          propertiesObject.put(elementIndexes.get(j), value.optString(j));
        } else {
          break;
        }

        if (!elementIndexes.isEmpty()) {
          itemsObject.put("properties", propertiesObject);
        }
      }

      items.add(itemsObject);
    }

    String listofProperties = mData.optString("listProperties");
    JSONObject tmp;
    if (listofProperties == null || listofProperties.isEmpty()) {
      tmp = new JSONObject();
    } else {
      tmp = new JSONObject(listofProperties);
    }
    if (isCategorie) {
      tmp.putOnce("items", new JSONArray(items));
    } else {

      tmp.putOnce("item", new JSONArray(items));
    }

    return tmp;
  }
Ejemplo n.º 10
0
  public void testcreateblog2() {
    System.out.println("Test Case to Create a Blog");
    Resource resource1 = client.resource(url);
    System.out.println("URL: " + url);
    JSONObject sendobject = new JSONObject();
    try {
      sendobject.put("subject", "sjsu_cmpe202");
      sendobject.put("description", "XML");
      sendobject.put("userid", "Shaunak");
      sendobject.put("timestamp", "11:53");

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    String jsonStringObj = sendobject.toString();
    System.out.println("Create : " + jsonStringObj);
    ClientResponse created =
        resource1
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .post(jsonStringObj);
    System.out.println(created.getStatusCode());
    System.out.println(created.getEntity(String.class));
  }
Ejemplo n.º 11
0
  protected Object parseMap(
      JSONObject jsonObj,
      Class<?> mapClazz,
      Type genericType,
      ValidationException validationException)
      throws IntrospectionException, IllegalAccessException, InstantiationException, JSONException,
          IllegalArgumentException, InvocationTargetException, ParseException {
    if (mapClazz == null) {
      throw new AJAXParserException("No specific class type.");
    }
    if (jsonObj == null) {
      return null;
    }
    if (genericType == null) {
      throw new AJAXParserException("No specific generic type for map " + mapClazz);
    }

    Map<Object, Object> mapInstance;

    if (java.util.HashMap.class.equals(mapClazz)) {
      mapInstance = new java.util.HashMap<Object, Object>(jsonObj.size());
    } else if (java.util.LinkedHashMap.class.equals(mapClazz)) {
      mapInstance = new java.util.LinkedHashMap<Object, Object>(jsonObj.size());
    } else if (java.util.TreeMap.class.equals(mapClazz)) {
      mapInstance = new java.util.TreeMap<Object, Object>();
    } else if (java.util.Hashtable.class.equals(mapClazz)) {
      mapInstance = new java.util.Hashtable<Object, Object>(jsonObj.size());
    } else {

      mapInstance = new java.util.LinkedHashMap<Object, Object>(jsonObj.size());
    }

    Type[] actualTypes = getActualTypes(genericType);

    Class<?> keyClazz =
        actualTypes[0] instanceof Class
            ? (Class<?>) actualTypes[0]
            : (Class<?>) ((ParameterizedType) actualTypes[0]).getRawType();

    Class<?> valueClazz =
        actualTypes[1] instanceof Class
            ? (Class<?>) actualTypes[1]
            : (Class<?>) ((ParameterizedType) actualTypes[1]).getRawType();

    for (Object jsonObjKey : jsonObj.keySet()) {

      String jsonKey = jsonObjKey.toString();
      Object jsonValue = jsonObj.get(jsonKey);
      String jsonStrValue = jsonValue == null ? null : jsonValue.toString();

      Object keyObj = dispatcher(jsonKey, keyClazz, null, validationException);

      Object valueObj = dispatcher(jsonStrValue, valueClazz, null, validationException);

      mapInstance.put(keyObj, valueObj);
    }

    return mapInstance;
  }
  /**
   * Gets the json.
   *
   * @param AssignedToUser the assigned to user
   * @param subjectId the subject id
   * @param tittle the tittle
   * @param content the content
   * @return the json
   * @throws Exception the exception
   */
  private String getJSON(String AssignedToUser, String subjectId, String tittle, String content)
      throws Exception {

    JSONObject json1 = new JSONObject();

    json1.put("subjectId", subjectId);
    json1.put("assignedUserId", AssignedToUser);
    json1.put("title", tittle);
    JSONArray parameter = new JSONArray();
    parameter.add(json1);
    parameter.add(content);

    JSONObject json = new JSONObject();
    json.put("parameters", parameter);

    return json.toString();
  }
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    PrintWriter out = resp.getWriter();

    String json = req.getParameter("json");
    String key = req.getParameter("key");

    String retval = new String();
    DBProc dbProc = new DBProc();

    ProfileProperties prop = dbProc.verifyProfileKey(key);

    if (prop == null) {
      out.print("Profile Key " + key + " was not Verified");
      out.flush();
      out.close();
      return;
    }

    if (!prop.ispEnabled()) {
      out.print("Profile Key " + key + " is not Enabled");
      out.flush();
      out.close();
      return;
    }

    if (!prop.isPgr_sp()) {
      out.print("ShortestPath Searches for this Profile is not enabled");
      out.flush();
      out.close();
      return;
    }

    if (!prop.ispPublic()) {
      if (!HostInfo.checkHostInfo(req.getRemoteHost(), prop.getHosts())) {
        if (!HostInfo.checkHostInfo(req.getRemoteAddr(), prop.getHosts())) {
          out.print("Not authorized to use this Service[ " + req.getRemoteAddr() + " ]");
          out.flush();
          out.close();
          return;
        }
      }
    }

    if (json == null) {
      out.print("No JSON Request Parameter");
      out.flush();
      out.close();
      return;
    }

    try {
      JSONObject jo = new JSONObject(json);
      String proj = jo.getString("projection");
      String source = jo.getJSONArray("points").getString(0);
      String target = jo.getJSONArray("points").getString(1);

      int epsg = Integer.parseInt(proj.split(":")[1]);

      if (epsg != RouteProperties.getSrid()) {
        source = dbProc.transformPoint(source, epsg);
        target = dbProc.transformPoint(target, epsg);
      }

      retval = dbProc.findShortestPath(prop.getId(), source, target, prop.isReverse_cost());
    } catch (Exception ex) {
      retval = "Error has occured";
      ex.printStackTrace();
    }

    resp.setContentType("application/json");

    out.print(retval);
    out.flush();
    out.close();
  }
 /**
  * Writes the JSON object to file and calls the parseJSON method in the jsonGroupParser object for
  * testing.
  *
  * @throws IOException
  * @throws AdeException
  */
 public void writeToFileAndParseJSON() throws IOException, AdeException {
   fileWriter.write(jsonGroupObject.toString());
   fileWriter.flush();
   jsonGroupParser.parseJSON(jsonFile);
 }
  public JSONObject toJSON() {
    JSONObject json = new JSONObject();

    JSONObject LDPLJSON = new JSONObject();
    JSONObject GPJSON = new JSONObject();
    JSONObject optJSON = new JSONObject();

    try {
      double[] params = getParams();
      LDPLJSON
          .put("n", params[0])
          .put("A", params[1])
          .put("fa", params[2])
          .put("fb", params[3])
          .put(HDIFF, hDiff);

      GPJSON.put("lengthes", new Double[] {lengthes[0], lengthes[1], lengthes[2]});
      GPJSON
          .put("sigmaP", stdev)
          .put("sigmaN", sigmaN)
          .put("useMask", gpLDPL.getUseMask() ? 1 : 0)
          .put("constVar", gpLDPL.getOptConstVar());

      optJSON.put("optimizeHyperParameters", doHyperParameterOptimize ? 1 : 0);

      json.put(LDPLParameters, LDPLJSON);
      json.put(GPParameters, GPJSON);
      json.put(OPTIONS, optJSON);

    } catch (JSONException e) {
      e.printStackTrace();
    }

    return json;
  }
  public void settingFromJSON(JSONObject json) {
    jsonParams = json;
    try {
      JSONObject ldplParams = json.getJSONObject(LDPLParameters);
      JSONObject gpParams = json.getJSONObject(GPParameters);
      JSONObject optJSON = json.getJSONObject(OPTIONS);

      // LDPLParameters
      double n = ldplParams.getDouble("n");
      double A = ldplParams.getDouble("A");
      double fa = ldplParams.getDouble("fa");
      double fb = ldplParams.getDouble("fb");
      if (ldplParams.containsKey(HDIFF)) {
        double hDiff = ldplParams.getDouble(HDIFF);
        this.setParams(new double[] {n, A, fa, fb});
        this.setHDiff(hDiff);
      }

      // GPParamters
      JSONArray jarray = gpParams.getJSONArray("lengthes");
      lengthes = JSONUtils.array1DfromJSONArray(jarray);
      stdev = gpParams.getDouble("sigmaP");
      sigmaN = gpParams.getDouble("sigmaN");

      boolean useMask = (gpParams.getInt("useMask") == 1);
      int optConstVar = gpParams.getInt("constVar");

      gpLDPL.setUseMask(useMask);
      gpLDPL.setOptConstVar(optConstVar);

      // Options
      doHyperParameterOptimize = optJSON.optBoolean("optimizeHyperParameters");
      if (!doHyperParameterOptimize) {
        doHyperParameterOptimize = optJSON.optInt("optimizeHyperParameters") == 1;
      }

      // Optional variables
      if (gpParams.containsKey(ARRAYS)) {
        JSONObject jobjArrays = gpParams.getJSONObject(ARRAYS);
        gpLDPL.fromJSON(jobjArrays);
      }
      if (json.containsKey(LIKELIHOOD_MODEL)) {
        JSONObject likelihoodJSON = json.getJSONObject(LIKELIHOOD_MODEL);
        LikelihoodModel likelihoodModel = LikelihoodModelFactory.create(likelihoodJSON);
        gpLDPL.setLikelihoodModel(likelihoodModel);
      } else {
        System.out.println("The key for [" + LIKELIHOOD_MODEL + "] was not found.");
      }

      if (json.containsKey(BEACON_FILTER)) {
        JSONObject bfJSON = json.getJSONObject(BEACON_FILTER);
        BeaconFilter bf = BeaconFilterFactory.create(bfJSON);
        beaconFilter = bf;
      } else {
        System.out.println("The key for [" + BEACON_FILTER + "] was not found.");
      }

    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 17
0
 private void importActivity(JSONObject activity, String portal_image_url) {
   // System.out.println(activity.toString());
   try {
     JSONObject member = activity.getJSONObject("member");
     if (member.containsKey("id")) {
       String title =
           activity.getString("body").replace(activity.getString("image_large_url"), "").trim();
       DBObject photo = new BasicDBObject();
       photo.put("portal_image_url", portal_image_url);
       if (mPhotoCollection.count(photo) > 0) {
         System.err.println(portal_image_url + " already exists");
         return;
       } else {
         System.out.println("Inserting " + portal_image_url);
       }
       String imageSourceUrl =
           Config.PORTAL_URL.startsWith("http:")
               ? portal_image_url.replace("https://", "http://")
               : portal_image_url;
       BufferedImage[] images = ImageUtil.convertImage(new URL(imageSourceUrl));
       if (images == null) {
         System.err.println(portal_image_url + " corrupted");
         return;
       }
       saveThumbnailImages(photo, images, "/" + getFileId(portal_image_url) + ".png");
       photo.put("uploader_user_id", member.getString("id"));
       photo.put("title", title);
       Object exifObj = getExifData(portal_image_url);
       Date date = null;
       if (exifObj instanceof JSONObject) {
         JSONObject exif = (JSONObject) exifObj;
         if (exif.containsKey("date")) {
           try {
             date = FORMAT_DATE_ISO.parse(exif.getString("date"));
           } catch (ParseException e) {
             e.printStackTrace();
           }
         }
         if (exif.containsKey("location")) {
           photo.put("exif_location", exif.getJSONArray("location"));
         }
       }
       if (date == null && activity.containsKey("created_at")) {
         try {
           date = FORMAT_DATE.parse(activity.getString("created_at"));
         } catch (ParseException e) {
           e.printStackTrace();
         }
       }
       if (date != null) {
         photo.put("exif_date", date);
       }
       mPhotoCollection.insert(photo);
       // System.out.println(photo);
       // System.out.println();
     }
   } catch (JSONException | MalformedURLException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 18
0
  public static List<BLEBeacon> readMapBLEBeacons(InputStream is) {
    int z = 0;
    List<BLEBeacon> bleBeacons = new ArrayList<>();

    try {
      JSONObject json = (JSONObject) JSON.parse(is);

      String type = json.getString("type");
      if (type.equals("FeatureCollection")) {
        JSONArray features = json.getJSONArray("features");
        Iterator<JSONObject> iter = features.iterator();
        while (iter.hasNext()) {
          JSONObject feature = iter.next();
          JSONObject properties = feature.getJSONObject("properties");
          JSONObject geometry = feature.getJSONObject("geometry");
          type = properties.getString("type");
          if (type.equals("beacon")) {

            int major = Integer.parseInt(properties.getString("major"));
            int minor = Integer.parseInt(properties.getString("minor"));
            String uuid = properties.getString("uuid");
            int outPower = Integer.parseInt(properties.getString("power"));
            int interval = Integer.parseInt(properties.getString("interval"));

            double x = geometry.getJSONArray("coordinates").getInt(0);
            double y = geometry.getJSONArray("coordinates").getInt(1);

            BLEBeacon bleBeacon = new BLEBeacon(minor, major, minor, x, y, z);
            bleBeacon.setUuid(uuid);
            bleBeacon.setOutputPower(outPower);

            bleBeacons.add(bleBeacon);
          }
        }
      }
    } catch (NullPointerException | JSONException e) {
      e.printStackTrace();
    }

    return bleBeacons;
  }
Ejemplo n.º 19
0
  public static List<Location> readWalkLocations(InputStream is) {
    int z = 0;
    List<Location> locs = new ArrayList<>();
    try {
      JSONObject json = (JSONObject) JSON.parse(is);
      String type = json.getString("type");
      if (type.equals("FeatureCollection")) {
        JSONArray features = json.getJSONArray("features");
        Iterator<JSONObject> iter = features.iterator();
        while (iter.hasNext()) {
          JSONObject feature = iter.next();
          JSONObject properties = feature.getJSONObject("properties");
          JSONObject geometry = feature.getJSONObject("geometry");
          type = properties.getString("type");
          if (type.equals("walk")) {

            double height = Double.parseDouble(properties.getString("height"));
            int repeat = Integer.parseInt(properties.getString("repeat"));

            JSONArray coordinates = geometry.getJSONArray("coordinates");

            Iterator<JSONArray> iterCoords = coordinates.iterator();
            while (iterCoords.hasNext()) {
              JSONArray coord = iterCoords.next();

              double x = coord.getDouble(0);
              double y = coord.getDouble(1);

              Location loc = new Location(x, y, z);
              loc.setH((float) height);

              for (int t = 0; t < repeat; t++) {
                locs.add(loc);
              }
            }
          }
        }
      }
    } catch (NullPointerException | JSONException e) {
      e.printStackTrace();
    }
    return locs;
  }
Ejemplo n.º 20
0
  public static List<Location> readGridLocations(InputStream is) {

    int z = 0;

    List<Location> locs = new ArrayList<>();
    try {
      JSONObject json = (JSONObject) JSON.parse(is);
      String type = json.getString("type");
      if (type.equals("FeatureCollection")) {
        JSONArray features = json.getJSONArray("features");
        Iterator<JSONObject> iter = features.iterator();
        while (iter.hasNext()) {
          JSONObject feature = iter.next();
          JSONObject properties = feature.getJSONObject("properties");
          JSONObject geometry = feature.getJSONObject("geometry");
          String propertiesType = properties.getString("type");
          String geometryType = geometry.getString("type");
          if (propertiesType.equals("grid")) {
            double height = Double.parseDouble(properties.getString("height"));
            int repeat = Integer.parseInt(properties.getString("repeat"));
            int spacing = Integer.parseInt(properties.getString("interval"));

            JSONArray coordinates = geometry.getJSONArray("coordinates");
            Iterator<JSONArray> iterCoords = null;
            if (geometryType.equals("Polygon")) {
              JSONArray exteriorRing = coordinates.getJSONArray(0);
              iterCoords = exteriorRing.iterator();
            } else if (geometryType.equals("LineString")) {
              iterCoords = coordinates.iterator();
            }

            double minx = Double.MAX_VALUE;
            double miny = Double.MAX_VALUE;
            double maxx = -Double.MAX_VALUE;
            double maxy = -Double.MAX_VALUE;
            while (iterCoords.hasNext()) {
              JSONArray coord = iterCoords.next();
              double x = coord.getDouble(0);
              double y = coord.getDouble(1);
              minx = Math.min(minx, x);
              miny = Math.min(miny, y);
              maxx = Math.max(maxx, x);
              maxy = Math.max(maxy, y);
            }

            double x = minx;
            while (x <= maxx) {
              double y = miny;
              while (y <= maxy) {
                Location loc = new Location(x, y, z);
                loc.setH((float) height);
                for (int t = 0; t < repeat; t++) {
                  locs.add(loc);
                }
                y += spacing;
              }
              x += spacing;
            }
          }
        }
      }
    } catch (NullPointerException | JSONException e) {
      e.printStackTrace();
    }
    return locs;
  }
Ejemplo n.º 21
0
  protected Object parseBean(
      JSONObject jsonObj, Class<?> beanClazz, ValidationException validationException)
      throws IntrospectionException, IllegalAccessException, InstantiationException, JSONException,
          InvocationTargetException, ParseException {
    if (beanClazz == null) {

      throw new AJAXParserException("No specific class type.");
    }
    if (jsonObj == null) {

      return null;
    }

    BeanInfo info = Introspector.getBeanInfo(beanClazz);
    PropertyDescriptor[] propDescriptors = info.getPropertyDescriptors();

    Object instance = beanClazz.newInstance();
    for (PropertyDescriptor property : propDescriptors) {
      String name = property.getName();
      Class<?> propClazz = property.getPropertyType();
      if (Class.class.equals(propClazz)) {

        continue;
      }

      Method setter = property.getWriteMethod();
      if (setter == null) {

        continue;
      }

      if ((propClazz.equals(java.sql.Date.class)
              || propClazz.equals(java.sql.Time.class)
              || propClazz.equals(java.sql.Timestamp.class)
              || propClazz.equals(java.util.Date.class))
          && jsonObj.containsKey(name)) {
        Object tempValue = jsonObj.get(name);
        if (tempValue != null && StringUtil.isEmpty(tempValue.toString())) {
          tempValue = null;
          jsonObj.put(name, tempValue);
        }
      }

      if (validateValue(beanClazz, name, jsonObj, validationException)
          && jsonObj.containsKey(name)) {

        Object nestObj = null;

        if (isServiceBeanType(propClazz)) {
          JSONObject jsonObjPropValue = jsonObj.getJSONObject(name);
          nestObj = parseBean(jsonObjPropValue, propClazz, validationException);
        } else if (isBasicType(propClazz)) {

          Object jsonObjPropValue = jsonObj.get(name);
          nestObj =
              parseBasic(jsonObjPropValue == null ? null : jsonObjPropValue.toString(), propClazz);
        } else if (propClazz.isArray()) {
          if (jsonObj.get(name) == null) {
            continue;
          }
          JSONArray jsonArrPropValue = jsonObj.getJSONArray(name);
          nestObj = parseArray(jsonArrPropValue, propClazz.getComponentType(), validationException);
        } else if (List.class.isAssignableFrom(propClazz)) {
          if (jsonObj.get(name) == null) {
            continue;
          }
          Type genericType = property.getReadMethod().getGenericReturnType();
          JSONArray jsonArrPropValue = jsonObj.getJSONArray(name);
          nestObj = parseList(jsonArrPropValue, propClazz, genericType, validationException);
        } else if (Map.class.isAssignableFrom(propClazz)) {
          Type genericType = property.getReadMethod().getGenericReturnType();
          JSONObject jsonObjPropValue = jsonObj.getJSONObject(name);
          nestObj = parseMap(jsonObjPropValue, propClazz, genericType, validationException);
        } else if (java.lang.Object.class.equals(propClazz)) {

          nestObj = jsonObj.getJSONObject(name);
        } else {
          nestObj = null;
        }

        setter.invoke(instance, new Object[] {nestObj});
      }
    }

    return instance;
  }
Ejemplo n.º 22
0
  public static List<Wall> readWalls(InputStream is) {

    int z = 0;

    List<Wall> walls = new ArrayList<>();

    try {
      JSONObject json = (JSONObject) JSON.parse(is);

      String type = json.getString("type");
      if (type.equals("FeatureCollection")) {
        JSONArray features = json.getJSONArray("features");
        Iterator<JSONObject> iter = features.iterator();
        while (iter.hasNext()) {
          JSONObject feature = iter.next();
          JSONObject properties = feature.getJSONObject("properties");
          JSONObject geometry = feature.getJSONObject("geometry");
          type = properties.getString("type");
          if (type.equals("wall")) {

            double height = Double.parseDouble(properties.getString("height"));
            double attenuation = Double.parseDouble(properties.getString("decay"));

            JSONArray coordsArray = geometry.getJSONArray("coordinates");
            int npoints = coordsArray.size();

            for (int i = 0; i < npoints - 1; i++) {
              JSONArray p0 = coordsArray.getJSONArray(i);
              JSONArray p1 = coordsArray.getJSONArray(i + 1);

              Wall wall =
                  new Wall.Builder(
                          p0.getDouble(0), p0.getDouble(1), p1.getDouble(0), p1.getDouble(1))
                      .height(height)
                      .attenuation(attenuation)
                      .build();

              walls.add(wall);
            }
          }
        }
      }
    } catch (NullPointerException | JSONException e) {
      e.printStackTrace();
    }

    return walls;
  }
Ejemplo n.º 23
0
  protected boolean validateValue(
      Class<?> beanClazz, String name, JSONObject jsonObj, ValidationException validationException)
      throws JSONException {
    boolean rightValue = true;

    try {
      Field field = beanClazz.getDeclaredField(name);
      Annotation[] annotations = field.getDeclaredAnnotations();

      ArrayList<Annotation> validators = new ArrayList<Annotation>();
      boolean inputRequired = false;
      for (Annotation annotation : annotations) {

        if (AnnotationValidator.isValidationAnnotation(annotation)) {
          validators.add(annotation);
        }

        if (!inputRequired) {
          if (annotation instanceof com.maxiaohua.genealogy.fw.core.validator.type.NotNull
              || annotation instanceof com.maxiaohua.genealogy.fw.core.validator.type.NotEmpty) {
            inputRequired = true;
          } else if (annotation instanceof MultiField) {
            MultiField multiField = (MultiField) annotation;
            if (multiField
                .validator()
                .equals(com.maxiaohua.genealogy.fw.core.validator.type.NotAllEmpty.class)) {
              inputRequired = true;
            }
          }
        }
      }

      boolean sitei = jsonObj.containsKey(name);

      if (inputRequired || (sitei && jsonObj.get(name) != null)) {

        Collections.sort(
            validators,
            new Comparator<Annotation>() {
              public int compare(Annotation arg0, Annotation arg1) {
                int result = -1;
                try {
                  Integer junban0 =
                      (Integer) arg0.getClass().getDeclaredMethod(KEY_JUNBAN).invoke(arg0);
                  Integer junban2 =
                      (Integer) arg1.getClass().getDeclaredMethod(KEY_JUNBAN).invoke(arg1);
                  result = junban0.compareTo(junban2);
                } catch (NoSuchMethodException nsme) {
                  errorLogger.writeErrorLog(nsme.getMessage());
                  appLogger.error(nsme.getMessage(), nsme);
                  debugLogger.error(nsme.getMessage(), nsme);
                } catch (InvocationTargetException ite) {
                  errorLogger.writeErrorLog(ite.getMessage());
                  appLogger.error(ite.getMessage(), ite);
                  debugLogger.error(ite.getMessage(), ite);

                } catch (IllegalAccessException iae) {
                  errorLogger.writeErrorLog(iae.getMessage());
                  appLogger.error(iae.getMessage(), iae);
                  debugLogger.error(iae.getMessage(), iae);
                }
                return result;
              }
            });

        for (Annotation annotation : validators) {

          if (annotation instanceof MultiField) {
            MultiField multiField = (MultiField) annotation;
            String[] fieldNames = multiField.others();
            if (fieldNames != null) {

              Object[] values = new Object[fieldNames.length + 1];
              if (sitei) {
                values[0] = jsonObj.get(name);
              }
              for (int i = 0; i < fieldNames.length; i++) {
                if (jsonObj.containsKey(fieldNames[i])) {
                  values[i + 1] = jsonObj.get(fieldNames[i]);
                }
              }

              AnnotationValidator validator = AnnotationValidationUtil.validate(values, annotation);

              if (validator != null) {

                String errorCode = validator.getErrorCode();
                String fieldBungen = beanClazz.getName() + "." + name;
                Alias alias = (Alias) field.getAnnotation(Alias.class);
                if (alias != null) {
                  fieldBungen = alias.value();
                }
                String[] parameters = null;
                String[] ps = validator.getMsgParameters();
                if (ps == null) {
                  parameters = new String[2];
                  parameters[0] = fieldBungen;
                  StringBuffer othersBungen = new StringBuffer();
                  for (int i = 0; i < fieldNames.length; i++) {
                    try {
                      String bungen = beanClazz.getName() + "." + name;
                      Field f = beanClazz.getDeclaredField(fieldNames[i]);
                      Alias a = (Alias) f.getAnnotation(Alias.class);
                      if (a != null) {
                        bungen = a.value();
                      }
                      if (i == 0) {
                        othersBungen.append(bungen);
                      } else {
                        othersBungen.append(",").append(bungen);
                      }
                    } catch (NoSuchFieldException nsfe) {
                      nsfe.printStackTrace();
                    }
                  }
                  parameters[1] = othersBungen.toString();
                } else {
                  parameters = new String[ps.length + 1];
                  parameters[0] = fieldBungen;
                  for (int i = 0; i < ps.length; i++) {
                    parameters[i + 1] = ps[i];
                  }
                }

                validationException.addValidationException(errorCode, parameters, null);
                rightValue = false;
              }
            }
          } else {
            Object value = null;
            if (sitei) {
              value = jsonObj.get(name);
            }

            AnnotationValidator validator = AnnotationValidationUtil.validate(value, annotation);

            if (validator != null) {

              String errorCode = validator.getErrorCode();
              String fieldBungen = beanClazz.getName() + "." + name;
              Alias alias = (Alias) field.getAnnotation(Alias.class);
              if (alias != null) {
                fieldBungen = alias.value();
              }
              String[] parameters = null;
              String[] ps = validator.getMsgParameters();
              if (ps == null) {
                parameters = new String[] {fieldBungen};
              } else {
                parameters = new String[ps.length + 1];
                parameters[0] = fieldBungen;
                for (int i = 0; i < ps.length; i++) {
                  parameters[i + 1] = ps[i];
                }
              }

              validationException.addValidationException(errorCode, parameters, null);
              rightValue = false;
            }
          }

          if (!rightValue) {
            break;
          }
        }
      }
    } catch (NoSuchFieldException nsfe) {

    }

    return rightValue;
  }