コード例 #1
0
  /** Handles new incoming object. */
  private void handle(JSONObject incomingObject) {
    if (!incomingObject.containsKey("class")) return;

    try {
      String classField = (String) incomingObject.get("class");

      if (classField.equals("loginko")) {
        showError(null, null, "Unauthorized. Cannot login: "******"errorstring"));

        logger.error("Error login: "******"errorstring"));

        destroy();

        return;
      } else if (classField.equals("login_id_ok")) {
        SipAccountIDImpl accountID = (SipAccountIDImpl) sipProvider.getAccountID();

        boolean useSipCredentials = accountID.isClistOptionUseSipCredentials();

        String password;
        if (useSipCredentials) {
          password = SipActivator.getProtocolProviderFactory().loadPassword(accountID);
        } else {
          password = accountID.getClistOptionPassword();
        }

        if (!authorize((String) incomingObject.get("sessionid"), password))
          logger.error("Error login authorization!");

        return;
      } else if (classField.equals("login_pass_ok")) {
        if (!sendCapas((JSONArray) incomingObject.get("capalist")))
          logger.error("Error send capas!");

        return;
      } else if (classField.equals("login_capas_ok")) {
        if (!sendFeatures(
            (String) incomingObject.get("astid"), (String) incomingObject.get("xivo_userid")))
          logger.error("Problem send features get!");

        return;
      } else if (classField.equals("features")) {
        if (!getPhoneList()) logger.error("Problem send get phones!");

        return;
      } else if (classField.equals("phones")) {
        phonesRecieved(incomingObject);
        return;
      } else if (classField.equals("disconn")) {
        destroy();
        return;
      } else {
        if (logger.isTraceEnabled()) logger.trace("unhandled classField: " + incomingObject);
        return;
      }
    } catch (Throwable t) {
      logger.error("Error handling incoming object", t);
    }
  }
コード例 #2
0
  /**
   * 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;
  }
コード例 #3
0
  public void trapException(String output) throws CrowdFlowerException {

    try {
      JSONObject error = new JSONObject(output);

      if (error.has("error")) {
        throw new CrowdFlowerException(error.get("error").toString());
      }

    } catch (JSONException e) {
      // ignore
    }
  }
コード例 #4
0
ファイル: RunLoadTest.java プロジェクト: paulnguyen/cloud
  /**
   * Performs a test by sending HTTP Gets to the URL, and records the number of bytes returned. Each
   * test results are documented and displayed in standard out with the following information:
   *
   * <p>URL - The source URL of the test REQ CNT - How many times this test has run START - The
   * start time of the last test run STOP - The stop time of the last test run THREAD - The thread
   * id handling this test case RESULT - The result of the test. Either the number of bytes returned
   * or an error message.
   */
  private void doTest() {
    String result = "";
    this.reqCount++;

    // Connect and run test steps
    Date startTime = new Date();
    try {
      ClientResource client = new ClientResource(this.myURL);

      // place order
      JSONObject json = new JSONObject();
      json.put("payment", "quarter");
      json.put("action", "place-order");
      client.post(new JsonRepresentation(json), MediaType.APPLICATION_JSON);

      // Get Gumball Count
      Representation result_string = client.get();
      JSONObject json_count = new JSONObject(result_string.getText());
      result = Integer.toString((int) json_count.get("count"));
    } catch (Exception e) {
      result = e.toString();
    } finally {
      Date stopTime = new Date();
      // Print Report of Result:
      System.out.println(
          "======================================\n"
              + "URL     => "
              + this.myURL
              + "\n"
              + "REQ CNT => "
              + this.reqCount
              + "\n"
              + "START   => "
              + startTime
              + "\n"
              + "STOP    => "
              + stopTime
              + "\n"
              + "THREAD  => "
              + Thread.currentThread().getName()
              + "\n"
              + "RESULT  => "
              + result
              + "\n");
    }
  }
コード例 #5
0
ファイル: Login.java プロジェクト: Vikas-kondapalli/Shopping
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, MongoException, DuplicateKeyException,
          UnknownHostException {
    // TODO Auto-generated method stub
    doGet(request, response);

    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String uname = request.getParameter("username");
    String password = request.getParameter("password");
    String email = request.getParameter("email");
    System.out.println(uname + " " + password + " " + email);
    /*String line;
    while((line=reader.readLine())!=null){
     buffer.append(line);
    }
    String data = buffer.toString();
    System.out.println(data);
    data = "{\"p\":\"N\",\"c\":\"W\"}";*/
    // System.out.println(data);
    // JSONObject params = (JSONObject)JSON.parse(data);
    JSONObject params = new JSONObject();
    params.put("username", uname);
    params.put("password", password);
    BasicDBObject user1 = new BasicDBObject(params);
    for (Object key : params.keySet().toArray()) {
      user1.put(key.toString(), params.get(key));
    }
    // System.out.println(user1.toJson());
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds035014.mongolab.com:35014/vikas2");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("users");
    users.insert(user1);
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
  }
コード例 #6
0
  /** @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();
    }
  }
コード例 #7
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;
  }
コード例 #8
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;
  }
コード例 #9
0
  /**
   * 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;
    }
    */
  }
コード例 #10
0
  /**
   * parses received phones list and creates/resolves groups and contacts
   *
   * @param objReceived the obj with data.
   */
  private void phonesRecieved(JSONObject objReceived) {
    try {
      if (!objReceived.get("function").equals("sendlist") || !objReceived.containsKey("payload"))
        return;

      JSONObject payload = (JSONObject) objReceived.get("payload");
      /*
       * FIXME The following contains two very inefficient Map-iterating
       * loops.
       */
      Iterator iter = payload.keySet().iterator();
      List<JSONObject> phoneList = new ArrayList<JSONObject>();
      while (iter.hasNext()) {
        JSONObject obj = (JSONObject) payload.get(iter.next());
        Iterator phonesIter = obj.keySet().iterator();
        while (phonesIter.hasNext()) phoneList.add((JSONObject) obj.get(phonesIter.next()));
      }

      for (JSONObject phone : phoneList) {
        try {
          // don't handle non sip phones
          if (!((String) phone.get("tech")).equalsIgnoreCase("sip")) continue;

          String groupName = (String) phone.get("context");

          ContactGroupSipImpl parentGroup = findGroupByName(groupName);

          if (parentGroup == null) {
            parentGroup = new ContactGroupSipImpl(groupName, sipProvider);
            parentGroup.setPersistent(true);
            getRootGroup().addSubgroup(parentGroup);

            fireGroupEvent(parentGroup, ServerStoredGroupEvent.GROUP_CREATED_EVENT);
          }

          String number = (String) phone.get("number");

          Address address = sipProvider.parseAddressString(number);

          // if the contact is already in the contact list
          ContactSipImpl contact = parentOperationSet.resolveContactID(address.toString());

          if (contact == null) {
            contact = new ContactSipImpl(address, sipProvider);
            contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname"));
            contact.setResolved(true);
            parentGroup.addContact(contact);

            fireContactAdded(parentGroup, contact);
          } else {
            contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname"));
            contact.setResolved(true);

            fireContactResolved(parentGroup, contact);
          }
        } catch (Throwable t) {
          logger.error("Error parsing " + phone);
        }
      }
    } catch (Throwable t) {
      logger.error("Error init list from server", t);
    }
  }