/** The logic that runs in separate thread. Dispatching responses. */
  public void run() {
    if (connection == null) {
      logger.error("No connection.");
      return;
    }

    try {
      connectionReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      if (!connectionReader.readLine().contains("XiVO")) {
        logger.error("Error xivo with server!");
        destroy();
        return;
      }

      String line;
      while ((line = connectionReader.readLine()) != null || !stopped) {
        try {
          if (logger.isTraceEnabled()) logger.trace("Read from server:" + line);

          handle((JSONObject) JSONValue.parseWithException(line));
        } catch (Throwable ex) {
          logger.error("Error parsing object:" + line, ex);
        }
      }
    } catch (IOException ex) {
      destroy();
    }
  }
Exemple #2
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;
 }
  /**
   * Parses the given http response.
   *
   * @param response the http response to parse
   * @return the new account
   */
  private NewAccount parseHttpResponse(String response) {
    NewAccount newAccount = null;
    try {
      JSONObject jsonObject = (JSONObject) JSONValue.parseWithException(response);
      boolean isSuccess = (Boolean) jsonObject.get("success");

      if (isSuccess) {
        newAccount =
            new NewAccount(
                (String) jsonObject.get("sip_address"),
                passField.getPassword(),
                null,
                (String) jsonObject.get("outbound_proxy"));

        String xcapRoot = (String) jsonObject.get("xcap_root");

        // as sip2sip adds @sip2sip.info at the end of the
        // xcap_uri but doesn't report it in resullt after
        // creating account, we add it
        String domain = null;
        int delimIndex = newAccount.getUserName().indexOf("@");
        if (delimIndex != -1) {
          domain = newAccount.getUserName().substring(delimIndex);
        }
        if (domain != null) {
          if (xcapRoot.endsWith("/"))
            xcapRoot = xcapRoot.substring(0, xcapRoot.length() - 1) + domain;
          else xcapRoot += domain;
        }

        newAccount.setXcapRoot(xcapRoot);
      } else {
        showErrorMessage((String) jsonObject.get("error_message"));
      }
    } catch (Throwable e1) {
      if (logger.isInfoEnabled()) logger.info("Failed Json parsing.", e1);
    }

    return newAccount;
  }
  // public List getUserStoryList(String sessionId,String iterationId,ServletOutputStream out) {
  public List getUserStoryList(String sessionId, String iterationId, PrintWriter out) {

    List<Map> list = new ArrayList<Map>();

    statusMap.put(sessionId, "0");

    try {

      String apiURL =
          rallyApiHost
              + "/hierarchicalrequirement?"
              + "query=(Iteration%20=%20"
              + rallyApiHost
              + "/iteration/"
              + iterationId
              + ")&fetch=true&start=1&pagesize=100";

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

      String responseXML = getRallyXML(apiURL);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      int totalSteps = xlist.size() + 1;
      int currentStep = 0;

      List taskRefLink = new ArrayList();

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {
        double totalTimeSpent = 0.0D;

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String planEstimate = item.getChildText("PlanEstimate");
        String formattedId = item.getChildText("FormattedID");

        String taskActualTotal = item.getChildText("TaskActualTotal");
        String taskEstimateTotal = item.getChildText("TaskEstimateTotal");
        String taskRemainingTotal = item.getChildText("TaskRemainingTotal");
        String scheduleState = item.getChildText("ScheduleState");

        Element ownerElement = item.getChild("Owner");

        String owner = "";
        String ownerRef = "";

        if (ownerElement != null) {
          owner = ownerElement.getAttributeValue("refObjectName");
        }

        Element taskElements = item.getChild("Tasks");
        // List taskElementList=taskElements.getContent();
        List taskElementList = taskElements.getChildren();

        List taskList = new ArrayList();

        log.info("taskElements.getChildren=" + taskElements);
        log.info("taskList=" + taskElementList);

        for (int i = 0; i < taskElementList.size(); i++) {
          Element taskElement = (Element) taskElementList.get(i);

          String taskRef = taskElement.getAttributeValue("ref");

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

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

          // Map taskMap=getTaskMap(taskRef);
          Map taskMap = getTaskMapBatch(objectId);

          double taskTimeSpentTotal =
              Double.parseDouble((String) taskMap.get("taskTimeSpentTotal"));
          totalTimeSpent += taskTimeSpentTotal;
          taskList.add(taskMap);
        }

        map.put("type", "userstory");
        map.put("formattedId", formattedId);
        map.put("name", name);
        map.put("taskStatus", scheduleState);
        map.put("owner", owner);
        map.put("planEstimate", planEstimate);
        map.put("taskEstimateTotal", taskEstimateTotal);
        map.put("taskRemainingTotal", taskRemainingTotal);
        map.put("taskTimeSpentTotal", "" + totalTimeSpent);

        list.add(map);
        list.addAll(taskList);

        ++currentStep;
        double percentage = 100.0D * currentStep / totalSteps;
        String status = "" + Math.round(percentage);
        statusMap.put(sessionId, status);

        out.println("<script>parent.updateProcessStatus('" + status + "%')</script>" + status);
        out.flush();
        log.info("out.flush..." + status);

        // log.info("status="+status+" sessionId="+sessionId);
        // log.info("L1 statusMap="+statusMap+" "+statusMap.hashCode());

      }

      double planEstimate = 0.0D;
      double taskEstimateTotal = 0.0D;
      double taskRemainingTotal = 0.0D;
      double taskTimeSpentTotal = 0.0D;
      Map iterationMap = new HashMap();
      for (Map map : list) {
        String type = (String) map.get("type");

        String planEstimateStr = (String) map.get("planEstimate");

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

        if ("userstory".equals(type)) {

          if (planEstimateStr != null) {
            planEstimate += Double.parseDouble(planEstimateStr);
          }
          taskEstimateTotal += Double.parseDouble((String) map.get("taskEstimateTotal"));
          taskRemainingTotal += Double.parseDouble((String) map.get("taskRemainingTotal"));
          taskTimeSpentTotal += Double.parseDouble((String) map.get("taskTimeSpentTotal"));
        }
      }

      apiURL = rallyApiHost + "/iteration/" + iterationId + "?fetch=true";
      log.info("iteration apiURL=" + apiURL);
      responseXML = getRallyXML(apiURL);

      bSAX = new org.jdom.input.SAXBuilder();
      doc = bSAX.build(new StringReader(responseXML));
      root = doc.getRootElement();

      xpath = XPath.newInstance("//Iteration");
      xlist = xpath.selectNodes(root);

      String projName = "";
      String iterName = "";
      String iterState = "";

      iter = xlist.iterator();
      while (iter.hasNext()) {
        Element item = (Element) iter.next();

        iterName = item.getChildText("Name");
        iterState = item.getChildText("State");
        Element projElement = item.getChild("Project");
        projName = projElement.getAttributeValue("refObjectName");
      }

      iterationMap.put("type", "iteration");
      iterationMap.put("formattedId", "");
      iterationMap.put("name", projName + " - " + iterName);
      iterationMap.put("taskStatus", iterState);
      iterationMap.put("owner", "");

      iterationMap.put("planEstimate", "" + planEstimate);
      iterationMap.put("taskEstimateTotal", "" + taskEstimateTotal);
      iterationMap.put("taskRemainingTotal", "" + taskRemainingTotal);
      iterationMap.put("taskTimeSpentTotal", "" + taskTimeSpentTotal);

      list.add(0, iterationMap);

      statusMap.put(sessionId, "100");

      log.info("L2 statusMap=" + statusMap);

      log.info("L2 verify=" + getProcessStatus(sessionId));
      log.info("-----------");

      // String jsonData=JsonUtil.encodeObj(list);
      String jsonData = JSONValue.toJSONString(list);

      out.println("<script>parent.tableResult=" + jsonData + "</script>");
      out.println("<script>parent.showTableResult()</script>");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
 /**
  * Initializes a new <tt>String</tt> to be sent over an <tt>SctpConnection</tt> in order to notify
  * an <tt>Endpoint</tt> that the dominant speaker in this multipoint conference has changed to a
  * specific <tt>Endpoint</tt>.
  *
  * @param dominantSpeaker the dominant speaker in this multipoint conference
  * @return a new <tt>String</tt> to be sent over an <tt>SctpConnection</tt> in order to notify an
  *     <tt>Endpoint</tt> that the dominant speaker in this multipoint conference has changed to
  *     <tt>dominantSpeaker</tt>
  */
 private String createDominantSpeakerEndpointChangeEvent(Endpoint dominantSpeaker) {
   return "{\"colibriClass\":\"DominantSpeakerEndpointChangeEvent\","
       + "\"dominantSpeakerEndpoint\":\""
       + JSONValue.escape(dominantSpeaker.getID())
       + "\"}";
 }
  /**
   * 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;
    }
    */
  }