Exemplo n.º 1
0
  private void getTrafficSpots() {
    controller.showProgressBar();
    String uploadWebsite =
        "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43";
    String[] ArrayOfData = null;
    StreamConnection c = null;
    InputStream s = null;
    StringBuffer b = new StringBuffer();

    String url = uploadWebsite;
    System.out.print(url);
    try {
      c = (StreamConnection) Connector.open(url);
      s = c.openDataInputStream();
      int ch;
      int k = 0;
      while ((ch = s.read()) != -1) {
        System.out.print((char) ch);
        b.append((char) ch);
      }
      // System.out.println("b"+b);
      try {
        JSONObject ff1 = new JSONObject(b.toString());
        String data1 = ff1.getString("locations");
        JSONArray jsonArray1 = new JSONArray(data1);
        Vector TrafficStatus = new Vector();
        for (int i = 0; i < jsonArray1.length(); i++) {

          System.out.println(jsonArray1.getJSONArray(i).getString(3));
          double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1));
          double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2));
          System.out.println(aDoubleLat + " " + aDoubleLon);
          TrafficStatus.addElement(
              new LocationPointer(
                  jsonArray1.getJSONArray(i).getString(3),
                  (float) aDoubleLon,
                  (float) aDoubleLat,
                  1,
                  true));
        }
        controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus));
      } catch (Exception E) {
        controller.setCurrentScreen(traf);
        new Thread() {
          public void run() {
            controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
          }
        }.start();
      }

    } catch (Exception e) {

      controller.setCurrentScreen(traf);
      new Thread() {
        public void run() {
          controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
        }
      }.start();
    }
  }
Exemplo n.º 2
0
  // Grabs assets off the intarwebz and saves them to a local store/jail for hydration.
  private void fetch(JSONArray args) {
    String url;
    String username;
    String password;
    String id;
    try {
      id = args.getString(0);
      url = args.getString(1);
      username = args.getString(2);
      password = args.getString(3);

      // Create directory for app.
      local_path = "/data/data/" + ctx.getPackageName() + "/remote_app/" + id + "/";
      File fp = new File(local_path);
      fp.mkdirs();

      if (fetchApp(url, username, password)) {
        this.success(
            new PluginResult(PluginResult.Status.OK, "file://" + local_path + "index.html"),
            this.callback);
      } else {
        this.error(
            new PluginResult(
                PluginResult.Status.ERROR,
                "Error during app saving or fetching; protocol or IO error likely."),
            this.callback);
      }
    } catch (JSONException e) {
      this.error(
          new PluginResult(
              PluginResult.Status.JSON_EXCEPTION,
              "JSON exception during argument parsing; make sure the app ID, URL, username and password were passed as an argument."),
          this.callback);
    }
  }
Exemplo n.º 3
0
  public void fillInEchoNestInfo() throws IOException, EchoNestException {
    if (artist == null || title == null) {
      JSONObject songProfile = null;
      try {
        songProfile =
            EchoNestQuery.get("song", "profile", "id=" + EchoNestId + "&bucket=audio_summary");
      } catch (EchoNestException e) {
      }

      JSONObject song = songProfile.optJSONArray("songs").optJSONObject(0);

      artist = new Artist(song.optString("artist_name"), song.optString("artist_id"));
      title = song.optString("title");
      duration = song.optJSONObject("audio_summary").optInt("duration");
    } else if (EchoNestId == null) {
      String artistName = URLEncoder.encode(artist.getName(), "UTF-8");
      String title = URLEncoder.encode(this.title, "UTF-8");

      JSONObject songSearch = null;
      try {
        songSearch =
            EchoNestQuery.get(
                "song",
                "search",
                "artist="
                    + artistName
                    + "&title="
                    + title
                    + "&results=1"
                    + "&bucket=audio_summary");
      } catch (EchoNestException e) {
      }

      JSONArray songs = songSearch.optJSONArray("songs");
      if (songs.length() == 0) throw new EchoNestException(6, "No items found.");

      JSONObject song = songs.optJSONObject(0);

      artist = new Artist(song.optString("artist_name"), song.optString("artist_id"));
      EchoNestId = song.optString("id");
      duration = song.optJSONObject("audio_summary").optInt("duration");
    } else if (duration == -1) {
      JSONObject songProfile = null;
      try {
        songProfile =
            EchoNestQuery.get("song", "profile", "id=" + EchoNestId + "&bucket=audio_summary");
      } catch (EchoNestException e) {
      }

      duration =
          songProfile
              .optJSONArray("songs")
              .optJSONObject(0)
              .optJSONObject("audio_summary")
              .optInt("duration");
    }
  }
