public void ImplyContainerFactoryInterface(String str) {
    String jsonText = str;
    // String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory =
        new ContainerFactory() {
          // 匿名类
          @Override
          public Map createObjectContainer() {
            return new LinkedHashMap();
          }

          @Override
          public List creatArrayContainer() {
            return new LinkedList();
          }
        };
    try {
      // java.lang.Object parse(java.lang.String s, ContainerFactory containerFactory)
      Map json = (Map) parser.parse(jsonText, containerFactory);
      Iterator iter = json.entrySet().iterator();
      System.out.println("iterate results");
      while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        System.out.println(entry.getKey() + "=>" + entry.getValue());
      }

      System.out.println("===toJSONString()===");
      System.out.println(JSONValue.toJSONString(json));

    } catch (ParseException ex) {
      Logger.getLogger(DecodeResearch.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  public void registrarUsuario() {
    String dato = "";
    JSONParser parser = new JSONParser();
    try {
      while (true) {
        dato = dis.readUTF();
        String usuario = "";
        String contraseña = "";
        String contra = "";
        if (dato.equals("Usuario")) {
          while (true) {
            usuario = dis.readUTF();
            if (usuario != null) {
              JSONObject user = new JSONObject();
              user.put(usuario, null);
              FileWriter escribir = new FileWriter("texto.txt");
              BufferedWriter bw = new BufferedWriter(escribir);
              PrintWriter pw = new PrintWriter(bw);
              pw.write(user.toJSONString());
              pw.close();
              bw.close();
              while (true) {
                contra = dis.readUTF();
                if (contra.equals("Contraseña")) {
                  while (true) {
                    contraseña = dis.readUTF();
                    if (contraseña != null) {
                      Object obj = parser.parse(new FileReader("texto.txt"));
                      JSONObject asignaPass = (JSONObject) obj;
                      asignaPass.put(usuario, contra);
                      FileWriter escribir2 = new FileWriter("texto.txt");
                      BufferedWriter bw2 = new BufferedWriter(escribir2);
                      PrintWriter pw2 = new PrintWriter(bw2);
                      pw2.write(asignaPass.toJSONString());
                      bw2.newLine();
                      pw2.close();
                      bw2.close();
                      break;
                    }
                  }
                  break;
                }
              }
              break;
            }
          }
          break;
        }
      }
    } catch (Exception e) {

    }
  }
 public void UseInstanceOfJSONParser(String str) {
   try {
     // Faster way: Reuse instance of JSONParser
     // String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
     String s = str;
     JSONParser parser = new JSONParser();
     Object obj = parser.parse(s);
     JSONArray array = (JSONArray) obj;
     System.out.println(array.get(0));
   } catch (ParseException ex) {
     Logger.getLogger(DecodeResearch.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
 public void TryFinderClass(String str, String matchKey) {
   // String jsonText = "{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\":
   // 123}], \"third\": 789, \"id\": null}";
   String jsonText = str;
   JSONParser parser = new JSONParser();
   KeyFinder finder = new KeyFinder();
   // finder.setMatchKey("id");
   finder.setMatchKey(matchKey);
   try {
     while (!finder.isEnd()) {
       parser.parse(jsonText, finder, true);
       if (finder.isFound()) {
         finder.setFound(false);
         System.out.println(matchKey + " found:");
         System.out.println(finder.getValue());
       }
     }
   } catch (ParseException pe) {
     System.out.println(pe.getMessage());
   }
 }
Exemple #5
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) {
    }
  }
  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;
  }
  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;
  }