Example #1
0
  /**
   * Parses error response.
   *
   * @param response parsed <tt>ErrorResponse</tt>
   * @return <tt>ErrorResponse</tt> parsed from HTTP content stream.
   * @throws IOException if any IO issues occur.
   * @throws ParseException if any issues with JSON parsing occur.
   */
  private ErrorResponse readErrorResponse(HttpResponse response)
      throws IOException, ParseException {
    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    jsonParser.parse(rd, errorJson);

    return errorJson.getResult();
  }
Example #2
0
  private LinkedHashMap getJsonRoot() throws IOException, ParseException {
    Object parse =
        parser.parse(
            br,
            new ContainerFactory() {
              @Override
              public LinkedHashMap createObjectContainer() {
                return new LinkedHashMap();
              }

              @Override
              public List createArrayContainer() {
                return new LinkedList();
              }
            });
    return (LinkedHashMap) parse;
  }
Example #3
0
  public UrlNode(String location) {
    parser = new JSONParser();
    try {
      try {
        URLConnection conn = new URL(location).openConnection();
        InputStream response = conn.getInputStream();

        // STUPID hack to convert an InputStream to a String in one line:
        InputStream input = conn.getInputStream();
        try {
          this.content = new java.util.Scanner(input).useDelimiter("\\A").next();
          ContainerFactory containerFactory =
              new ContainerFactory() {
                public List creatArrayContainer() {
                  return new LinkedList();
                }

                public Map createObjectContainer() {
                  return new LinkedHashMap();
                }
              };

          try {
            Map json = (Map) parser.parse(content, containerFactory);
            Iterator iter = json.entrySet().iterator();
            data = new HashMap<String, String>();
            while (iter.hasNext()) {
              Map.Entry entry = (Map.Entry) iter.next();
              data.put(entry.getKey().toString(), entry.getValue().toString());
            }
          } catch (ParseException pe) {
          }
        } catch (java.util.NoSuchElementException e) {
          this.content = "{\"Error\": \"NO CONTENT\"}";
        }
      } catch (MalformedURLException e) {
      }
    } catch (IOException e) {
    }
  }
Example #4
0
  /**
   * Parses JSON string returned in HTTP response and converts it to <tt>Conference</tt> instance.
   *
   * @param conference <tt>Conference</tt> instance that contains the data returned by API endpoint.
   * @param response HTTP response returned by the API endpoint.
   * @return <tt>Conference</tt> instance that contains the data returned by API endpoint.
   * @throws IOException if any IO problems occur.
   * @throws ParseException if any problems with JSON parsing occur.
   */
  private Conference readConferenceResponse(Conference conference, HttpResponse response)
      throws IOException, ParseException {
    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    if (conference != null) {
      conferenceJson.setForUpdate(conference);
    }

    jsonParser.parse(rd, conferenceJson);

    if (conference == null) {
      conference = conferenceJson.getResult();
    }

    logger.info("ID: " + conference.getId());
    logger.info("PIN: " + conference.getPin());
    logger.info("URL: " + conference.getUrl());
    logger.info("SIP ID: " + conference.getSipId());
    logger.info("START TIME: " + conference.getStartTime());
    logger.info("DURATION: " + conference.getDuration());

    return conference;
  }