Exemplo n.º 4
0
 public static boolean hasUpdate(int projectID, String version) {
   try {
     HttpURLConnection con =
         (HttpURLConnection)
             (new URL("https://api.curseforge.com/servermods/files?projectIds=" + projectID))
                 .openConnection();
     con.setRequestMethod("GET");
     con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
     con.setRequestProperty("Pragma", "no-cache");
     con.connect();
     JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream()));
     String[] cdigits =
         ((String) ((JSONObject) json.get(json.size() - 1)).get("name"))
             .toLowerCase()
             .split("\\.");
     String[] vdigits = version.toLowerCase().split("\\.");
     int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length;
     int a;
     int b;
     for (int i = 0; i < max; i++) {
       a = b = 0;
       try {
         a = Integer.parseInt(cdigits[i]);
       } catch (Throwable t1) {
         char[] c = cdigits[i].toCharArray();
         for (int j = 0; j < c.length; j++) {
           a += (c[j] << ((c.length - (j + 1)) * 8));
         }
       }
       try {
         b = Integer.parseInt(vdigits[i]);
       } catch (Throwable t1) {
         char[] c = vdigits[i].toCharArray();
         for (int j = 0; j < c.length; j++) {
           b += (c[j] << ((c.length - (j + 1)) * 8));
         }
       }
       if (a > b) {
         return true;
       } else if (a < b) {
         return false;
       } else if ((i == max - 1) && (cdigits.length > vdigits.length)) {
         return true;
       }
     }
   } catch (Throwable t) {
   }
   return false;
 }
