@Override
  public boolean handleMessage(Message msg) {
    if (msg.what == MSG_CHANGE) {
      value = tv.getText().toString();
      JSONObject o = new JSONObject();
      try {
        o.put("value", value);
        eventManager.invokeSuccessListeners(CHANGE_EVENT, o.toString());
      } catch (JSONException e) {
        Log.e(LCAT, "Error setting value: ", e);
      }
    } else if (msg.what == MSG_SETVALUE) {
      doSetValue((String) msg.obj);
    } else if (msg.what == MSG_CANCEL) {
      doSetValue((String) msg.obj);
      eventManager.invokeSuccessListeners(CANCEL_EVENT, null);
    } else if (msg.what == MSG_RETURN) {
      value = tv.getText().toString();
      JSONObject o = new JSONObject();
      try {
        o.put("value", value);
        eventManager.invokeSuccessListeners(RETURN_EVENT, o.toString());
      } catch (JSONException e) {
        Log.e(LCAT, "Error setting value: ", e);
      }
    }

    return super.handleMessage(msg);
  }
  public static String invokeServer(String serverURL, String params) throws Exception {
    try {
      JSONObject jsonParams = new JSONObject(params);
      String belongProject = XcmApplication.getInstance().gettMetaData();
      jsonParams.put("belong_project", belongProject);
      LogUtil.e("gomtel", "belong_project= " + belongProject);

      params = jsonParams.toString();
      StringEntity se = new StringEntity(params);
      HttpParams paramsw = createHttpParams();
      se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
      HttpPost post = new HttpPost(serverURL);
      post.setEntity(se);
      HttpResponse response = new DefaultHttpClient(paramsw).execute(post);
      int sCode = response.getStatusLine().getStatusCode();
      if (sCode == HttpStatus.SC_OK) {
        return EntityUtils.toString(response.getEntity());
      } else {
        JSONObject json = new JSONObject();
        json.put("resultCode", -6);
        return json.toString(); // 链接不上后台
      }
    } catch (Exception e) {
      JSONObject json = new JSONObject();
      json.put("resultCode", -6);
      return json.toString(); // 链接不上后台
    }
  }
 @Override
 protected String doInBackground(JSONObject... params) {
   HttpClient httpClient = new DefaultHttpClient();
   JSONObject json = params[0];
   try {
     HttpPost request = new HttpPost(restfulURL);
     System.out.println("JSON DATA2 : " + json.toString());
     StringEntity entity = new StringEntity(json.toString(), "UTF-8");
     entity.setContentType("application/json");
     request.setEntity(entity);
     HttpResponse response = httpClient.execute(request);
     System.out.println("Status Code : " + response.getStatusLine());
     BufferedReader rd =
         new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
     StringBuffer sb = new StringBuffer("");
     String line = "";
     String NL = System.getProperty("line.separator");
     while ((line = rd.readLine()) != null) {
       sb.append(line + NL);
     }
     rd.close();
     return sb.toString();
   } catch (Exception e) {
     System.out.println(e.getMessage());
   }
   return "";
 }
Exemple #4
0
  @Override
  public void actionPerformed(ActionEvent arg0) { // Trata os eventos onClick do panel.
    if (arg0.getActionCommand().equals("Salvar")) {
      String login = list.getSelectedValue();
      String nivel = types.get(comboBox.getSelectedItem());

      JSONObject packet = new JSONObject();
      HashMap<String, String> tmp = new HashMap<>();

      tmp.put("login", login);
      tmp.put("nivel", nivel);

      packet.put("changeNivel", tmp);

      escritor.println(packet.toString());
      escritor.flush();

    } else if (arg0.getActionCommand().equals("Voltar")) {
      next = new ListaEquipes(escritor);

      JSONObject packet = new JSONObject();
      packet.put("listarEquipes", "");

      escritor.println(packet.toString());
      escritor.flush();
    }
  }
