public synchronized void input(JSONObject o) throws ProtocolException, IOException {
   if (!gotHandshake) {
     if (parseHandshake(o)) {
       try {
         JSONObject successMessage =
             new JSONObject().put("message", "connect").put("status", true);
         sendMessage(successMessage);
       } catch (JSONException e) {
       }
     }
     return;
   } else if (!gotLoadout.get()) {
     parseLoadout(o);
   } else if (o.has("message")) {
     try {
       if (o.get("message").equals("action")) {
         messages.add(o);
       } else {
         throw new ProtocolException(
             "Unexpected message, got '" + o.get("message") + "' but expected 'action'");
       }
     } catch (JSONException e) {
       throw new ProtocolException("Invalid or incomplete packet: " + e.getMessage());
     }
   } else {
     try {
       throw new ProtocolException("Unexpected packet: '" + o.get("message") + "'");
     } catch (JSONException e) {
       throw new ProtocolException("Invalid or incomplete packet");
     }
   }
 }
Exemple #2
0
 @OnMessage
 public void recibir(String msg, Session session) {
   System.out.println("Se ha recibido: " + msg);
   try {
     JSONObject jso = new JSONObject(msg);
     if (jso.get("tipo").equals("identificacion")) {
       String login = jso.getString("texto");
       if (login.equals("admin")) {
         admin = new ChatUser(login, session);
       } else if (admin == null) {
         enviar(
             session,
             "NoDisponible",
             "No existe ninguna persona del soporte conectada al chat. Intentelo más tarde",
             "");
       } else {
         ChatUser chatUser = new ChatUser(login, session);
         chatUsers.put(login, chatUser);
         enviar(admin.getSession(), "nuevoChat", jso.getString("texto"), "");
       }
     } else if (jso.get("tipo").equals("mensaje") && admin != null) {
       enviar(admin.getSession(), "mensaje", jso.getString("remitente"), jso.getString("texto"));
     } else if (jso.get("tipo").equals("respuesta")) {
       ChatUser u = chatUsers.get(jso.getString("destinatario"));
       enviar(u.getSession(), "respuesta", jso.getString("remitente"), jso.getString("texto"));
     } else if (jso.get("tipo").equals("cierre") && admin != null) {
       enviar(admin.getSession(), "cierre", jso.getString("texto"), "");
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
    @Override
    protected void onPostExecute(JSONObject post) {
      try {
        JSONArray response = post.getJSONArray("results");
        JSONObject mObject = response.getJSONObject(0);

        //                String answer = post.getString();
        //                Gson gson = new Gson();
        //                TVProgram tvProgram = gson.fromJson(answer, TVProgram.class);
        //                if (tvProgram.equals(null)) {
        //                    Toast.makeText(MainActivity.this, "Error in getting Json",
        // Toast.LENGTH_LONG).show();
        //                }

        // Get the values from Json Object and set to the class
        mTvProgram.setName(mObject.get(TAG_NAME).toString().replace("\"", ""));
        mTvProgram.setChannel(mObject.get(TAG_CHANNEL).toString().replace("\"", ""));
        mTvProgram.setStartTime(mObject.get(TAG_STARTTIME).toString().replace("\"", ""));
        mTvProgram.setEndTime(mObject.get(TAG_ENDTIME).toString().replace("\"", ""));
        mTvProgram.setRating(mObject.get(TAG_RATING).toString().replace("\"", ""));
        mArrayList.add(mTvProgram);

      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
 public void testMessageWithDestroy() throws IOException, JSONException {
   StringWriter stringWriter = new StringWriter();
   PrintWriter printWriter = new PrintWriter(stringWriter);
   ProtocolMessageWriter writer = new JsonMessageWriter(printWriter);
   Display display = new Display();
   Shell shell = new Shell(display);
   Button button = new Button(shell, SWT.PUSH);
   writer.addDestroyPayload(WidgetUtil.getId(button));
   String widgetId = WidgetUtil.getId(button);
   String actual = stringWriter.getBuffer().toString();
   JSONObject message = new JSONObject(actual + "]}");
   JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   JSONObject widgetObject = widgetArray.getJSONObject(0);
   String type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_DESTROY, type);
   String actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(widgetId, actualId);
   Object payload = widgetObject.get(IProtocolConstants.WIDGETS_PAYLOAD);
   assertEquals(JSONObject.NULL, payload);
   writer.addDestroyPayload(WidgetUtil.getId(shell));
   writer.finish();
   String shellId = WidgetUtil.getId(shell);
   actual = stringWriter.getBuffer().toString();
   message = new JSONObject(actual);
   widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   widgetObject = widgetArray.getJSONObject(1);
   type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_DESTROY, type);
   actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(shellId, actualId);
   payload = widgetObject.get(IProtocolConstants.WIDGETS_PAYLOAD);
   assertEquals(JSONObject.NULL, payload);
 }
  /** {@inheritDoc} */
  @Override
  public BasicOperator deserialize(final JSONObject serializedOperator) throws JSONException {
    /*
     * instanciate the subgraphcontainer formatter, which is used for
     * subgraph execution
     */
    final SubgraphContainerFormatter serializer =
        new SubgraphContainerFormatter(this.dataset, this.operatorCreator, this.application);

    final JSONObject _serializedOperator = serializedOperator.getJSONObject("subgraph");
    final Root r = serializer.deserialize(_serializedOperator);
    /*
     * deserialize the key of the subgraph container
     */
    final String subgraphKey = (String) serializedOperator.get("key");
    Object obj = null;
    try {
      obj = JsonReader.jsonToJava(subgraphKey);
    } catch (final IOException e) {
      e.printStackTrace();
    }
    /*
     * read out the subgraphType, otherwise set default
     */
    String subgraphType = (String) serializedOperator.get("type");
    if (subgraphType == null) {
      subgraphType = SubgraphContainer.class.getName();
    }
    /*
     * create the subgraph container with the given key and executer
     */
    return this.invoke(subgraphType, r, obj, this.executer);
  }
 @Override
 public void handleMessage(Message msg) {
   if (msg.what == 0x125) {
     mProgressBar.setVisibility(View.INVISIBLE);
     try {
       JSONObject jsonObject = new JSONObject(result);
       Log.i(TAG, jsonObject.toString());
       if (jsonObject.get("code").equals("200")) {
         showToast("登陆成功");
         user =
             new User(
                 Integer.parseInt(jsonObject.getJSONObject("data").get("uid").toString()),
                 strUsername);
         changeLogState(true, user);
         turnToPerson(user);
       } else if (jsonObject.get("code").equals("402")) {
         showToast("登陆失败,密码不匹配");
       } else {
         showToast("登陆失败");
       }
     } catch (JSONException e) {
       e.printStackTrace();
       showToast("登陆失败");
     }
   }
 }
  @Override
  public void onMessage(String message) {
    System.out.println("received: " + message);
    try {
      JSONObject msg = new JSONObject(message);
      System.out.println("received data: " + msg.get("data").toString());
      JSONObject data = new JSONObject(msg.get("data").toString());
      String msgkey = msg.get("msg_uuid").toString();
      String timestamp = msg.get("timestamp").toString();

      String type = data.get("type").toString();
      String account = data.get("account").toString();
      if (type.equals("message")) {
        String content = data.get("content").toString();
        String clid = data.get("clid").toString();
        MessageModel model = new MessageModel(msgkey, content, clid, account, timestamp, "0", null);
        dbTask.getInstance().AddMessage(model);

      } else if (type.equals("answer")) {

        String qid = data.get("qid").toString();
        String answer = data.get("content").toString();
        if (dbTask.getInstance().HasTakeQuiz(qid, account, answer)) {
          dbTask.getInstance().UpdateTakeQuiz(qid, account, answer);
        } else {
          dbTask.getInstance().AddTakeQuiz(qid, account, answer);
        }
      }

    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
  /**
   * 被邀请的人 加入房间 (加入到房间)
   *
   * @param object
   * @return
   */
  public String receive(JSONObject object, String sessionID) {
    String nickname = (String) object.get("nickname");
    String mucname = (String) object.get("mucname");
    AbstractXMPPConnection conn = conn_map.get(sessionID);
    MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(conn);
    MultiUserChat multiChat = mucMgr.getMultiUserChat(mucname);
    try {
      multiChat.join(nickname);
      //
      multiChat.addMessageListener(
          new MessageListener() {
            @Override
            public void processMessage(Message message) {
              System.out.println("txt-----------" + message.toXML());

              if (getResource(message.getFrom()).equals(getName(message.getTo()))) return;

              String body = message.getBody();
              String username = getName(message.getTo());

              sess_map
                  .get(user_map.get(username))
                  .getAsyncRemote()
                  .sendText(rs.replace("${type}", "msg").replace("${msg}", body + "--helloworld"));
            }
          });
    } catch (NoResponseException | XMPPErrorException | NotConnectedException e) {
      e.printStackTrace();
    }
    return null;
  }
Exemple #9
0
  public static LocalType consume(Parser<? extends LocalType> parser, String content)
      throws JSONException {
    JSONObject json = new JSONObject(content);
    if (json.has("apiVersion")) {
      Util.log("apiVersion:" + json.get("apiVersion"));
    }

    if (json.has("data")) {
      Util.log("parse data:" + json.get("data"));
      return parser.parse((JSONObject) json.get("data"));
    } else if (json.has("error")) {
      Util.getData("parse error:" + json.get("error"));
      return parser.parse((JSONObject) json.get("error"));
    } else {
      throw new JSONException("no valueable data contained!!");
    }
    /*
    if (key.equals("error")) {

    } else {
    	Object obj = json.get(key);
    	if (obj instanceof JSONArray) {
    		return parser.parse((JSONArray)obj);
    	} else if (obj instanceof JSONObject){
    		return parser.parse((JSONObject)obj);
    	} else {
    		Util.log("MQ", "obj:"+obj);
    	}
    }
    */
  }
 private void parseData(String data) {
   try {
     JSONObject boardArrayData = new JSONObject(data);
     currentTurn = boardArrayData.getInt("turn");
     players = new LinkedList<>();
     JSONArray playersList = new JSONArray(boardArrayData.get("players_list").toString());
     for (int i = 0; i < playersList.length(); i++) {
       JSONObject obj = playersList.optJSONObject(i);
       players.add(
           new Player(
               PlayerType.values()[obj.getInt("type")],
               obj.getString("name"),
               obj.getInt("image")));
     }
     JSONArray rowArray = new JSONArray(boardArrayData.get("double_array").toString());
     JSONArray coloumArray = new JSONArray(rowArray.get(0).toString());
     int rowLength = rowArray.length();
     int coloumLength = coloumArray.length();
     arrayOfBoard = new Integer[rowLength][coloumLength];
     for (int i = 0; i < rowLength; i++) {
       coloumArray = new JSONArray(rowArray.get(i).toString());
       for (int j = 0; j < coloumArray.length(); j++) {
         arrayOfBoard[i][j] = coloumArray.getInt(j);
       }
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
Exemple #11
0
 public static NewsDetail parseNewsDetail(String jsonStr) {
   NewsDetail detail = new NewsDetail();
   String dataStr = JsonParser.parseBase(detail, jsonStr);
   JSONObject data = JSON.parseObject(dataStr);
   if (data != null) {
     for (Map.Entry<String, Object> entry : data.entrySet()) {
       if (entry.getKey().equals("title")) {
         detail.title = entry.getValue().toString();
       } else if (entry.getKey().equals("abstract")) {
         detail.abstractX = entry.getValue().toString();
       } else if (entry.getKey().equals("content")) {
         String contentStr = entry.getValue().toString();
         try {
           List<Map<String, String>> list = new LinkedList<>();
           JSONArray jsonArray = new JSONArray(contentStr);
           for (int i = 0; i < jsonArray.length(); i++) {
             org.json.JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象
             Map<String, String> map = new HashMap<>();
             if (item.get("type").equals("text")) {
               map.put("text", item.get("info").toString());
             } else if (item.get("type").equals("img")) {
               String imgStr = item.get("img").toString();
               JSONObject imgObj = JSON.parseObject(imgStr);
               for (Map.Entry<String, Object> imgItem : imgObj.entrySet()) {
                 if (imgItem.getKey().toString().startsWith("imgurl")
                     && !TextUtils.isEmpty(imgItem.getValue().toString())) {
                   JSONObject imgUrlObj = JSON.parseObject(imgItem.getValue().toString());
                   String url = imgUrlObj.getString("imgurl");
                   map.put("img", url);
                   break;
                 }
               }
             }
             list.add(map);
           }
           detail.content = list;
         } catch (Exception e) {
           e.printStackTrace();
         }
       } else if (entry.getKey().equals("url")) {
         detail.url = entry.getValue().toString();
       } else if (entry.getKey().equals("imgurl")) {
         detail.imgurl = entry.getValue().toString();
       } else if (entry.getKey().equals("imgurl1")) {
         detail.imgurl1 = entry.getValue().toString();
       } else if (entry.getKey().equals("imgurl2")) {
         detail.imgurl2 = entry.getValue().toString();
       } else if (entry.getKey().equals("pub_time")) {
         detail.time = entry.getValue().toString();
       } else if (entry.getKey().equals("atype")) {
         detail.atype = entry.getValue().toString();
       } else if (entry.getKey().equals("commentId")) {
         detail.commentId = entry.getValue().toString();
       } else {
         detail.newsAppId = entry.getValue().toString();
       }
     }
   }
   return detail;
 }
  public static int[] getTimeAndDistanceByCoord(
      double latX, double lonX, double latY, double lonY) {
    String distanceFeed = null;
    int ret[] = new int[2];
    try {
      distanceFeed = GeocodeService.getJSONDistance(latX, lonX, latY, lonY);
      JSONObject ja = new JSONObject(distanceFeed);
      if (ja.get("origin_addresses").equals("[\"Zakinthos, Greece\"]")
          || ja.get("destination_addresses").equals("[\"Zakinthos, Greece\"]")) {
        System.out.println("first if problem");
        return null;
      }
      JSONArray rows = (JSONArray) ja.get("rows");
      if (rows.length() == 0) {
        System.out.println("rows -1");
        return null;
      }
      JSONObject elmnts = (JSONObject) rows.get(0);
      JSONArray infoArr = (JSONArray) elmnts.get("elements");
      if (infoArr.length() == 0) {
        System.out.println("info arr -1");
        return null;
      }

      JSONObject infoJson = (JSONObject) infoArr.get(0);
      ret[0] = Integer.parseInt(((JSONObject) infoJson.get("distance")).get("value").toString());
      ret[1] = Integer.parseInt(((JSONObject) infoJson.get("duration")).get("value").toString());
      return ret;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Exemple #13
0
  public static void csvForm(URL url) {

    JSONTokener tokener = null;
    JSONArray jsonArray = null;
    JSONObject place = null;
    String record;
    String[] csvRecord;
    String csvFileName = "data.csv";

    try (CSVWriter writer = new CSVWriter(new FileWriter(csvFileName))) {
      tokener = new JSONTokener(url.openStream());
      jsonArray = new JSONArray(tokener);

      // Get relevant data and write it in CSV format to file
      for (int i = 0; i < jsonArray.length(); i++) {
        place = jsonArray.getJSONObject(i);
        record =
            Integer.toString(place.getInt("_id"))
                + "#"
                + place.get("name")
                + "#"
                + place.get("type")
                + "#"
                + Double.toString(place.getJSONObject("geo_position").getDouble("latitude"))
                + "#"
                + Double.toString(place.getJSONObject("geo_position").getDouble("latitude"));
        System.out.println(record);
        csvRecord = record.split("#");
        writer.writeNext(csvRecord);
      }

    } catch (IOException e) {
      System.err.println("Caught IOexception: " + e.getMessage());
    }
  }
 @Override
 public EmployeeDto getEmployeeById(String id) {
   EmployeeDto dto = null;
   input = new JSONObject();
   input.put("empId", id);
   try {
     requestData = new JSONObject();
     requestData.put("requestData", input);
     if (LOGGER.isInfoEnabled())
       LOGGER.info("Input for getEmployeeById:\n" + requestData.toString());
     headers = new HttpHeaders();
     headers.setContentType(MediaType.APPLICATION_JSON);
     entity = new HttpEntity<String>(requestData.toString(), headers);
     url = ProjectConfiguration.serviceUrl + "/getEmployeeById";
     restTemplate = new RestTemplate();
     serviceResponse = restTemplate.postForObject(url, entity, String.class);
     JSONObject jObj = new JSONObject(serviceResponse);
     String status = jObj.get("status").toString();
     if ("1".equals(status)) {
       gson = new Gson();
       LOGGER.info("\n" + jObj.get("emp").toString());
       dto = gson.fromJson(jObj.get("emp").toString(), EmployeeDto.class);
     }
   } catch (Exception e) {
     e.printStackTrace();
     LOGGER.error("Exception: " + e.getMessage());
   }
   return dto;
 }
Exemple #15
0
 @Override
 public void httpUpdate(String response) {
   if (feedDatas == null) feedDatas = new ArrayList<>();
   feedDatas.clear();
   try {
     JSONArray jsonArray = new JSONArray(response);
     for (int i = 0; i < jsonArray.length(); i++) {
       JSONObject jsonObject = (JSONObject) jsonArray.get(i);
       TaskData taskData =
           ProjectManager.getInstance().getTaskData(String.valueOf(jsonObject.get("task")));
       UserData userData =
           ProjectManager.getInstance().getUserData(String.valueOf(jsonObject.get("user")));
       String id = String.valueOf(jsonObject.get("id"));
       String summary = (String) jsonObject.get("summary");
       FeedData feedData = new FeedData(taskData, userData, id, summary);
       feedDatas.add(feedData);
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
   LinearLayout feed_layout = (LinearLayout) res_layout.findViewById(R.id.feed_layout);
   feed_layout.removeAllViews();
   for (FeedData feedData : feedDatas) {
     FeedView feedView = new FeedView(context, feedData);
     LinearLayout new_layout = feedView.getLayout(feed_layout);
     new_layout.setTag(feedView);
     feed_layout.addView(new_layout);
   }
 }
  @Test
  public void testpostReflection() throws ClientProtocolException, IOException, JSONException {
    String id = "http://machine5:4444/";
    DefaultHttpClient client = new DefaultHttpClient();

    JSONObject o = new JSONObject();
    o.put("id", id);
    o.put("getURL", "");
    o.put("getBoolean", "");
    o.put("getString", "");

    System.out.println("REQUEST " + o.toString());
    BasicHttpEntityEnclosingRequest r =
        new BasicHttpEntityEnclosingRequest("POST", status.toExternalForm());
    r.setEntity(new StringEntity(o.toString()));

    HttpResponse response = client.execute(host, r);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    JSONObject res = extractObject(response);

    Assert.assertEquals(MyCustomProxy.MY_BOOLEAN, res.get("getBoolean"));
    Assert.assertEquals(MyCustomProxy.MY_STRING, res.get("getString"));
    // url converted to string
    Assert.assertEquals(MyCustomProxy.MY_URL.toString(), res.get("getURL"));
  }
Exemple #17
0
  // Displays the users currently online in the usersOnlineWindow JTextArea
  private void showUsersOnline() throws JSONException {

    // F**k det här under. Det f*****g sög att skriva. JSONArrays är retarderade.

    for (int i = 0; i < ((JSONArray) obj.get("listOfUsernames")).length(); i++) {
      if (!((JSONArray) obj.get("listOfUsernames")).isNull(i)) {
        if (!doesArrayContain(
            arrayOfAddedUsernames, ((JSONArray) obj.get("listOfUsernames")).getString(i))) {
          usersOnlineWindow.append("\n" + ((JSONArray) obj.get("listOfUsernames")).getString(i));
          pushValueToArray(
              arrayOfAddedUsernames, ((JSONArray) obj.get("listOfUsernames")).getString(i));
        }
      }
    }

    if (!obj.getString("disconnectedUser").equals("")) {
      int offset = usersOnlineWindow.getText().indexOf(obj.getString("disconnectedUser"));

      if (offset != -1) {
        try {
          int line = usersOnlineWindow.getLineOfOffset(offset);
          int start = usersOnlineWindow.getLineStartOffset(line);
          int end = usersOnlineWindow.getLineEndOffset(line);

          usersOnlineWindow.replaceRange("", start, end);
        } catch (BadLocationException e) {
          e.printStackTrace();
        }
      }
      obj.put("disconnectedUser", "");
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuilder buffer = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
      buffer.append(line);
    }
    String data = buffer.toString();
    System.out.println(data);

    JSONObject params = new JSONObject(data);
    String email = (String) params.get("email");
    String password = (String) params.get("password");

    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds011459.mlab.com:11459/farmville");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("logindetails");

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.append("$set", new BasicDBObject().append("password", password));
    BasicDBObject searchQuery = new BasicDBObject().append("email", email);
    WriteResult result = users.update(searchQuery, newDocument);

    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");

    response.getWriter().write(result.toString());
  }
  @SuppressWarnings("rawtypes")
  public KCClassParser(String jsonStr) {
    try {
      JSONObject json = new JSONObject(jsonStr);
      mJSClzName = json.get(CLZ).toString();
      mJSMethodName = json.get(METHOD).toString();
      if (json.has(ARGS)) {
        mArgsJSON = json.getJSONObject(ARGS);
        Iterator it = mArgsJSON.keys();
        while (it.hasNext()) {
          String key = (String) it.next();
          if (key != null) {
            Object value = mArgsJSON.get(key);
            if (KCJSNull.isNull(value)) value = new KCJSNull();
            KCArg arg = null;

            if (key.equals(KCJSDefine.kJS_callbackId)) {
              arg = new KCArg(key, new KCJSCallback(value.toString()), KCJSCallback.class);
            } else {
              arg = new KCArg(key, value);
            }
            mArgList.addArg(arg);
          }
        }
      }
    } catch (JSONException e) {
      KCLog.e(e);
    }
  }
Exemple #20
0
    @Override
    protected String doInBackground(String... params) {
      String result = "";
      try {
        HttpClient httpclient = new DefaultHttpClient();
        System.out.println("Result::" + "http://www.google.com/ig/calculator?q=" + params[0]);
        HttpPost httppost = new HttpPost("http://www.google.com/ig/calculator?q=" + params[0]);
        // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
          sb.append(line);
        }
        is.close();

        String output = sb.toString();
        System.out.println("output::" + output);
        JSONObject jobj = new JSONObject(output);
        System.out.println(jobj + "arrlen::" + jobj.length());
        String foo = jobj.get("lhs").toString();
        result = jobj.get("rhs").toString();
        System.out.println(foo + "::" + result + "RESULT : -" + output + "-");
        return result;

      } catch (Exception e) {
        System.out.println("Error parsing data " + e.toString());
      }

      return result;
    }
 @JavascriptInterface
 public void onMessage(String data) {
   try {
     JSONObject json = new JSONObject(data);
     String type = (String) json.get("type");
     if (type.equals("candidate")) {
       IceCandidate candidate =
           new IceCandidate(
               (String) json.get("id"), json.getInt("label"), (String) json.get("candidate"));
       if (queuedRemoteCandidates != null) {
         queuedRemoteCandidates.add(candidate);
       } else {
         pc.addIceCandidate(candidate);
       }
     } else if (type.equals("answer") || type.equals("offer")) {
       SessionDescription sdp =
           new SessionDescription(
               SessionDescription.Type.fromCanonicalForm(type),
               preferISAC((String) json.get("sdp")));
       pc.setRemoteDescription(sdpObserver, sdp);
     } else if (type.equals("bye")) {
       logAndToast("Remote end hung up; dropping PeerConnection");
       disconnectAndExit();
     } else {
       throw new RuntimeException("Unexpected message: " + data);
     }
   } catch (JSONException e) {
     throw new RuntimeException(e);
   }
 }
Exemple #22
0
  /**
   * Description: Retrieves the available stations, saves them to a PandoraRadio member variable,
   * and returns them.
   */
  public ArrayList<Station> getStations()
      throws RPCException, IOException, HttpResponseException, Exception {
    if (!this.isUserAuthorized()) {
      throw new Exception(
          "Improper call to getStations(), " + "the user has not been logged in yet.");
    }

    JSONObject result = doCall("user.getStationList", null, false, true, null);

    // Our stations come in a JSONArray within the JSONObject
    JSONArray result_stations = result.getJSONArray("stations");
    ArrayList<Station> stations = new ArrayList<Station>();

    // Run through the stations within the array, and pick out some of the
    // properties we want.
    for (int i = 0; i < result_stations.length(); ++i) {
      JSONObject single_station = result_stations.getJSONObject(i);
      HashMap<String, Object> station_prep = new HashMap<String, Object>();
      station_prep.put("stationId", single_station.get("stationId"));
      station_prep.put("stationIdToken", single_station.get("stationToken"));
      station_prep.put("stationName", single_station.get("stationName"));
      station_prep.put("isQuickMix", single_station.get("isQuickMix"));
      stations.add(new Station(station_prep, this));
    }

    return stations;
  }
  @Test(description = TEST_DESCRIPTION)
  public void testAppPropertyRetrieval() throws Exception {
    HttpResponse response =
        appmPublisherRestClient.webAppCreate(appName, context, appVersion, trackingCode);
    JSONObject responseData = new JSONObject(response.getData());
    String uuid = responseData.getString(AppmTestConstants.ID);
    String appType = AppmTestConstants.WEB_APP;
    appmPublisherRestClient.publishWebApp(uuid);

    HttpResponse appPropertyResponse = appmPublisherRestClient.getWebAppProperty(uuid);
    JSONObject jsonObject = new JSONObject(appPropertyResponse.getData());

    // Check App Id
    String appId = (String) jsonObject.get(AppmTestConstants.ID);
    assertTrue((appId.equals(uuid) == true), "Unable to Retrieve application id.");

    // Check App Type
    String type = (String) jsonObject.get(AppmTestConstants.TYPE);
    assertTrue((type.equals(appType) == true), "Unable to Retrieve application type.");

    // Check lifecycleState
    String lifecycleState = (String) jsonObject.get(AppmTestConstants.LIFE_CYCLE_STATE);
    assertTrue(
        (lifecycleState.equalsIgnoreCase(AppmTestConstants.PUBLISHED) == true),
        "Unable to Retrieve application life cycle.");

    // Check Path attribute
    String appPropertyString = userName + "/" + appName + "/" + appVersion + "/" + appType;
    String path = (String) jsonObject.get("path");
    assertTrue(path.endsWith(appPropertyString), "Unable to Retrieve application path.");
  }
 @Override
 public void handleData(String mCmd, JSONObject json) throws JSONException {
   if (mCmd.equals(cmdVerifySignupPhone)) {
     if (json != null) {
       Log.d(TAG, json.toString());
       int status = json.getInt("status");
       if (status == 1) {
         Prefs.setPhoneNo(mPrefs, phoneCode, phoneNumber);
         Intent intent = new Intent(context, SignUpStep2Activity.class);
         startActivity(intent);
         finish();
       } else {
         try {
           String error = json.get("Error").toString();
           if (error.equals("wrong code")) {
             UIUtils.alert(this, R.string.your_verify_code_is_not_correct);
           }
         } catch (Exception e) {
           try {
             String errorCode = json.get("errorCode").toString();
             ErrorCode.showErrorAlert(this, errorCode);
           } catch (Exception e1) {
             UIUtils.alert(this, json.toString());
           }
         }
       }
     }
   }
   hideLoading();
 }
  @Test
  public void writeJSONWithSelectedFieldsAddsSelectedValues() throws ComponentLookupException {
    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put(STATUS_KEY, "1");
    String pubmedID = "pubmed:0001";
    map.put("solved__pubmed_id", pubmedID);
    String geneID = "ABC1";
    map.put("solved__gene_id", geneID);
    String notes = "some notes about the solved case";
    map.put("solved__notes", notes);
    PatientData<String> patientData = new DictionaryPatientData<String>(DATA_NAME, map);
    doReturn(patientData).when(this.patient).getData(DATA_NAME);
    JSONObject json = new JSONObject();
    Collection<String> selectedFields = new LinkedList<>();
    selectedFields.add(STATUS_KEY);
    selectedFields.add("solved__notes");

    this.mocker.getComponentUnderTest().writeJSON(this.patient, json, selectedFields);

    JSONObject container = json.getJSONObject(DATA_NAME);
    Assert.assertEquals(2, container.length());
    Assert.assertEquals(STATUS_SOLVED, container.get("status"));
    Assert.assertEquals(notes, container.get("notes"));
    Assert.assertFalse(container.has("pubmed_id"));
    Assert.assertFalse(container.has("gene"));
  }
Exemple #26
0
  private IGeometry decodeGeometry(JSONObject object) throws JSONException {
    IGeometry geom = null;
    LineString[] lineStrings;
    if (object.get("type").equals("MultiLineString")) {
      JSONArray coordinates = object.getJSONArray("coordinates");
      int size = coordinates.length();
      lineStrings = new LineString[size];
      LineString l;
      for (int i = 0; i < size; i++) {
        JSONArray lineStrCoord = coordinates.getJSONArray(i);
        double[][] coords = this.decodeLineStringCoords(lineStrCoord);
        l = new LineString(coords[0], coords[1]);
        lineStrings[i] = l;
      }

      geom = new MultiLineString(lineStrings);
    } else if (object.get("type").equals("LineString")) {
      JSONArray coordinates = object.getJSONArray("coordinates");
      double[][] coords = this.decodeLineStringCoords(coordinates);
      geom = new LineString(coords[0], coords[1]);
    } else if (object.get("type").equals("Point")) {
      JSONArray coordinates = object.getJSONArray("coordinates");
      geom = new Point(coordinates.getDouble(0), coordinates.getDouble(1));
    } else if (object.get("type").equals("Polygon")) {
      JSONArray coordinates = object.getJSONArray("coordinates");
      double[][] coords = this.decodeLineStringCoords(coordinates);
      geom = new Polygon(coords[0], coords[1]);
    }

    return geom;
  }
  @Override
  protected void onPostExecute(String result) {
    super.onPostExecute(result);
    try {
      JSONObject jsonObject = new JSONObject(result);
      JSONArray jsonArray = new JSONArray();
      Iterator iterator = jsonObject.keys();

      while (iterator.hasNext()) {
        String key = (String) iterator.next();
        if (key != "") {
          jsonArray.put(jsonObject.get(key));
          MyCurrencyObject object = new MyCurrencyObject();
          object.setNameId(key);
          object.setFullCountryName(jsonObject.get(key).toString());
          MyCurrencyObjArray.addCurrencyObj(object);
        }
      }
      MainActivity.countriesList.clear();
      for (int i = 0; i < jsonArray.length(); i++) {
        MainActivity.countriesList.add(jsonArray.get(i).toString());
      }
      complete.asyncComplete1(true);
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
 protected void onPostExecute(String result) {
   try {
     JSONObject jsonObject = new JSONObject(result);
     JSONArray fileArray;
     Object status = jsonObject.get("estado");
     Object message = jsonObject.get("mensaje");
     if (status.equals("ok")) {
       Toast.makeText(getApplicationContext(), message.toString(), Toast.LENGTH_LONG).show();
       Log.i("Search", message.toString());
       Utility.appendToInfoLog("Search", message.toString());
       Log.d("Search", jsonObject.toString());
       Utility.appendToDebugLog("Search", jsonObject.toString());
       if (jsonObject.has("archivos")) {
         fileArray = jsonObject.getJSONArray("archivos");
         for (int i = 0; i < fileArray.length(); i++) {
           String filePath = fileArray.getString(i);
           String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
           filesList.add(fileName);
         }
       } else {
         filesList.add("No results for your search");
       }
       ArrayAdapter<String> files =
           new ArrayAdapter<>(getApplicationContext(), R.layout.list_item, filesList);
       lv.setAdapter(files);
     } else {
       Toast.makeText(getApplicationContext(), message.toString(), Toast.LENGTH_LONG).show();
       Log.e("Search", message.toString());
       Utility.appendToErrorLog("Search", message.toString());
     }
   } catch (Exception e) {
     Log.e("Search", e.getLocalizedMessage());
     Utility.appendToErrorLog("Search", e.getLocalizedMessage());
   }
 }
  @Test
  public void testAString() throws Exception {
    FileLoggerMock mockFileLogger = setFileLoggerInstanceField(activity);
    LogPersister.setContext(activity);
    LogPersister.setLogLevel(LEVEL.DEBUG);
    Logger logger = Logger.getLogger("package");
    LogPersister.setAnalyticsCapture(true);

    logger.analytics("message", null);

    waitForNotify(logger);

    JSONArray jsonArray = mockFileLogger.getAccumulatedLogCalls();
    JSONObject jsonObject = jsonArray.getJSONObject(0);

    // jsonObject should have a fixed number of key/value pairs
    assertEquals(
        "resulting jsonobject in file has wrong number of key/value pairs", 6, jsonObject.length());
    // verify the key/value pairs
    assertTrue(
        jsonObject.has(TIMESTAMP_KEY)); // don't test the value, as it may differ from current
    assertEquals("package", jsonObject.get(PACKAGE_KEY));
    // WARN
    assertEquals("ANALYTICS", jsonObject.get(LEVEL_KEY));
    assertEquals("message", jsonObject.get(MESSAGE_KEY));
    // ensure no exception is thrown by parsing the threadid value:
    assertFalse(jsonObject.getLong(THREADID_KEY) == 0);
  }
 private void parseLoadout(JSONObject o) throws ProtocolException {
   try {
     if (!(o.get("message").equals("loadout"))) {
       throw new ProtocolException("Expected 'loadout', but got '" + o.get("message") + "' key");
     }
     if (!Util.validateWeapon(o.getString("primary-weapon"))) {
       throw new ProtocolException(
           "Invalid primary weapon: '" + o.getString("primary-weapon") + "'");
     }
     if (!Util.validateWeapon(o.getString("secondary-weapon"))) {
       throw new ProtocolException(
           "Invalid secondary weapon: '" + o.getString("secondary-weapon") + "'");
     }
     if (o.getString("primary-weapon").equals(o.getString("secondary-weapon"))) {
       throw new ProtocolException("Invalid loadout: Can't have the same weapon twice.");
     }
     primaryWeapon = o.getString("primary-weapon");
     secondaryWeapon = o.getString("secondary-weapon");
     Debug.info(
         username + " selected loadout: " + primaryWeapon + " and " + secondaryWeapon + ".");
     gotLoadout.set(true);
   } catch (JSONException e) {
     throw new ProtocolException("Invalid or incomplete packet: " + e.getMessage());
   }
 }