Example #5
0
  public Map getTaskMapBatch(String objectId) throws Exception {

    Map map = new HashMap();

    String apiURL = "https://rally1.rallydev.com/slm/webservice/1.34/adhoc";

    String requestJSON =
        "{"
            + "\"task\" : \"/task?query=(ObjectID%20=%20"
            + objectId
            + ")&fetch=true\","
            + "\"userstory\" : \"/hierarchicalrequirement?query=(ObjectID%20=%20${task.WorkProduct.ObjectID})&fetch=FormattedID\","
            + "\"timeentryitem\":\"/timeentryitem?query=(Task.ObjectID%20=%20"
            + objectId
            + ")&fetch=Values\","
            + "\"timespent\":\"${timeentryitem.Values.Hours}\""
            + "}";

    log.info("apiURL=" + apiURL);
    log.info("requestJSON=" + requestJSON);

    String responseJSON = postRallyXML(apiURL, requestJSON);

    // log.info("responseJSON="+responseJSON);

    // Map jsonMap=JsonUtil.jsonToMap(responseJSON);
    JSONParser parser = new JSONParser();
    Map jsonMap = (Map) parser.parse(responseJSON);

    // log.info("jsonMap="+jsonMap);

    String taskObjId = "";
    String taskFormattedId = "";
    String taskName = "";
    String estimate = "";
    String toDo = "";
    String taskState = "";
    String taskOwner = "";
    String userstoryFormattedId = "";

    // Get task info
    JSONObject taskMap = (JSONObject) jsonMap.get("task");
    JSONArray taskArray = (JSONArray) taskMap.get("Results");
    if (taskArray != null && taskArray.size() > 0) {
      JSONObject taskInfo = (JSONObject) taskArray.get(0);
      // log.info("taskMap="+taskMap);
      // log.info("taskInfo="+taskInfo);

      taskObjId = (taskInfo.get("ObjectID")).toString();
      taskFormattedId = (taskInfo.get("FormattedID")).toString();
      taskState = (taskInfo.get("State")).toString();

      Object taskNameObj = taskInfo.get("Name");
      taskName = taskNameObj == null ? "" : taskNameObj.toString();

      Object estimateObject = taskInfo.get("Estimate");
      estimate = estimateObject == null ? "" : estimateObject.toString();

      Object toDoObject = taskInfo.get("ToDo");
      toDo = toDoObject == null ? "" : toDoObject.toString();

      JSONObject ownerMap = (JSONObject) taskInfo.get("Owner");
      log.info("ownerMap=" + ownerMap);
      if (ownerMap != null) {
        taskOwner = (String) ownerMap.get("_refObjectName");
        if (taskOwner == null) {
          taskOwner = "";
        }
      }
    }

    // Get user story info
    JSONObject userstoryMap = (JSONObject) jsonMap.get("userstory");
    JSONArray userstoryArray = (JSONArray) userstoryMap.get("Results");
    if (userstoryArray != null && userstoryArray.size() > 0) {
      JSONObject userstoryInfo = (JSONObject) userstoryArray.get(0);

      userstoryFormattedId = (userstoryInfo.get("FormattedID")).toString();
      log.info("userstoryFormattedId=" + userstoryFormattedId);
    }

    // Calculate timeSpent
    JSONArray timeSpentList = (JSONArray) jsonMap.get("timespent");
    log.info("timeSpentList=" + timeSpentList);

    double timeSpent = 0.0;
    for (int i = 0; i < timeSpentList.size(); i++) {
      String timeSpentString = (String) timeSpentList.get(i);

      if (timeSpentString != null) {
        timeSpent += Double.parseDouble(timeSpentString);
      }
    }

    map.put("type", "task");
    map.put("formattedId", taskFormattedId);
    map.put("usId", userstoryFormattedId);
    map.put("name", taskName);
    map.put("taskStatus", taskState);
    map.put("owner", taskOwner);
    map.put("taskEstimateTotal", estimate);
    map.put("taskRemainingTotal", toDo);
    map.put("taskTimeSpentTotal", "" + timeSpent);

    return map;
  }