Exemple #5
0
  private static void connectAndPlay(VideoComponent vc, String settings, String addr)
      throws UnknownHostException, IOException {
    // find this ip
    updateResource();

    Socket skt = null;
    if (addr.length() > 0) {
      Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
      while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration<InetAddress> ee = n.getInetAddresses();
        while (ee.hasMoreElements()) {
          InetAddress i = (InetAddress) ee.nextElement();
          if (!i.isLinkLocalAddress() && !i.isLoopbackAddress()) {
            pushLog("CLNT START IP:" + i.getHostAddress());
            clientLoc = i.getHostAddress();
          }
        }
      }
      serverLoc = addr;
      skt = new Socket(serverLoc, 45000);
    } else if (addr.length() == 0) {
      clientLoc = "127.0.0.1";
      serverLoc = "127.0.0.1";
      skt = new Socket("localhost", 45000);
    }

    skt.setReuseAddress(true);
    BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
    out = new PrintWriter(skt.getOutputStream(), true);

    JSONObject portNeg = new JSONObject(in.readLine());
    int port = portNeg.getInt("port");
    System.out.println("Client port: " + port);

    JSONObject json_settings = new JSONObject();
    json_settings.put("settings", attribute + " " + clientbw + " " + request);
    out.println(json_settings.toString());

    pushLog("> SYS: CNCT SUCCESS");
    startStreaming(vc, settings, port);

    pushLog("> CTRL: LISTENING FOR COMMANDS");
    Scanner s = new Scanner(System.in);
    String line;
    JSONObject json_command;
    while (true) {
      line = s.nextLine();
      json_command = new JSONObject();
      json_command.put("command", line);
      // json_command.put("bandwidth", "");
      out.println(json_command.toString());

      if (line.equals("stop")) break;
    }

    in.close();
    out.close();
    skt.close();
  }
Exemple #6
0
 @Override
 public void publishVentaDia() {
   VentaDia ventaDia = getExtractor().getVenta();
   JSONObject ventaDiaJSON = venta2JSON(ventaDia);
   Logger.getLogger(WebSocketWS.class).info("Ventas publicadas: " + ventaDiaJSON.toString());
   wsClient.send(ventaDiaJSON.toString());
 }
 /**
  * Gets the user group messages.
  *
  * @param request the request
  * @param response the response
  * @param userEntitlementsVO the user entitlements vo
  * @param model the model
  * @return the user group messages
  */
 @RequestMapping(value = "/getUserGroupMessages", method = RequestMethod.POST)
 public void getUserGroupMessages(
     HttpServletRequest request,
     HttpServletResponse response,
     @ModelAttribute ParameterVO parameterVO,
     Model model) {
   List<DiscussionQuestionVO> updatedQuestionList = null;
   try {
     // complete fetch basic objects from session
     dataAccessServiceManager.getUserGroupMessages(parameterVO);
     // updatedQuestionList = parameterVO.getQuestionsList();
     // JSONArray responseArray = new JSONArray(Arrays.asList(updatedQuestionList));
     JSONArray questionArray = parameterVO.getQuestionsArray();
     JSONObject responseObject = new JSONObject();
     response.setCharacterEncoding("UTF-8");
     response.setContentType("text/html");
     if (questionArray != null) {
       responseObject.put("questions", questionArray);
       responseObject.put("questionscount", questionArray.length());
     } else {
       responseObject.put("questionscount", "0");
     }
     System.out.println(responseObject.toString());
     response.getWriter().write(responseObject.toString());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 @Override
 public boolean log(HistorianBroadcastReceiver.LogType type, Map objectMap) {
   JSONObject object = new JSONObject(objectMap);
   SQLiteDatabase sqLiteDatabase = this.openDatabase();
   Log.d("historian log:", object.toString());
   String query =
       "INSERT INTO "
           + TABLE_NAME
           + " ("
           + KEY_HISTORIAN_TYPE
           + COMMA_SEP
           + KEY_HISTORIAN_LOG
           + ") "
           + "values"
           + " ("
           + "\'"
           + type.toString()
           + "\'"
           + COMMA_SEP
           + "\'"
           + object.toString()
           + "\'"
           + ");";
   sqLiteDatabase.execSQL(query);
   this.closeDatabase();
   return true;
 }
Exemple #9
0
 @Override
 public Response getTree(final String path) {
   if (isBadConfig()) {
     return Response.status(500).entity("Error config").build();
   } else {
     JSONObject result = new JSONObject();
     try {
       JSONArray array = new JSONArray();
       recursiveRoute(
           "",
           new StringBuilder("https://api.dropboxapi.com/1/metadata/auto/")
               .append(path)
               .append("?access_token=")
               .append(this.m_token)
               .toString(),
           array);
       result.put("files", array);
     } catch (Exception e) {
       JSONObject err = new JSONObject();
       err.put("err", "Unable to parse json ");
       return Response.status(500).entity(err.toString()).build();
     }
     return Response.status(200).entity(result.toString()).build();
   }
 }
 @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();
 }
 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());
   }
 }