Exemplo n.º 5
0
  // El string debe estar em formato json
  public boolean updateRegistry(String dataJson) {
    try {
      // Crea objeto json con string por parametro
      JSONObject json = new JSONObject(dataJson);
      // Obtiene el array de Registos
      JSONArray arr = json.getJSONArray("Registry");
      // Recorre el array
      for (int i = 0; i < arr.length(); i++) {
        // Obtiene los datos idSensor y value
        int idSensor = arr.getJSONObject(i).getInt("idSensor");

        int value = arr.getJSONObject(i).getInt("value");
        // Recorre la configuracion de registro
        for (RegistryConf reg : registryConf) {

          // Se fija si el registro corresponde a esta configuracion
          if (reg.getIdSensor() == idSensor) {

            // Checkea el criterio para guardar, o no en la BD
            // Checkea tambien si el valor es igual al anterior
            if (reg.getSaveTypeString() == "ONCHANGE" && lastRead.get(idSensor) != value) {
              // Actualizo la ultima lectura y guardo en la BD
              lastRead.put(idSensor, value);
              saveRegistry(idSensor, value);

            } else if (reg.getSaveTypeString() == "ONTIME") {
              // Variables auxiliares, para checkear tiempo
              Long auxLong = System.currentTimeMillis() / 1000;
              int now = auxLong.intValue();
              int timeToSave = lastRead.get(idSensor) + reg.getValue();
              // Checkea si ya es tiempo para guerdar un nuevo registro
              if (now >= timeToSave) {
                // Actualizo el ultimo guardado
                lastRead.put(idSensor, now);
                saveRegistry(idSensor, value);
              }
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
  /**
   * Sends login command.
   *
   * @param capalistParam param from previous command.
   * @return is command successful.
   */
  @SuppressWarnings("unchecked")
  private boolean sendCapas(JSONArray capalistParam) {
    if (connection == null || capalistParam == null || capalistParam.isEmpty()) return false;

    JSONObject obj = new JSONObject();
    try {
      obj.put("class", "login_capas");
      obj.put("capaid", capalistParam.get(0));
      obj.put("lastconnwins", "false");
      obj.put("loginkind", "agent");
      obj.put("state", "");

      return send(obj);
    } catch (Exception e) {
      logger.error("Error login", e);
      return false;
    }
  }
Exemplo n.º 7
0
 // Removes locally-stored app(s).
 private void remove(JSONArray args) {
   try {
     local_path = "/data/data/" + ctx.getPackageName() + "/remote_app/" + args.getString(1) + "/";
     deleteDirectory(new File(local_path));
   } catch (JSONException e) {
     this.error(
         new PluginResult(
             PluginResult.Status.ERROR,
             "JSON exception during argument parsing; make sure the app ID was passed as an argument."),
         this.callback);
   }
 }
Exemplo n.º 8
0
 // Loads a locally-saved app into the WebView.
 private void load(JSONArray args) {
   try {
     local_path = "/data/data/" + ctx.getPackageName() + "/remote_app/" + args.getString(1) + "/";
     this.success(
         new PluginResult(PluginResult.Status.OK, "file://" + local_path + "index.html"),
         this.callback);
   } catch (JSONException e) {
     this.error(
         new PluginResult(
             PluginResult.Status.ERROR,
             "JSON exception during argument parsing; make sure the app ID was passed as an argument."),
         this.callback);
   }
 }
Exemplo n.º 9
0
  @RequestMapping(
      value = "/getCityApi",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCityApi(
      HttpServletRequest request,
      @RequestParam(value = "locationname") String locationname,
      ModelMap model) {

    Map<Object, Object> map = new HashMap<Object, Object>();
    JSONArray jSONArray = new JSONArray();
    try {
      String status = "active";
      List<City> cityList = cityService.getCityApi(locationname, status);
      if (cityList != null && cityList.size() > 0) {
        for (int i = 0; i < cityList.size(); i++) {
          City city = (City) cityList.get(i);
          String cityName = (String) city.getCity();
          String stateName = (String) city.getState();

          int ID = (Integer) (city.getId());
          JSONObject jSONObject = new JSONObject();

          jSONObject.put("id", ID);
          jSONObject.put("text", cityName);
          jSONArray.put(jSONObject);
        }
        utilities.setSuccessResponse(response, jSONArray.toString());
      } else {
        throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA);
      }
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
      utilities.setErrResponse(ex, response);
    }
    model.addAttribute("model", jSONArray.toString());
    return "home";
  }
Exemplo n.º 10
0
 public static JSONValue parseJSONValue(ParseState parseState) {
   if (parseState.skipWhite()) {
     char c = parseState.current();
     switch (c) {
       case '{':
         return JSONObject.parseJSON(parseState);
       case '"':
         return JSONString.parseJSON(parseState);
       case '[':
         return JSONArray.parseJSON(parseState);
       case 'n':
         return JSONNull.parseJSON(parseState);
       case 't':
       case 'f':
         return JSONBoolean.parseJSON(parseState);
       default:
         if ((c >= '0' && c <= '9') || c == '-' || c == '.' || c == 'N') // NaN ok
         return JSONNumber.parseJSON(parseState);
         break;
     }
   }
   return null;
 }
Exemplo n.º 11
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;
  }
Exemplo n.º 12
0
  public Map getUserStoryTaskMap(String timeEntryItemRef) throws Exception {
    Map taskMap = new HashMap();

    String[] objectIdArr = timeEntryItemRef.split("/");
    String objectId = objectIdArr[objectIdArr.length - 1];

    log.info("objectId=" + objectId);

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

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

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

    String responseJSON = postRallyXML(apiURL, requestJSON);

    // Bypass"%;" to avoid exception
    responseJSON = responseJSON.replace("%;", ";");
    responseJSON = responseJSON.replace("%", "");

    Map jsonMap = JsonUtil.jsonToMap(responseJSON);

    String usRef = "";
    String usName = "";
    String usFormattedId = "";
    String usPlanEstimate = "";
    String usTaskEstimateTotal = "";
    String usTaskRemainingTotal = "";
    String usState = "";
    String usOwner = "";

    Map usMap = new HashMap();

    // Get user story info
    JSONObject userstoryMap = (JSONObject) jsonMap.get("userstory");
    JSONArray userstoryArray = (JSONArray) userstoryMap.get("Results");
    if (userstoryArray == null || userstoryArray.size() == 0) {
      userstoryMap = (JSONObject) jsonMap.get("defect");
      userstoryArray = (JSONArray) userstoryMap.get("Results");
    }

    if (userstoryArray != null && userstoryArray.size() > 0) {
      JSONObject userstoryInfo = (JSONObject) userstoryArray.get(0);
      // log.info("userstoryInfo="+userstoryInfo);
      usRef = (userstoryInfo.get("_ref")).toString();
      usFormattedId = (userstoryInfo.get("FormattedID")).toString();
      usName = (userstoryInfo.get("Name")).toString();
      usState = (userstoryInfo.get("ScheduleState")).toString();

      if (userstoryInfo.get("PlanEstimate") != null)
        usPlanEstimate = (userstoryInfo.get("PlanEstimate")).toString();

      if (userstoryInfo.get("TaskEstimateTotal") != null)
        usTaskEstimateTotal = (userstoryInfo.get("TaskEstimateTotal")).toString();

      if (userstoryInfo.get("TaskRemainingTotal") != null)
        usTaskRemainingTotal = (userstoryInfo.get("TaskRemainingTotal")).toString();

      JSONObject ownerMap = (JSONObject) userstoryInfo.get("Owner");
      if (ownerMap != null) {
        usOwner = (String) ownerMap.get("_refObjectName");
        if (usOwner == null) {
          usOwner = "";
        }
      }
    }

    Map usDetailMap = new HashMap();

    usDetailMap.put("usFormattedId", usFormattedId);
    usDetailMap.put("usName", usName);
    usDetailMap.put("usPlanEstimate", usPlanEstimate);
    usDetailMap.put("usTaskEstimateTotal", usTaskEstimateTotal);
    usDetailMap.put("usTaskRemainingTotal", usTaskRemainingTotal);
    usDetailMap.put("usOwner", usOwner);
    usDetailMap.put("usState", usState);

    usMap.put(usRef, usDetailMap);

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

    String taskObjId = "";
    String taskFormattedId = "";
    String taskName = "";
    String estimate = "";
    String toDo = "";
    String taskState = "";
    String taskOwner = "";
    String projectName = "";
    String iterationName = "";
    String workProductRef = "";

    List taskList = new ArrayList();

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

      for (int i = 0; i < taskArray.size(); i++) {

        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 = "";
          }
        }

        JSONObject workProductMap = (JSONObject) taskInfo.get("WorkProduct");
        // log.info("workProductMap="+workProductMap);
        if (workProductMap != null) {
          workProductRef = (String) workProductMap.get("_ref");
          if (workProductRef == null) {
            workProductRef = "";
          }
        }

        JSONObject projectMap = (JSONObject) taskInfo.get("Project");
        // log.info("projectMap="+projectMap);
        if (projectMap != null) {
          projectName = (String) projectMap.get("_refObjectName");
          if (projectName == null) {
            projectName = "";
          }
        }

        JSONObject iterationMap = (JSONObject) taskInfo.get("Iteration");
        // log.info("iterationMap="+iterationMap);
        if (iterationMap != null) {
          iterationName = (String) iterationMap.get("_refObjectName");
          if (iterationName == null) {
            iterationName = "";
          }
        }

        taskMap.put("taskFormattedId", taskFormattedId);
        taskMap.put("taskName", taskName);
        taskMap.put("taskState", taskState);
        taskMap.put("owner", taskOwner);
        taskMap.put("taskEstimate", estimate);
        taskMap.put("taskRemaining", toDo);
        taskMap.put("projectName", projectName);
        taskMap.put("iterationName", iterationName);

        Map map = (Map) usMap.get(workProductRef);
        taskMap.put("usName", map.get("usFormattedId") + " " + map.get("usName"));

        log.info("taskMap=" + taskMap);
      } // for taskArray
    }

    return taskMap;
  }
Exemplo n.º 13
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;
  }
  /**
   * tries to parse the given json message into a query object
   *
   * @param json_file a json that fulfills the exchange format between frontend and middleware
   * @return a query object that holds the information in the json message
   */
  public static Query parse(String json_file) {

    try {
      Query query = new Query();
      Object obj = JSONValue.parse(json_file);
      // System.out.println(obj);
      JSONObject j = (JSONObject) obj;
      // System.out.println(j);
      // sources
      if (j.get("source") != null) {
        /*
        JSONArray jArray = (JSONArray)j.get("sources");
        ArrayList<String> sources = new ArrayList<String>();
        for (int i = 0; i < jArray.size(); i++){
        	sources.add(jArray.get(i).toString());
        }
        */
        if (((String) (j.get("source"))).equals("dbSNP")) {
          query.s_Source = (short) 0;
        }
        if (((String) (j.get("source"))).equals("1000GenomesProject")) {
          query.s_Source = (short) 1;
        }
      }
      // chromosome
      if (j.get("chromosome") != null) {
        if (((String) j.get("chromosome")).equals("X")) {
          query.s_Chromosome = 23;
        } else if (((String) j.get("chromosome")).equals("Y")) {
          query.s_Chromosome = 24;
        } else if (((String) j.get("chromosome")).equals("MT")) {
          query.s_Chromosome = 25;
        } else {
          query.s_Chromosome = (short) Integer.parseInt((String) j.get("chromosome"));
        }
      }
      // position
      if (j.get("intervall") != null) {
        JSONObject pos_obj = (JSONObject) j.get("intervall");
        query.i_Start = (int) (long) pos_obj.get("from");
        query.i_End = (int) (long) pos_obj.get("to");
        query.i_ZoomLevel = (int) (long) pos_obj.get("size");
      }
      // gene search
      if (j.get("search") != null) {
        query.x_Search = (String) j.get("search");
      }
      // prefix
      if (j.get("prefix") != null) {
        query.b_isPrefix = (boolean) j.get("prefix");
      } else {
        query.b_isPrefix = false;
      }
      /*
      // subintervals
      if (j.get("subintervals") != null){
      	query.subintervals = (int)(long) j.get("subintervals");
      }
      */
      // hasDetail flag
      if (j.get("hasDetail") != null) {
        query.b_hasDetail = (boolean) j.get("hasDetail");
      }
      if (j.get("filter") != null) {
        JSONObject fil_obj = (JSONObject) j.get("filter");
        if (((boolean) fil_obj.get("male")) && !((boolean) fil_obj.get("female"))) {
          query.s_Gender = (short) 0;
        } else if (!((boolean) fil_obj.get("male")) && ((boolean) fil_obj.get("female"))) {
          query.s_Gender = (short) 1;
        }
        query.i_RelFrq = (int) (long) fil_obj.get("relfrq");
        JSONArray orig_array = (JSONArray) fil_obj.get("origin");
        query.s_Country = new short[orig_array.size()];
        for (int i = 0; i < orig_array.size(); i++) {
          query.s_Country[i] = IndexController.getNumber((String) orig_array.get(i));
        }
      }
      return query;
    } catch (Exception e) {
      System.out.println("Unknown query format");
      return null;
    }

    /*
    try{
    	Query query = new Query();
    	Integer randomID = get_random_number();
    	query.queryID = randomID;
    	queryID_pool.remove(randomID);
    	Object obj = JSONValue.parse(json_file);
    	//System.out.println(obj);
    	JSONObject j = (JSONObject) obj;
    	//System.out.println(j);
    	// sources
    	if (j.get("source") != null){
    		query.source = (String)j.get("source");
    	}
    	// chromosome
    	if (j.get("chromosome") != null){
    		query.chromosome = (int) (long) j.get("chromosome");
    	}
    	// position
    	if (j.get("intervall") != null){
    		JSONObject pos_obj = (JSONObject) j.get("intervall");
    		Integer[] pos = new Integer[2];
    		pos[0] =  (int)(long)pos_obj.get("from");
    		pos[1] =  (int)(long)pos_obj.get("to");
    		query.zoom_level = (int)(long)pos_obj.get("size");
    		query.position = pos;
    	}
    	// gene search
    	if (j.get("search") != null){
    		query.search = (String) j.get("search");
    	}
    	// prefix
    	if (j.get("prefix") != null){
    		query.isPrefix = (boolean)j.get("prefix");
    	}
    	else{
    		query.isPrefix = false;
    	}

    	// hasDetail flag
    	if (j.get("hasDetail") != null){
    		query.hasDetail = (boolean) j.get("hasDetail");
    	}
    	if (j.get("filter") != null){
    		Filter fil = new Filter();
    		JSONObject fil_obj = (JSONObject)j.get("filter");
    		fil.male = (boolean)fil_obj.get("male");
    		fil.female = (boolean) fil_obj.get("female");
    		fil.relfrq = (int) (long)fil_obj.get("origin");
    		JSONArray orig_array = (JSONArray) fil_obj.get("origin");
    		String[] orig = new String[orig_array.size()];
    		for (int i = 0; i < orig_array.size(); i++){
    			orig[i] = (String)orig_array.get(i);
    		}
    		fil.origin = orig;
    		query.filter = fil;
    	}
    	return query;
    }
    catch(Exception e){
    	System.out.println("Unknown query format");
    	return null;
    }
    */
  }
  /**
   * parses an answer object into the json exchange format for an answer
   *
   * @param answer the answer object that should be translated
   * @return json string in the exchange format between frontend and middleware
   */
  public static String answerQuery(QueryAnswer answer) {
    JSONObject obj = new JSONObject();
    obj.put("source", answer.source);
    // add chromosome attribute to json answer
    obj.put("chromosome", answer.chromosome);
    JSONObject from_to = new JSONObject();
    from_to.put("from", answer.position[0]);
    from_to.put("to", answer.position[1]);
    obj.put("position", from_to);
    String response;
    if (answer.hasDetail) {
      JSONObject details = new JSONObject();
      details.put("refseq", answer.refseq);
      // create json_array for found mutations
      JSONArray mutations_array = new JSONArray();
      for (IntervalST.Mutation x : answer.mutations) {
        // json object for single mutation, that was found
        JSONObject mut = new JSONObject();

        // name of mutation, need to convert from byte array to string
        mut.put("name", new String(x.b_RefName));

        // json object for position of mutation's interval, with "to" and "from" as attributes
        JSONObject mut_pos = new JSONObject();
        mut_pos.put("from", x.i_Low);
        mut_pos.put("to", x.i_High);
        mut.put("position", mut_pos);

        // json object for metadata
        JSONObject meta = new JSONObject();

        // json object for gender
        JSONObject gender = new JSONObject();
        // -1 for no filter on gender, 0 for male and 1 for female
        if (x.s_Gender == -1) {
          gender.put("m", true);
          gender.put("w", true);
        } else if (x.s_Gender == 0) {
          gender.put("m", true);
          gender.put("w", false);
        } else if (x.s_Gender == 1) {
          gender.put("m", false);
          gender.put("w", true);
        } else {
          gender = null;
        }
        meta.put("gender", gender);

        // add country
        meta.put("origin", IndexController.getCountry(x.s_Country));

        // downloadtime
        meta.put("downloadtime", x.s_Date);

        // add metadata json object to mutation json object
        mut.put("metadata", meta);

        // add sequence of basis pairs, first need to convert integer to string
        if (answer.chromosome == 23) {
          mut.put("mutationseq", Chromosome_reader.retrieve_sequence(x.i_Low, x.i_High, "X"));
        } else if (answer.chromosome == 24) {
          mut.put("mutationseq", Chromosome_reader.retrieve_sequence(x.i_Low, x.i_High, "Y"));
        } else if (answer.chromosome == 25) {
          mut.put("mutationseq", Chromosome_reader.retrieve_sequence(x.i_Low, x.i_High, "MT"));
        } else {
          mut.put(
              "mutationseq",
              Chromosome_reader.retrieve_sequence(x.i_Low, x.i_High, answer.chromosome.toString()));
        }
        // add json object for mutation x to json array for all mutations that were found
        mutations_array.add(mut);
      }
      details.put("mutations", mutations_array);
      obj.put("details", details);
      StringWriter out = new StringWriter();
      try {
        obj.writeJSONString(out);
      } catch (IOException e) {
        e.printStackTrace();
      }
      response = out.toString();

    } else {
      obj.put("details", null);
      // function to count occurrences of mutations in subintervals
      Integer[] counts = count_mutations(answer);
      JSONArray mutation_counts = new JSONArray();
      for (int i = 0; i < counts.length; i++) {
        mutation_counts.add(counts[i]);
      }
      obj.put("graph", mutation_counts);
      StringWriter out = new StringWriter();
      try {
        obj.writeJSONString(out);
      } catch (IOException e) {
        e.printStackTrace();
      }
      response = out.toString();
    }
    if (response != null) {
      return response;
    } else {
      return "Something went wrong while creating answer";
    }
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  @SuppressWarnings("unchecked")
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json");
    response.setHeader("Cache-Control", "nocache");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    StringWriter result = new StringWriter();

    // get received JSON data from request
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String postData = "";
    if (br != null) {
      postData = br.readLine();
    }

    try {
      JSONObject json = (JSONObject) new JSONParser().parse(postData);
      JSONObject resultObj = new JSONObject();
      JSONArray list = new JSONArray();
      List<Tracking> trackingList = new ArrayList<Tracking>();

      // get the website list
      if (json.get("type").equals("websiteslist")) {
        trackingList = trackingDao.websiteList(pool);
        for (Tracking item : trackingList) {
          list.add(item.getWebsite());
        }
      }
      // render report
      else if (json.get("type").equals("submit")) {
        if (json.get("criteria").equals("date")) {
          // render repoty by date
          trackingList = trackingDao.getListByDate(pool, json.get("date").toString());
        } else if (json.get("criteria").equals("daterange")) {
          // render repoty by date range
          trackingList =
              trackingDao.getListByDateRange(
                  pool, json.get("fromdate").toString(), json.get("todate").toString());
        } else if (json.get("criteria").equals("website")) {
          // render repoty by website
          String website = (json.get("website") == null ? "" : json.get("website").toString());
          trackingList = trackingDao.getListByWebsite(pool, website);
        }

        for (Tracking item : trackingList) {
          JSONObject trackingObj = new JSONObject();
          trackingObj.put("date", item.getDate());
          trackingObj.put("website", item.getWebsite());
          trackingObj.put("visit", item.getVisit());
          list.add(trackingObj);
        }
      }
      resultObj.put("result", list);
      resultObj.writeJSONString(result);
      // finally output the json string
      out.print(result.toString());
    } catch (ParseException | SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * takes a query object and calls the appropriate sub component that answers the given query
   *
   * @param query the query that has to be answered
   * @return a string in the answer exchange format that will be sent to the frontend
   */
  public static String handleQuery(Query query) {
    // interval search
    String answer;
    if (query.x_Search == null) {
      // check if necessary fields are given
      if (query.i_Start == -1 || query.i_End == -1) {
        // query.response_format = "Wrong interval given";
        return "Wrong interval given";
      } else if (query.s_Chromosome == -1) {
        // query.response_format = "No chromosome given";
        return "No chromosome given";
      } else if (query.s_Source == -1) {
        // query.response_format = "No source given";
        return "No source given";
      }
      // correct query format
      else {
        // Send query to IndexController
        // Translation from query to intervalst.query
        // needs to be unified
        /*
        short s_SourceNo=(short)0;
        if (query.source.equals("dbSNP")) {
          				s_SourceNo = (short) 0;
          			}
          			if (query.source.equals("1000GenomesProject")){
          				s_SourceNo =(short) 1;
          			}
          			*/

        Query[] q_Query = {query};
        QueryAnswer temp_answer = indexController.answerQuery(q_Query);
        answer = answerQuery(temp_answer);

        /*
          		//	byte temp = query.chromosome.get();
          		//	byte[] b={temp};
          			//CRITICAL PART. change query format into intervallst.query . answerquery throws nullpointer
          			byte[] b=new byte[0];
          			byte[] c=new byte[0];
          			int i=query.position[0];
          			int j=query.position[1];
        IntervalST.Query intervalst_query=new IntervalST.Query(1,i,j,s_SourceNo,Integer.toString(query.chromosome).getBytes(),null,null);
        IntervalST.Query[] queries={intervalst_query};
        IntervalST.Answer x_Result=indexController.answerQuery(queries);
                    System.out.println("Length of AnswerList: "+x_Result.x_List.size());
                    if (query.hasDetail) {
                    	String sequence = Chromosome_reader.retrieve_sequence(i,j,Integer.toString(query.chromosome));
                    }
                    return query;
                    */
      }
    }
    // gene name search
    else {
      // test for prefix query
      if (query.b_isPrefix) {
        /*
        // This needs to be replaced!
        String[] genenames = GeneTranslator.completeGeneName(query.search);
        */
        String[] genenames = {"FOXP2", "FOXP4"};
        JSONObject obj = new JSONObject();
        obj.put("source", query.s_Source);
        obj.put("chromosome", query.s_Chromosome);
        JSONArray names = new JSONArray();
        for (int i = 0; i < genenames.length; i++) {
          names.add(genenames[i]);
        }
        obj.put("prefix", names);
        StringWriter out = new StringWriter();
        try {
          obj.writeJSONString(out);
        } catch (IOException e) {
          e.printStackTrace();
        }
        answer = out.toString();

      } else {
        if (query.x_Search == "getInitialSources") {
          System.out.println("getInitialSources");
          return null;
        } else {
          String[] interval = GeneTranslator.translateToIntervall(query.x_Search);
          JSONObject pos_obj = new JSONObject();
          JSONObject obj = new JSONObject();
          pos_obj.put("from", Integer.valueOf(interval[0]));
          pos_obj.put("to", Integer.valueOf(interval[1]));
          obj.put("search", query.x_Search);
          obj.put("position", pos_obj);

          StringWriter out = new StringWriter();
          try {
            obj.writeJSONString(out);
          } catch (IOException e) {
            e.printStackTrace();
          }
          answer = out.toString();
        }
      }
    }
    // queryID_pool.add(query.queryID);
    return answer;
  }
      @Override
      public void onComplete(String response, Object state) {
        try {
          Log.i(TAG, response);
          json = Util.parseJson(response);

          // photos are in the form of a json array
          child = json.getJSONArray("data");

          int total = child.length();

          // contains links to photos
          links = new ArrayList<String>(total);

          // adds link to each photo to our list after replacing the "https" from url
          // DownloadManager does not support https in gingerbread
          for (int i = 0; i < total; i++) {
            photo_json = child.getJSONObject(i);

            if (dl_high_res_pics) {
              JSONArray image_set = photo_json.getJSONArray("images");

              // highest resolution picture has the index zero in the images jsonarray
              JSONObject highest_res_pic = image_set.getJSONObject(0);
              String http_replaced =
                  highest_res_pic.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            } else {
              // source property of the json object points to the photo's link
              String http_replaced = photo_json.getString("source").replaceFirst("https", "http");
              links.add(i, http_replaced);
            }
          }

          download_photos.this.runOnUiThread(
              new Runnable() {
                public void run() {
                  //	mytask = new DownloadImageTask();
                  //	mytask.execute(links);
                  // start downloading using asynctask
                  // new DownloadImageTask().execute(links);
                  // downloadThread.setPath(path);
                  // downloadThread.setWholeTasks(links.size());
                  if (resume_file.exists()) {

                    initial_value = readProgress()[0];
                    final_value = links.size();
                    // case if the task is already completed
                    if (initial_value == final_value) {
                      completed = true;
                      resume_pause.setVisibility(View.GONE);

                      progress_download.setMax(final_value);
                      progress_download.setProgress(0); // bug in progress bar
                      progress_download.setProgress(initial_value);

                      progress_text.setText("Completed.");
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");

                    }

                    // case if some of the photos are already downloaded
                    else {
                      progress_download.setMax(links.size());
                      // progress_download.setProgress(0);	//bug in progress bar
                      progress_download.setProgress(initial_value);

                      // N.B if i= initial_value -1, then one image will be downloaded again. so to
                      // save cost we start with i = initial_value
                      for (int i = initial_value; i < links.size(); i++) {
                        mtext.setText(
                            getText(R.string.download_textview_message_1)
                                + " "
                                + path.toString()
                                + ". ");
                        // downloadThread.setRunningTask(i + 1);
                        downloadThread.enqueueDownload(
                            new DownloadTask(
                                links.get(i), path, i + 1, final_value, download_photos.this));
                      }
                    }
                  }

                  // case if the task is entirely new task
                  else {
                    for (int i = 0; i < links.size(); i++) {
                      mtext.setText(
                          getText(R.string.download_textview_message_1)
                              + " "
                              + path.toString()
                              + ". ");
                      // downloadThread.setRunningTask(i + 1);
                      downloadThread.enqueueDownload(
                          new DownloadTask(
                              links.get(i), path, i + 1, links.size(), download_photos.this));
                    }
                  }
                }
              });
        } catch (JSONException ex) {
          Log.e(TAG, "JSONEXception : " + ex.getMessage());
        }
      }