Example #6
0
  public double getTimeSpentByTask(String taskNo) throws Exception {

    double timeSpent = 0.0D;

    String apiURL = "https://rally1.rallydev.com/slm/webservice/1.34/adhoc";

    String requestJSON =
        "{"
            + "\"task\" : \"/task?query=(FormattedID%20=%20"
            + taskNo
            + ")&fetch=true\","
            + "\"timeentryitem\":\"/timeentryitem?query=(Task.FormattedID%20=%20"
            + taskNo
            + ")&fetch=Values\","
            + "\"timespent\":\"${timeentryitem.Values.Hours}\""
            + "}";

    log.info("apiURL=" + apiURL);
    log.info("requestJSON=" + requestJSON);

    String responseJSON = postRallyXML(apiURL, requestJSON);

    // log.info("responseJSON="+responseJSON);

    // Map jsonMap=JsonUtil.jsonToMap(responseJSON);
    JSONParser parser = new JSONParser();
    Map jsonMap = (Map) parser.parse(responseJSON);

    /*
    //log.info("jsonMap="+jsonMap);

    String taskObjId="";
    String taskFormattedId="";
    String taskName="";
    String estimate="";
    String toDo="";
    String taskState="";
    String taskOwner="";
    String userstoryFormattedId="";

    //Get task info
    JSONObject taskMap=(JSONObject)jsonMap.get("task");
    JSONArray taskArray=(JSONArray)taskMap.get("Results");
    if(taskArray!=null && taskArray.size()>0) {
    	JSONObject taskInfo=(JSONObject)taskArray.get(0);
    	//log.info("taskMap="+taskMap);
    	//log.info("taskInfo="+taskInfo);

    	taskObjId=(taskInfo.get("ObjectID")).toString();
    	taskFormattedId=(taskInfo.get("FormattedID")).toString();
    	taskState=(taskInfo.get("State")).toString();

    	Object taskNameObj=taskInfo.get("Name");
    	taskName=taskNameObj==null ? "" : taskNameObj.toString();

    	Object estimateObject=taskInfo.get("Estimate");
    	estimate=estimateObject==null ? "" : estimateObject.toString();

    	Object toDoObject=taskInfo.get("ToDo");
    	toDo=toDoObject==null ? "" : toDoObject.toString();

    	JSONObject ownerMap=(JSONObject)taskInfo.get("Owner");
    	log.info("ownerMap="+ownerMap);
    	if(ownerMap!=null) {
    		taskOwner=(String)ownerMap.get("_refObjectName");
    		if(taskOwner==null) {
    			taskOwner="";
    		}
    	}
    }

    //Get user story info
    JSONObject userstoryMap=(JSONObject)jsonMap.get("userstory");
    JSONArray userstoryArray=(JSONArray)userstoryMap.get("Results");
    if(userstoryArray!=null && userstoryArray.size()>0) {
    	JSONObject userstoryInfo=(JSONObject)userstoryArray.get(0);

    	userstoryFormattedId=(userstoryInfo.get("FormattedID")).toString();
    	log.info("userstoryFormattedId="+userstoryFormattedId);
    }
    */

    // Calculate timeSpent
    JSONArray timeSpentList = (JSONArray) jsonMap.get("timespent");
    log.info("timeSpentList=" + timeSpentList);

    // double timeSpent=0.0;
    for (int i = 0; i < timeSpentList.size(); i++) {
      String timeSpentString = (String) timeSpentList.get(i);

      if (timeSpentString != null) {
        timeSpent += Double.parseDouble(timeSpentString);
      }
    }

    return timeSpent;
  }