Exemple #12
0
  /**
   * 保存google事件
   *
   * @param event
   * @param cid
   * @throws Exception
   */
  public FDEvent saveGoogleEvent(FDEvent event, FDCalendar cal) throws Exception {
    Map<String, String> params = new HashMap<String, String>();
    //		params.put("cid", cal.getId());
    //		params.put("cid", event.getCalendarId());
    //		params.put("type", "1"	);
    //		FDPrintln.print("save google event :"+event);
    //		JSONObject obj =event.toJsonObjByGoogle();
    //		params.put("text", obj.toString()	);

    params.put("method", "addEvent");
    params.put("accountId", cal.getGoogleAccountId());
    params.put("calendarId", event.getCalendarId());
    FDPrintln.print("save google event :" + event);
    JSONObject obj = event.toJsonObjByGoogle();
    params.put("params", obj.toString());
    FDPrintln.print("saveGoogleEvent params  " + obj.toString());
    FDEvent receiveEvent = null;
    FDJson json = sendPOSTRequestByJson("user/Google", params);
    if (json != null) {
      if (json.getStatusCode() != 1) return null;
      receiveEvent = new FDEvent(json.getData(), cal, FDCalendarAccount.TYPE_GOOGLE);
      receiveEvent.setBackground(cal.getBackgroundColor());
      receiveEvent.setAccount(cal.getId());
    }
    return receiveEvent;
  }
  public void checkuser() {

    Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
    String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
    String personName = currentPerson.getDisplayName();

    try {

      long timeInMillis = System.currentTimeMillis();

      final String PhoneModel = android.os.Build.MODEL;
      JSONObject userData = new JSONObject();
      userData.put("phoneModel", PhoneModel);
      userData.put("username", personName);
      userData.put("email", email);
      Log.d(TAG, userData.toString());
      String response = CommonFunctions.sendRequestToServer(userData.toString(), "login");
      if (response.contains("SUCCESS") || response.contains("ALREADY")) {
        Log.d("testing", response);
        String userid = response.subSequence(13, 17).toString();
        // Log.d("testing", userid);
        saveSharedString("USERID", userid);
        // initialsetup();
        // SensingController.unregisterAlarm(getApplicationContext());
      }

    } catch (Exception e) {
      Log.e(TAG, e.toString());
    }
  }
 private String creatPostParam(String[] baseNames) {
   String postParame = null;
   try {
     JSONObject object = new JSONObject();
     object.put("action", "GetChannelsByNames");
     JSONObject developer = new JSONObject();
     developer.put("apikey", "HZP9DZMA");
     developer.put("secretkey", "197d2dc3226786eb2377995f8c58e1df");
     object.put("developer", developer);
     JSONObject device = new JSONObject();
     device.put("dnum", "123456");
     object.put("device", device);
     JSONObject user = new JSONObject();
     user.put("userid", "123456");
     object.put("user", user);
     JSONObject param = new JSONObject();
     JSONArray names = new JSONArray();
     for (String baseName : baseNames) {
       names.put(baseName);
     }
     param.put("names", names);
     object.put("param", param);
     postParame = object.toString();
     Log.i(TAG, "LocalChannelUtil>>creatPostParam>>PostString =" + object.toString());
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return postParame;
 }
Exemple #15
0
  public static JSONObject getRSAKeys(String address, boolean auto_generate) throws Exception {
    String privateKeyFilename = "resources/db/ck-" + address;

    if (!(new File(privateKeyFilename)).exists()) {
      if (!auto_generate) return null;

      // init a rsa key file for current address
      JSONObject keyMap = RSACoder.initKey();
      logger.info("Generated new keys: " + keyMap.toString());

      if (!exportTextToFile(keyMap.toString(), privateKeyFilename)) {
        logger.error("Failed to save generated RSA keys to " + privateKeyFilename);
        return null;
      }
    }
    String tmpKeyStr = Util.readTextFile(privateKeyFilename);
    if (tmpKeyStr == null) {
      logger.error("Failed to get RSA keys from " + privateKeyFilename);
      return null;
    }

    JSONObject keyMap = new JSONObject(tmpKeyStr);

    return keyMap;
  }
  public void rateStory(View view) {

    RatingBar ratingBar = (RatingBar) findViewById(R.id.rating_bar);
    int rating = (int) Math.round(ratingBar.getRating());
    System.out.println(rating);

    // Update rating if user hit like button
    try {
      // Store json object with value of user rating
      JSONObject storyRate = getStoryObj();
      storyRate.put("rating", rating);

      System.out.println(storyRate.toString());

      // Post json data with rating to server
      Utility.postJsonData(
          storyRate.toString(), getResources().getString(R.string.server_rate_story));

    } catch (Exception e) {
      getResources().getString(R.string.server_error);
      e.printStackTrace();
    }
    // Go back to main activity after sending rating
    NavUtils.navigateUpFromSameTask(this);
  }
 /**
  * 查询图书馆的整体统计信息
  *
  * @throws IOException
  */
 @RequestMapping(value = "/library/summary")
 public void summary(final HttpServletRequest request, final HttpServletResponse response)
     throws IOException {
   try {
     JSONObject result = new JSONObject();
     // 解决跨域
     String callback = request.getParameter("callback");
     int bookCount = libraryService.getBookCount();
     int libraryCount = libraryService.getLibraryCount();
     int userCount = libraryService.getUserCount();
     result.put(Constants.STATUS, 1);
     result.put(Constants.MSG, "【查询成功】有料哦!");
     result.put("bookCount", bookCount);
     result.put("bookCount", libraryCount);
     result.put("bookCount", userCount);
     getJson(request, response, callback, result.toString());
     return;
   } catch (Exception e) {
     logger.error("图书馆统计信息查询异常 " + e);
     String callback = request.getParameter("callback");
     JSONObject result = new JSONObject();
     try {
       result.put(Constants.STATUS, -1);
       result.put(Constants.MSG, "靠,服务歇菜了!");
     } catch (JSONException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
     }
     getJson(request, response, callback, result.toString());
   }
 }
Exemple #18
0
 @Override
 protected void parserData(JSONObject response) {
   LogTool.i("登陆应答 :");
   LogTool.i(response.toString());
   android.util.Log.d("xcq", "登录返回数据: " + response.toString());
   //		String str = utils.readFile();
   try {
     //			response = new JSONObject(str);
     JSONObject obj = response.getJSONObject("result");
     String code = obj.getString("code");
     if (RESPONSE_CODE.FAIL_CODE.equals(code)) {
       ToastTool.showText(LoginAtivity.this, obj.getString("msg"));
       return;
     }
     SharedPreferenceUtil.saveUserInfo("user_name", userName, getApplicationContext());
     SharedPreferenceUtil.saveUserInfo("user_password", userPassword, getApplicationContext());
     JSONObject rsObj = obj.getJSONObject("rs");
     SysVar.getInstance(this).saveUserInfo(rsObj);
     Intent intent = new Intent(LoginAtivity.this, MainActivity.class);
     startActivity(intent);
     SysValue.is_login = true;
     this.finish();
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
  // 初始化list数据函数
  public void InitListDataForHistory(String url, JSONObject json, AjaxStatus status) {
    if (status.getCode() == AjaxStatus.NETWORK_ERROR
        && app.GetServiceData("user_Histories") == null) {
      aq.id(R.id.ProgressText).gone();
      app.MyToast(aq.getContext(), getResources().getString(R.string.networknotwork));
      return;
    }
    ObjectMapper mapper = new ObjectMapper();
    try {
      if (isLastisNext == 1) {
        m_ReturnUserPlayHistories =
            mapper.readValue(json.toString(), ReturnUserPlayHistories.class);
        app.SaveServiceData("user_Histories", json.toString());
      } else if (isLastisNext > 1) {
        m_ReturnUserPlayHistories = null;
        m_ReturnUserPlayHistories =
            mapper.readValue(json.toString(), ReturnUserPlayHistories.class);
      }
      // 创建数据源对象
      GetVideoMovies();

    } catch (JsonParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  @Test
  public void testUpdate() {

    ds.begin(ReadWrite.WRITE);
    try {
      Ontology ont = Ontology.loadOntology(ds, testOntologyName);

      JSONObject values = new JSONObject();

      OntologyInstance instance = ont.createInstance(simpleClassId, values);

      JSONObject rep = instance.getJSONRepresentation();

      assertTrue(rep.length() == 0);

      // Add DataProperty

      values.put(idChar + dataPropId, new JSONArray("[test]"));

      instance.update(values);

      rep = instance.getJSONRepresentation();

      assertTrue(rep.length() == 1);
      assertTrue(rep.toString().equals(values.toString()));

      ds.commit();
    } catch (JSONException e) {
      ds.abort();
      fail(e.getMessage());
    } finally {
      ds.end();
    }
  }
  private ServerResponse connectHTTP(String monkeyId, String encriptedKeys, JSONArray ignore_params)
      throws JSONException, IOException {

    // Create a new HttpClient and Post Header
    HttpClient httpclient = MonkeyHttpClient.newClient();
    HttpPost httppost =
        MonkeyHttpClient.newPost(
            MonkeyKitSocketService.Companion.getHttpsURL() + "/user/connect", urlUser, urlPass);

    JSONObject localJSONObject1 = new JSONObject();

    localJSONObject1.put("usk", encriptedKeys);
    localJSONObject1.put("monkey_id", monkeyId);
    localJSONObject1.put("ignore_params", ignore_params);

    JSONObject params = new JSONObject();
    params.put("data", localJSONObject1.toString());
    Log.d("connectHTTP", "Req: " + params.toString());

    JSONObject finalResult = MonkeyHttpClient.getResponse(httpclient, httppost, params.toString());
    Log.d("connectHTTP", finalResult.toString());
    finalResult = finalResult.getJSONObject("data");

    prefs.edit().putString("sdomain", finalResult.getString("sdomain")).apply();
    prefs.edit().putString("sport", finalResult.getString("sport")).apply();

    final String domain = finalResult.getString("sdomain");
    final int port = finalResult.getInt("sport");
    return new ServerResponse(monkeyId, domain, port);
  }
  /* (non-Javadoc)
   * @see com.welocally.geodb.services.util.JsonStoreLoader#loadSingle(org.json.JSONObject, int, int, java.io.StringWriter)
   */
  public void loadSingle(
      JSONObject deal, Integer count, Integer commitEvery, StringWriter sw, String endpoint)
      throws JSONException, IOException {
    logger.debug("adding document:" + deal.getString("_id"));

    URL solrUrl = new URL(endpoint);

    JSONObject doc = welocallyJSONUtils.makeIndexableDeal(deal);
    JSONObject solrCommand = new JSONObject("{\"add\": {\"doc\":" + doc.toString() + "}}");

    ByteArrayInputStream bais = new ByteArrayInputStream(solrCommand.toString().getBytes());
    BufferedReader newReader = new BufferedReader(new InputStreamReader(bais));

    postData(newReader, sw, solrUrl);

    // commit only every x docs
    if (count % commitEvery == 0) {
      logger.debug("commit");
      commit(sw, solrUrl);
      sw.flush();
      sw.close();
      sw = new StringWriter();
    }

    loadMonitor.increment();
  }
Exemple #23
0
  @Override
  public void onResponse(JSONObject response) {
    LogUtil.v("LoginListener TAG", response.toString());
    try {
      boolean stat = response.getBoolean("stat");
      if (!stat) { // 失败
        int errorcode = response.getInt("errcode"); // 获取失败码
        NetFailToast.show(errorcode); // 提示失败原因

        if (context instanceof LoginActivity) { // 回调activity
          Message mess = new Message();
          mess.what = 300;
          messhandler.sendMessage(mess);
        }
      } else { // 成功
        Gson gson = new Gson();
        ResponseLogin reslogin = gson.fromJson(response.toString(), ResponseLogin.class);

        ((WelcomeActivity) context).onFinishLogin(reslogin);
      }
      /** 释放引用 */
      messhandler = null;
      context = null;
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Exemple #24
0
 public String Key2Json(
     String marddk, String value1, String value2, String value3, String[] update) {
   String jsonresult = "";
   JSONObject object = new JSONObject();
   try {
     object.put("mark", marddk);
     object.put("account", value1);
     JSONObject info = new JSONObject();
     info.put("name", value2);
     info.put("head", value3);
     object.put("info", info);
     JSONArray array = new JSONArray();
     if (!update[0].equals("no")) {
       for (int i = 0; i < update.length; i++) {
         Log.e("aaaaaa", update[i]);
         String[] info1 = update[i].split("#");
         JSONObject jsoninfo = new JSONObject();
         jsoninfo.put("type", info1[0]);
         jsoninfo.put("content", decryption(info1[1]));
         Log.e("aaaaaa", jsoninfo.toString() + "----------" + i);
         array.put(i, jsoninfo);
       }
     }
     object.put("update", array);
     jsonresult = object.toString();
     Log.e("------", jsonresult);
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return jsonresult + "\r\n";
 }
  public String getUserFollowers() {
    OAuthRequest request = new OAuthRequest(Verb.GET, GET_FOLLOWERS_URL);
    this.service.signRequest(twToken.getAccessToken(), request);
    Response response = request.send();
    JSONObject res = null;
    JSONObject followers = new JSONObject();
    JSONArray followersList = new JSONArray();
    try {
      res = new JSONObject(response.getBody());
      JSONArray followersIDList = res.getJSONArray("ids");

      JSONObject other = null;

      for (int i = 0; i < followersIDList.length(); i++) {
        // System.out.println(friendsIDList.get(i).toString());

        other = getOtherProfileJson(followersIDList.get(i).toString());

        // System.out.println(other);
        if (!other.toString().contains("No user matches for specified terms"))
          followersList.put(other);
        followers.put("friends", followersList);
      }
    } catch (JSONException e) {
      response.getBody();
    }

    if (res != null)
      // return res.toJSONString();
      return followers.toString();
    else return null;
  }
Exemple #26
0
  /**
   * Publish
   *
   * <p>Send a message to a channel.
   *
   * @param String channel name.
   * @param JSONObject message.
   * @return boolean false on fail.
   */
  public JSONArray publish(String channel, JSONObject message) {
    // Generate String to Sign
    String signature = "0";
    if (this.SECRET_KEY.length() > 0) {
      StringBuilder string_to_sign = new StringBuilder();
      string_to_sign
          .append(this.PUBLISH_KEY)
          .append('/')
          .append(this.SUBSCRIBE_KEY)
          .append('/')
          .append(this.SECRET_KEY)
          .append('/')
          .append(channel)
          .append('/')
          .append(message.toString());

      // Sign Message
      signature = md5(string_to_sign.toString());
    }

    // Build URL
    List<String> url = new ArrayList<String>();
    url.add("publish");
    url.add(this.PUBLISH_KEY);
    url.add(this.SUBSCRIBE_KEY);
    url.add(signature);
    url.add(channel);
    url.add("0");
    url.add(message.toString());

    // Return JSONArray
    return _request(url);
  }
  @Test
  public void testCopyFileOverwrite() throws Exception {
    String directoryPath = "/testCopyFile/directory/path" + System.currentTimeMillis();
    String sourcePath = directoryPath + "/source.txt";
    String destName = "destination.txt";
    String destPath = directoryPath + "/" + destName;
    createDirectory(directoryPath);
    createFile(sourcePath, "This is the contents");
    createFile(destPath, "Original file");

    // with no-overwrite, copy should fail
    JSONObject requestObject = new JSONObject();
    addSourceLocation(requestObject, sourcePath);
    WebRequest request =
        getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy,no-overwrite");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, response.getResponseCode());

    // now omit no-overwrite and copy should succeed and return 200 instead of 201
    request = getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject responseObject = new JSONObject(response.getText());
    checkFileMetadata(responseObject, destName, null, null, null, null, null, null, null);
    assertTrue(checkFileExists(sourcePath));
    assertTrue(checkFileExists(destPath));
  }
    public boolean waitForStartGame() {
      try {
        socket = SocketSingleton.getInstance();
        Thread.sleep(1000);
        Log.d("Abriendo", "ABRIENDOOOOOOOOOOO");
        JSONObject request = new JSONObject();
        request.put("tipo_mensaje", "1");
        // Thread.sleep(200000);
        String responseString = socket.enviarMensaje(request.toString(2));
        Log.d("PRegunta 2", request.toString(2));
        Log.d("RESPUETA 2", responseString);
        JSONObject response = new JSONObject(responseString);
        String estado_juego = response.getString(Player.INICIO_JUEGO_TAG);
        Log.d("Abriendo", "RESPUESTAAAAA");
        if (estado_juego.equals(Player.ESTADO_OK)) {
          return true;
        }
        return false;

      } catch (JSONException e) {
        e.printStackTrace();
        Log.d("EXCEPCIONNNN", "XXXXXXXXXXXXXXXXXXXX");
        return false;
      } catch (Exception e) {
        e.printStackTrace();
        Log.d("EXCEPCIONNNN", "XXXXXXXXXXXXXXXXXXXX");
        return false;
      }
    }
 @RequestMapping(value = "PosterLoginServlet", produces = "application/json;charset=UTF-8")
 @ResponseBody
 public String PosterLogin(HttpServletRequest req) {
   String infor = req.getParameter("sendInfor");
   String postername = "";
   String password = "";
   System.out.println(infor);
   JSONObject json;
   try {
     json = new JSONObject(infor);
     postername = json.getString("postername");
     password = json.getString("password");
   } catch (JSONException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   Map<String, Object> posterinfo = new HashMap<String, Object>();
   posterinfo = us.PosterLogin(postername, password);
   if (posterinfo != null && !posterinfo.toString().equals("[]")) {
     JSONObject jsonres = new JSONObject(posterinfo);
     System.out.println(jsonres.toString());
     return encodeUTF_8.encodeStr(jsonres.toString());
   } else {
     return "Failed to Login!";
   }
 }
  @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"));
  }