Example #7
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      JSONParser parser = new JSONParser();
      String originalRouteJsonString = request.getParameter("originalroutejsontext");
      JSONObject originalRouteJsonObject = (JSONObject) parser.parse(originalRouteJsonString);
      JSONObject routes = (JSONObject) ((JSONArray) originalRouteJsonObject.get("routes")).get(0);
      JSONArray legs = (JSONArray) routes.get("legs");
      JSONArray steps = (JSONArray) ((JSONObject) legs.get(0)).get("steps");

      String routeID = request.getParameter("routeid");
      // System.out.println("Route steps loaded in a JSONArray...size is " + steps.size());

      List<Double> stepLats = new ArrayList<Double>();
      List<Double> stepLngs = new ArrayList<Double>();

      for (int i = 0; i < steps.size(); i++) {
        JSONObject temp = (JSONObject) ((JSONObject) steps.get(i)).get("end_location");
        // System.out.println("Lat of end_location of step " + i + " " + temp.get("lat"));
        stepLats.add(Double.parseDouble(temp.get("lat").toString()));
        stepLngs.add(Double.parseDouble(temp.get("lng").toString()));
      }
      // System.out.println("All steps set with size " + stepLngs.size() + " and " +
      // stepLats.size());

      // System.out.println("Skipping route boxer...");
      // RouteBoxer routeBoxer = new RouteBoxer(stepLats, stepLngs,
      // Double.parseDouble(request.getParameter("radius")));

      // if(routeBoxer.getFlag())
      //  throw new RuntimeException("Could not create boxes for the route");

      // List<Double> boxLats = routeBoxer.getLats();
      // List<Double> boxLngs = routeBoxer.getLngs();

      // System.out.println("Calculated boxes with number of lats " + boxLats.size() + " and number
      // of lngs " + boxLngs.size());

      double r = Double.parseDouble(request.getParameter("radius").toString());
      int radius = r > RADIUS_TO_LOOK_FOR_PLACES ? RADIUS_TO_LOOK_FOR_PLACES : (int) r;

      String[] types = request.getParameter("keywords").split(",");
      System.out.println("Size of types is " + types.length);

      JSONObject finalPlacesJSONObject = new JSONObject();

      for (int j = 0; j < types.length; j++) {
        JSONArray jsonArrayForType = new JSONArray();

        for (int i = 0; i < stepLats.size(); i++) {
          JSONObject placesAroundLocationJSONObject =
              (JSONObject)
                  parser.parse(
                      GoogleMap.getPlacesAroundLocation(
                          stepLats.get(i), stepLngs.get(i), radius, types[j]));
          JSONArray placesAroundLocationJSONArray =
              (JSONArray) placesAroundLocationJSONObject.get("results");

          if (!placesAroundLocationJSONArray.isEmpty()) {
            jsonArrayForType.addAll(placesAroundLocationJSONArray);
          }
        }
        finalPlacesJSONObject.put(types[j], jsonArrayForType);
      }
      List<String> place_ids = new ArrayList<String>();

      finalPlacesJSONObject = removeDuplicatePlaces(finalPlacesJSONObject);
      finalPlacesJSONObject =
          filterPlacesRandomly(finalPlacesJSONObject, FINAL_PLACES_NUMBER_PER_REQUEST, place_ids);

      // System.out.println("MAGIC " + place_ids.toString());
      DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
      MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();

      // add places as a property of original route entity
      Entity originalRouteEntity =
          datastore.get(KeyFactory.createKey("Route", Long.parseLong(routeID)));
      Text placesJsonAsText = new Text(finalPlacesJSONObject.toJSONString());
      originalRouteEntity.setProperty("placesJSON", placesJsonAsText);
      datastore.put(originalRouteEntity);
      // System.out.println("SUCCESS written places to datastore");

      // add task for fetching place reviews to queue
      QueueFactory.getDefaultQueue()
          .add(
              TaskOptions.Builder.withUrl("/waypointsreview")
                  .param("places", place_ids.toString()));

      System.out.println("Task to get reviews added to queue");
      // We cache the route entity
      String cacheKey = "route-" + routeID;
      syncCache.put(cacheKey, originalRouteEntity);
    } catch (Exception e) {
      System.out.println("ERROR " + e.getMessage());
      e.printStackTrace();
    }
  }
 public static <T> T parseObject(String json, Type type) {
   Object object = null;
   if (StringUtils.isEmpty(json)) {
     throw new JSONException("illegal json: json is empty");
   }
   json = json.trim();
   if (json.startsWith("{")) {
     object = new JSONObject(json);
   } else if (json.startsWith("[")) {
     object = new JSONArray(json);
   } else {
     throw new JSONException("illegal json:" + json);
   }
   return JSONParser.parse(object, type);
 }