/**
   * Create a Mock wrapper
   *
   * @throws IOException
   */
  @Test
  public void testCreateMOCKWrapper() throws InterruptedException, IOException {
    String message =
        "{\"wr_type\":\"compute\",\"tenant_ext_net\":\"ext-subnet\",\"tenant_ext_router\":\"ext-router\",\"vim_type\":\"Mock\",\"vim_address\":\"http://localhost:9999\",\"username\":\"Eve\",\"pass\":\"Operator\",\"tenant\":\"operator\"}";
    String topic = "infrastructure.management.compute.add";
    BlockingQueue<ServicePlatformMessage> muxQueue =
        new LinkedBlockingQueue<ServicePlatformMessage>();
    BlockingQueue<ServicePlatformMessage> dispatcherQueue =
        new LinkedBlockingQueue<ServicePlatformMessage>();

    TestProducer producer = new TestProducer(muxQueue, this);
    ServicePlatformMessage addVimMessage =
        new ServicePlatformMessage(
            message, "application/json", topic, UUID.randomUUID().toString(), topic);
    consumer = new TestConsumer(dispatcherQueue);
    AdaptorCore core = new AdaptorCore(muxQueue, dispatcherQueue, consumer, producer, 0.05);

    core.start();

    consumer.injectMessage(addVimMessage);
    Thread.sleep(2000);
    while (output == null) {
      synchronized (mon) {
        mon.wait(1000);
      }
    }

    JSONTokener tokener = new JSONTokener(output);
    JSONObject jsonObject = (JSONObject) tokener.nextValue();
    String uuid = jsonObject.getString("uuid");
    String status = jsonObject.getString("status");
    Assert.assertTrue(status.equals("COMPLETED"));

    output = null;
    message = "{\"wr_type\":\"compute\",\"uuid\":\"" + uuid + "\"}";
    topic = "infrastructure.management.compute.remove";
    ServicePlatformMessage removeVimMessage =
        new ServicePlatformMessage(
            message, "application/json", topic, UUID.randomUUID().toString(), topic);
    consumer.injectMessage(removeVimMessage);

    while (output == null) {
      synchronized (mon) {
        mon.wait(1000);
      }
    }

    tokener = new JSONTokener(output);
    jsonObject = (JSONObject) tokener.nextValue();
    status = jsonObject.getString("status");
    Assert.assertTrue(status.equals("COMPLETED"));

    core.stop();
  }
Esempio n. 2
0
  /**
   * Construct a JSONObject from a JSONTokener.
   *
   * @param x A JSONTokener object containing the source string.
   * @throws JSONException If there is a syntax error in the source string or a duplicated key.
   */
  public JSONObject(JSONTokener x) throws JSONException {
    this();
    char c;
    String key;

    if (x.nextClean() != '{') {
      throw x.syntaxError("A JSONObject text must begin with '{'");
    }
    for (; ; ) {
      c = x.nextClean();
      switch (c) {
        case 0:
          throw x.syntaxError("A JSONObject text must end with '}'");
        case '}':
          return;
        default:
          x.back();
          key = x.nextValue().toString();
      }

      /*
       * The key is followed by ':'. We will also tolerate '=' or '=>'.
       */

      c = x.nextClean();
      if (c == '=') {
        if (x.next() != '>') {
          x.back();
        }
      } else if (c != ':') {
        throw x.syntaxError("Expected a ':' after a key");
      }
      putOnce(key, x.nextValue());

      /*
       * Pairs are separated by ','. We will also tolerate ';'.
       */

      switch (x.nextClean()) {
        case ';':
        case ',':
          if (x.nextClean() == '}') {
            return;
          }
          x.back();
          break;
        case '}':
          return;
        default:
          throw x.syntaxError("Expected a ',' or '}'");
      }
    }
  }
  // Returns either a JSONObject or JSONArray representation of the 'key' property of 'jsonObject'.
  public static Object getStringPropertyAsJSON(
      JSONObject jsonObject, String key, String nonJSONPropertyKey) throws JSONException {
    Object value = jsonObject.opt(key);
    if (value != null && value instanceof String) {
      JSONTokener tokener = new JSONTokener((String) value);
      value = tokener.nextValue();
    }

    if (value != null && !(value instanceof JSONObject || value instanceof JSONArray)) {
      if (nonJSONPropertyKey != null) {
        // Facebook sometimes gives us back a non-JSON value such as
        // literal "true" or "false" as a result.
        // If we got something like that, we present it to the caller as
        // a GraphObject with a single
        // property. We only do this if the caller wants that behavior.
        jsonObject = new JSONObject();
        jsonObject.putOpt(nonJSONPropertyKey, value);
        return jsonObject;
      } else {
        throw new FacebookException("Got an unexpected non-JSON object.");
      }
    }

    return value;
  }
Esempio n. 4
0
 /**
  * 获取 迅雷 云播的 地址
  *
  * @param url
  * @param headers
  * @param pairs
  * @return
  */
 public static ArrayList<VideoPlayUrl> getPlayUrl(
     String url, Header[] headers, NameValuePair[] pairs) {
   try {
     ArrayList<VideoPlayUrl> urls = new ArrayList<VideoPlayUrl>();
     String json = HttpUtils.getContent(url, headers, pairs);
     if (TextUtils.equals(json, null)) {
       return null;
     }
     JSONTokener jsonParser = new JSONTokener(json);
     JSONObject object = (JSONObject) jsonParser.nextValue();
     JSONObject resp = object.getJSONObject("resp");
     JSONArray array = resp.getJSONArray("vodinfo_list");
     for (int i = 0; i < array.length(); i++) {
       VideoPlayUrl playurl = new VideoPlayUrl();
       JSONObject urlobject = array.getJSONObject(i);
       playurl.playurl = urlobject.getString("vod_url");
       playurl.sharp = SharpnessEnum.getSharp(i);
       urls.add(playurl);
     }
     return urls;
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 5
0
 /**
  * Construct a JSONArray from a JSONTokener.
  *
  * @param x A JSONTokener
  * @throws JSONException If there is a syntax error.
  */
 public JSONArray(JSONTokener x) throws JSONException {
   this();
   if (x.nextClean() != '[') {
     throw x.syntaxError("A JSONArray text must start with '['");
   }
   if (x.nextClean() != ']') {
     x.back();
     for (; ; ) {
       if (x.nextClean() == ',') {
         x.back();
         this.myArrayList.add(JSONObject.NULL);
       } else {
         x.back();
         this.myArrayList.add(x.nextValue());
       }
       switch (x.nextClean()) {
         case ';':
         case ',':
           if (x.nextClean() == ']') {
             return;
           }
           x.back();
           break;
         case ']':
           return;
         default:
           throw x.syntaxError("Expected a ',' or ']'");
       }
     }
   }
 }
Esempio n. 6
0
 /**
  * 获取 用户 信息
  *
  * @param url
  * @param cookieStore
  * @return
  */
 public static XLLXUserInfo getUser(Context context, Header cookies) {
   String content = HttpUtils.getContent(USERINFO_URL, new Header[] {cookies}, null);
   if (content != null) {
     try {
       String json = content.substring(content.indexOf("{"));
       XLLXUserInfo info = new XLLXUserInfo();
       JSONTokener jsonParser = new JSONTokener(json);
       JSONObject object = (JSONObject) jsonParser.nextValue();
       info.autopay = Integer.parseInt(object.getString("autopay"));
       info.daily = Integer.parseInt(object.getString("daily"));
       info.expiredate = object.getString("expiredate");
       info.growvalue = Integer.parseInt(object.getString("growvalue"));
       info.isvip = Integer.parseInt(object.getString("isvip"));
       info.isyear = Integer.parseInt(object.getString("isvip"));
       info.level = Integer.parseInt(object.getString("level"));
       info.nickname = object.getString("nickname");
       info.usrname = object.getString("usrname");
       info.payname = object.getString("payname");
       saveUserInfo(context, info);
       return info;
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return null;
 }
Esempio n. 7
0
        @Override
        public void handleMessage(Message msg) {
          switch (msg.what) {
            case -1:
              {
                Bundle b = msg.getData();
                String data = b.getString("data");
                mlistener.onIMHttpErr(data);
                break;
              }
            case 1:
              {
                try {
                  Bundle b = msg.getData();
                  String data = b.getString("data");
                  JSONTokener jsonParser = new JSONTokener(data);
                  JSONObject result = (JSONObject) jsonParser.nextValue();
                  mlistener.onIMHttpDone(result);
                } catch (JSONException e) {

                }

                break;
              }
            default:
              break;
          }
        }
    @Override
    protected Boolean doInBackground(Void... params) {
      JSONArray mxb = new JSONArray();
      JSONObject json = new JSONObject();
      try {
        json.put("name", name.getText());
        json.put("sl", total.getText());
        json.put("jl_danwei", COUNT_TYPE[totalUnit.getSelectedItemPosition()]);
        json.put("zzl", weight.getText());
        json.put("zldanwei", UNIT[weightUnit.getSelectedItemPosition()]);
        json.put("tiji", cubage.getText());
        json.put("tjdanwei", "m³");
        json.put("baozhuang", PACK_TYPE[pack.getSelectedItemPosition()]);
        json.put("startaddr", from.getText());
        json.put("endaddr", to.getText());
        json.put("usname", contact.getText());
        json.put("phone", phone.getText());
        json.put("details", remark.getText());
        json.put("ydqx", date.getText());
        mxb.put(json);
      } catch (JSONException e) {
        e.printStackTrace();
      }

      SoapObject rpc = new SoapObject(Constant.NAMESPACE, "PhInfoEdit");
      rpc.addProperty("id", "");
      rpc.addProperty("mode", "ADD");
      rpc.addProperty("jsonMxbArrayString", mxb.toString());
      rpc.addProperty("currentUserno", SessionManager.getInstance().getUsername());
      rpc.addProperty("token", SessionManager.getInstance().getTokene());
      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
      envelope.dotNet = true;
      envelope.setOutputSoapObject(rpc);
      HttpTransportSE transport = new HttpTransportSE(Constant.SERVICE_URL);
      transport.debug = true;
      try {
        transport.call(Constant.NAMESPACE + "PhInfoEdit", envelope);
        SoapObject response = (SoapObject) envelope.bodyIn;
        if (response != null) {
          JSONTokener parser = new JSONTokener(response.getPropertyAsString("PhInfoEditResult"));
          JSONObject obj = (JSONObject) parser.nextValue();
          Log.i("suxoyo", obj.toString());
          if (obj.getBoolean("result")) {

            return true;
          } else {
            //						errMsg = json.getString("msg");
            return false;
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
        //				errMsg = e.toString();
        //				errMsg = "操作失败,请稍候重试";
      }

      return false;
    }
Esempio n. 9
0
 /**
  * Creates a new {@code JSONObject} with name/value mappings from the next object in the tokener.
  *
  * @param readFrom a tokener whose nextValue() method will yield a {@code JSONObject}.
  * @throws JSONException if the parse fails or doesn't yield a {@code JSONObject}.
  */
 public JSONObject(JSONTokener readFrom) throws JSONException {
   /*
    * Getting the parser to populate this could get tricky. Instead, just
    * parse to temporary JSONObject and then steal the data from that.
    */
   Object object = readFrom.nextValue();
   if (object instanceof JSONObject) {
     this.nameValuePairs = ((JSONObject) object).nameValuePairs;
   } else {
     throw JSON.typeMismatch(object, "JSONObject");
   }
 }
Esempio n. 10
0
 /**
  * @param url
  * @param parameter
  * @param isPost
  * @return
  * @throws IOException
  * @throws JSONException
  */
 public JSONObject getJSONObject(String url, String parameter, boolean isPost)
     throws IOException, JSONException {
   String json = getJson(url, parameter, isPost);
   if (isEffectiveJson(json)) {
     JSONTokener jsonTokener = new JSONTokener(json);
     JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
     return jsonObject;
   } else {
     Log.d(TAG, "!!error json :: " + json);
   }
   return null;
 }
Esempio n. 11
0
  public static ArrayList<VideoPlayUrl> getLXPlayUrl_2(Context context, XLLXFileInfo info) {
    ArrayList<VideoPlayUrl> urls = new ArrayList<VideoPlayUrl>();
    try {
      // BT文件夹转码没有完成或失败
      if (info.isDir || info.file_name == null || info.src_url == null) {
        return urls;
      }
      String CookieUID =
          "userid=" + XLLXBiz.getUID(context) + "; sessionid=" + XLLXBiz.getSessionid(context);
      for (int i = 2; i > 0; i--) {
        String json =
            HttpUtils.getContent(
                GET_PLAY_URL_2,
                new Header[] {
                  new BasicHeader(XLLXBiz.COOKIE, CookieUID), new BasicHeader("Referer", REFERER)
                },
                new NameValuePair[] {
                  new BasicNameValuePair("url", URLEncoder.encode(info.src_url)),
                  new BasicNameValuePair("video_name", URLEncoder.encode(info.file_name)),
                  new BasicNameValuePair("platform", i + ""),
                  new BasicNameValuePair("userid", XLLXBiz.getUID(context)),
                  new BasicNameValuePair("vip", "1"),
                  new BasicNameValuePair("sessionid", XLLXBiz.getSessionid(context)),
                  new BasicNameValuePair("cache", System.currentTimeMillis() + ""),
                  new BasicNameValuePair("from", "vlist")
                });

        Log.d(TAG, "play url 2 : json =" + json);
        JSONTokener jsonParser = new JSONTokener(json);
        JSONObject object = (JSONObject) jsonParser.nextValue();
        JSONObject resp = object.getJSONObject("resp");
        if (resp.has("src_info")) {

          JSONArray array = resp.getJSONArray("vodinfo_list");
          Log.d("", "" + array.length());
          for (int j = 0; j < array.length(); j++) {
            VideoPlayUrl playurl = new VideoPlayUrl();
            JSONObject urlobject = array.getJSONObject(j);
            playurl.playurl = urlobject.getString("vod_url");
            playurl.sharp = SharpnessEnum.getSharp(j);
            urls.add(playurl);
          }
        }
        if (urls.size() > 0) {
          return urls;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return urls;
  }
  public Message getMessage(String messageString) {
    JSONTokener parser = new JSONTokener(messageString);
    Message message = new Message();
    try {
      JSONObject json = (JSONObject) parser.nextValue();

      message.setContent(json.getString("content"));
      message.setDate(json.getString("date"));
    } catch (Exception e) {
      Log.i("error", e.toString());
    }
    return message;
  }
 /* (non-Javadoc)
  * @see com.qhad.ads.sdk.adsinterfaces.IQhVideoAd#getContent()
  */
 @Override
 public JSONObject getContent() {
   QHADLog.i("QHAD", "Get content of video ad");
   try {
     JSONTokener jsonParser = new JSONTokener(vo.adm);
     JSONObject adjson = (JSONObject) jsonParser.nextValue();
     return adjson;
   } catch (JSONException e) {
     // TODO Auto-generated catch block
     QHADLog.e(QhAdErrorCode.ADM_JSON_PARSE_ERROR, "QhVideoAd get content failed, adm.", e, vo);
   }
   return null;
 }
  public JSONObject sendAndReceive(JSONObject message) throws HttpSessionException {
    String resp = executePost(message.toString());

    try {
      JSONTokener tokener = new JSONTokener(resp);
      Object rawResponseMessage = tokener.nextValue();
      JSONObject response = (JSONObject) rawResponseMessage;

      if (response == null) {
        throw new HttpSessionException("Invalid response type");
      }
      return response;
    } catch (JSONException e) {
      throw new HttpSessionException(e.getMessage());
    }
  }
Esempio n. 15
0
  public static ArrayList<VideoPlayUrl> getLXPlayUrl_1(Context context, XLLXFileInfo info) {
    ArrayList<VideoPlayUrl> urls = new ArrayList<VideoPlayUrl>();
    try {
      if (info.isDir) { // 文件夹 没有解析播放地址
        return urls;
      }
      String CookieUID =
          "userid=" + XLLXBiz.getUID(context) + "; sessionid=" + XLLXBiz.getSessionid(context);
      String list_json =
          HttpUtils.getContent(
              GET_PLAY_URL_1,
              new Header[] {new BasicHeader(XLLXBiz.COOKIE, CookieUID)},
              new NameValuePair[] {
                new BasicNameValuePair("userid", info.userid),
                new BasicNameValuePair("gcid", info.gcid),
                new BasicNameValuePair("filename", URLEncoder.encode(info.src_url))
              });
      JSONTokener jsonParser = new JSONTokener(list_json);
      JSONObject object = (JSONObject) jsonParser.nextValue();
      JSONObject full_HD_Object = object.getJSONObject("Full_HD");
      Log.d(TAG, full_HD_Object + "");
      if (full_HD_Object.has("url") && !full_HD_Object.isNull("url")) {
        VideoPlayUrl playurl = new VideoPlayUrl();
        playurl.playurl = full_HD_Object.getString("url");
        playurl.sharp = SharpnessEnum.getSharp(3);
        urls.add(playurl);
      }

      JSONObject HD_Object = object.getJSONObject("HD");
      if (HD_Object.has("url") && !HD_Object.isNull("url")) {
        VideoPlayUrl playurl = new VideoPlayUrl();
        playurl.playurl = HD_Object.getString("url");
        playurl.sharp = SharpnessEnum.getSharp(2);
        urls.add(playurl);
      }
      JSONObject SD_Object = object.getJSONObject("SD");
      if (SD_Object.has("url") && !SD_Object.isNull("url")) {
        VideoPlayUrl playurl = new VideoPlayUrl();
        playurl.playurl = SD_Object.getString("url");
        playurl.sharp = SharpnessEnum.getSharp(0);
        urls.add(playurl);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return urls;
  }
Esempio n. 16
0
  public static List<WeiboStatus> buildWeboStatus(String json) throws JSONException {

    JSONTokener tokener = new JSONTokener(json);

    JSONObject jsonTimeline = (JSONObject) tokener.nextValue();

    JSONArray jsonStatuses = jsonTimeline.getJSONArray("statuses");

    for (int i = 0; i < jsonStatuses.length(); i++) {

      JSONObject jsonStatus = (JSONObject) jsonStatuses.getJSONObject(i);

      String text = jsonStatus.getString("text");
    }

    return null;
  }
Esempio n. 17
0
 /**
  * Construct a JSONArray from a JSONTokener.
  *
  * @param x A JSONTokener
  * @throws JSONException If there is a syntax error.
  */
 @SuppressWarnings("unchecked")
 public JSONArray(JSONTokener x) throws JSONException {
   this();
   char c = x.nextClean();
   char q;
   if (c == '[') {
     q = ']';
   } else if (c == '(') {
     q = ')';
   } else {
     throw x.syntaxError("A JSONArray text must start with '['");
   }
   if (x.nextClean() == ']') {
     return;
   }
   x.back();
   for (; ; ) {
     if (x.nextClean() == ',') {
       x.back();
       this.myArrayList.add(null);
     } else {
       x.back();
       this.myArrayList.add(x.nextValue());
     }
     c = x.nextClean();
     switch (c) {
       case ';':
       case ',':
         if (x.nextClean() == ']') {
           return;
         }
         x.back();
         break;
       case ']':
       case ')':
         if (q != c) {
           throw x.syntaxError("Expected a '" + new Character(q) + "'");
         }
         return;
       default:
         throw x.syntaxError("Expected a ',' or ']'");
     }
   }
 }
Esempio n. 18
0
  public static XLLXFileInfo[] getSubFile(Context context, XLLXFileInfo btdir) {
    String CookieUID = XLLXBiz.getUserUID(context);
    if (isNumeric(CookieUID) && CookieUID != "-") {
      CookieUID = "userid=" + CookieUID + ";";
    } else {
      CookieUID =
          "userid=" + XLLXBiz.getUID(context) + "; sessionid=" + XLLXBiz.getSessionid(context);
    }
    Log.d(TAG, "CookieUID= " + CookieUID);
    Header cookie = new BasicHeader(XLLXBiz.COOKIE, CookieUID);
    try {
      String suburl =
          "http://i.vod.xunlei.com/req_subBT/info_hash/"
              + btdir.src_url.substring(5)
              + "/req_num/30/req_offset/0";
      String btjson = HttpUtils.getContent(suburl, new Header[] {cookie}, null);
      btjson = URLDecoder.decode(btjson);
      JSONTokener btjsonParser = new JSONTokener(btjson);
      JSONObject btobject = (JSONObject) btjsonParser.nextValue();
      JSONObject btresp = btobject.getJSONObject("resp");
      JSONArray btsubfile_list = btresp.getJSONArray("subfile_list");
      XLLXFileInfo[] btFiles = new XLLXFileInfo[btsubfile_list.length()];
      for (int j = 0; j < btsubfile_list.length(); j++) {
        JSONObject btsubfile = btsubfile_list.getJSONObject(j);
        Log.d(TAG, "btsubfile = " + btsubfile);
        btFiles[j] = new XLLXFileInfo();
        btFiles[j].file_name = btsubfile.getString("name");
        btFiles[j].src_url = btdir.src_url + "/" + btsubfile.getString("index");
        btFiles[j].createTime = btdir.createTime;
        btFiles[j].duration = btsubfile.getString("duration");
        btFiles[j].filesize = btsubfile.getString("file_size");
        btFiles[j].gcid = btsubfile.getString("gcid");
        btFiles[j].userid = btdir.userid;
      }
      btdir.btFiles = btFiles;
      return btFiles;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
Esempio n. 19
0
        private void parseResult(String json_text) {
          try {
            JSONTokener jsonTokener = new JSONTokener(json_text);
            JSONObject json = (JSONObject) jsonTokener.nextValue();
            int canStatus;
            int ident = json.getInt("ident");
            switch (ident) {
              case IDENT_DEVICE_STATUS:
                int usage = json.getInt("usage");
                if (usage == CanlibRest.kvrDeviceUsage_FREE) {
                  t_logBottom.append("\nkvrDeviceUsage_FREE");
                } else if (usage == CanlibRest.kvrDeviceUsage_REMOTE) {
                  t_logBottom.append("\nkvrDeviceUsage_REMOTE");
                }
                break;
              case IDENT_INIT:
                canStatus = json.getInt("stat");
                t_logBottom.append("\n" + CanlibRest.getErrorText(canStatus));
                if (canStatus == CanlibRest.canOK) {
                  restActivityContext.setSession(json.getString("session"));
                }
                break;
              case IDENT_OPEN_CHANNEL:
                int hnd = json.getInt("hnd");
                canStatus = json.getInt("stat");
                t_logBottom.append("\n" + CanlibRest.getErrorText(canStatus));
                if (canStatus == CanlibRest.canOK) {
                  restActivityContext.setHandle(hnd);
                }
                break;

              default:
                canStatus = json.getInt("stat");
                t_logBottom.append("\n" + CanlibRest.getErrorText(canStatus));
            }
          } catch (Exception e) {
            Log.e(TAG, "Get: Failed to parse JSON:" + json_text + "\n", e);
          }
        }
  public GeoLocation geocode(String address) throws GMapsException {
    try {
      String gmurl =
          "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address="
              + URLEncoder.encode(address, GMAPS_CHARSET);

      URL url = new URL(gmurl);

      InputStream in = url.openStream();
      InputStreamReader reader = new InputStreamReader(in);

      JSONTokener tokener = new JSONTokener(reader);

      JSONObject object = (JSONObject) tokener.nextValue();
      String status = object.getString("status");
      if (status.equals("ZERO_RESULTS")) {
        return null;
      }
      if (!status.equals("OK")) {
        throw new GMapsException("Error during request: " + status);
      }

      JSONArray results = object.getJSONArray("results");
      JSONObject result = results.getJSONObject(0);
      JSONObject geometry = result.getJSONObject("geometry");
      JSONObject jsonLocation = geometry.getJSONObject("location");

      GeoLocation location =
          new GeoLocation(jsonLocation.getDouble("lat"), jsonLocation.getDouble("lng"));

      in.close();

      return location;
    } catch (IOException ex) {
      throw new GMapsException("Unexpectec I/O error", ex);
    } catch (JSONException ex) {
      throw new GMapsException("API error: invalid JSON", ex);
    }
  }
Esempio n. 21
0
 public Map<String, Object[]> parseJSONData(String jsonData) throws Exception {
   HashMap<String, Object[]> map = new HashMap<String, Object[]>();
   List<String> idList = new ArrayList<String>();
   List<String> nameList = new ArrayList<String>();
   List<String> addList = new ArrayList<String>();
   JSONTokener jsonTokener = new JSONTokener(jsonData);
   // JSONObject object = (JSONObject) jsonTokener.nextValue();
   JSONArray arr = (JSONArray) jsonTokener.nextValue();
   for (int i = 0; i < arr.length(); i++) {
     JSONObject object = arr.getJSONObject(i);
     String id = object.getString("id");
     String name = object.getString("name");
     String address = object.getString("add_line1");
     idList.add(id);
     nameList.add(name);
     addList.add(address);
     // System.out.println("SMM:CODE::"+name+" <> FOR ID="+id);
   }
   map.put("idArr", idList.toArray());
   map.put("nameArr", nameList.toArray());
   map.put("addArr", addList.toArray());
   return map;
 }
Esempio n. 22
0
 /**
  * http://i.vod.xunlei.com/subtitle/list?gcid= CB957B71B95D0C03678AACE628DCE12D1F565338
  * &cid=DDDE9CECC640BE251D5885DE2DBC013C0B1F7715 &userid=58531257&t=1377049152562 解析字幕列表
  *
  * @param gcid cid userid t
  * @return
  */
 public static ArrayList<LXSRT> getLxSrtsInfo(XLLXFileInfo info) {
   String url = "http://i.vod.xunlei.com/subtitle/list";
   String json =
       HttpUtils.getContent(
           url,
           null,
           new NameValuePair[] {
             new BasicNameValuePair("gcid", info.gcid),
             new BasicNameValuePair("cid", info.cid),
             new BasicNameValuePair("userid", info.userid),
             new BasicNameValuePair("t", System.currentTimeMillis() + "")
           });
   if (json != null) {
     System.out.println(json);
     ArrayList<LXSRT> lxList = new ArrayList<LXSRT>();
     try {
       JSONTokener jsonParser = new JSONTokener(json);
       JSONObject object = (JSONObject) jsonParser.nextValue();
       // JSONObject resp = object.getJSONObject("resp");
       JSONArray array = object.getJSONArray("sublist");
       for (int i = 0; i < array.length(); i++) {
         LXSRT lxsrt = new LXSRT();
         JSONObject lxsrtobject = array.getJSONObject(i);
         lxsrt.setSurl(lxsrtobject.getString("surl"));
         lxsrt.setSname(lxsrtobject.getString("sname"));
         lxsrt.setScid(lxsrtobject.getString("scid"));
         lxsrt.setLanguage(lxsrtobject.getString("language"));
         lxList.add(lxsrt);
       }
       Log.i("info", "字幕信息" + lxList.toString());
       return lxList;
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   return null;
 }
  public Map<String, Object[]> parseJSONData(String jsonData) throws Exception {
    HashMap<String, Object[]> map = new HashMap<String, Object[]>();
    List<String> idList = new ArrayList<String>();
    List<String> nameList = new ArrayList<String>();
    List<String> addList = new ArrayList<String>();
    docList2 = new ArrayList();
    JSONTokener jsonTokener = new JSONTokener(jsonData);
    // JSONObject object = (JSONObject) jsonTokener.nextValue();
    JSONArray arr = (JSONArray) jsonTokener.nextValue();
    for (int i = 1; i < arr.length(); i++) {
      JSONObject object = arr.getJSONObject(i);
      String id = object.getString("id");
      String name = object.getString("name");
      String address =
          (opr == DbAdapter.PRACTICE || opr == DbAdapter.HOSPITAL
              ? object.getString("add_line1")
              : "");
      idList.add(id);
      nameList.add(name);
      addList.add(address);

      if (opr == DbAdapter.DOCTOR) {
        String pracName = object.getString("prac_name");
        Long pracId = object.getLong("prac_id");
        Long cntyId = object.getLong("county_id");
        address = object.getString("add_line_1");
        addDocToList(name, pracName, address, pracId, cntyId);
        docList2.add(object);
      }
      // System.out.println("SMM:CODE::"+name);
    }
    map.put("idArr", idList.toArray());
    map.put("nameArr", nameList.toArray());
    map.put("addArr", addList.toArray());
    return map;
  }
  public void ProcessWeibo(String response, ArrayList<weibo_statuses> Datalist) {
    Log.i("时间线", "读取成功");
    try {
      JSONTokener jsonTokener = new JSONTokener(response);
      JSONObject timeline = (JSONObject) jsonTokener.nextValue();
      JSONArray statuses_array = timeline.getJSONArray("statuses");
      for (int i = 0; i < statuses_array.length(); i++) {
        JSONObject status = statuses_array.getJSONObject(i);
        weibo_statuses wStatuses = new weibo_statuses();
        wStatuses.favorited = (Boolean) status.getBoolean("favorited");
        wStatuses.text = (String) status.getString("text"); // 填充微博内容
        wStatuses.ID = Long.parseLong(status.getString("id")); // 获取该条微博的id
        wStatuses.created_at = (String) status.getString("created_at");
        // 获取微博配图,此处为了方便,不考虑多副图的情况
        JSONArray pic_urls = status.getJSONArray("pic_urls");
        if (0 != pic_urls.length()) {
          for (int j = 0; j < pic_urls.length(); j++) {
            wStatuses
                .pic_urls
                .getThumbnail_pics()
                .add(pic_urls.getJSONObject(j).getString("thumbnail_pic"));
            // 填充weibo_status里的pic_urls
          }
          // 暂时只读取微博配图的第一个
          wStatuses.bmiddle_pic_url = status.getString("bmiddle_pic");
          // wStatuses.bmiddle_pic =
          // getNetBitmap(wStatuses.bmiddle_pic_url);
          wStatuses.thumbnail_pic = getNetBitmap(wStatuses.pic_urls.getThumbnail_pics().get(0));
        }
        // getNetBitmap(status
        // .getString("thumbnail_pic"));//获取微博配图的缩略版本
        JSONObject user = status.getJSONObject("user");
        wStatuses.username = (String) user.getString("screen_name");
        wStatuses.profile_image_url = (String) user.getString("profile_image_url"); // 头像image的地址
        wStatuses.usericon = getNetBitmap(wStatuses.profile_image_url);
        JSONObject re_status = null;
        // 检查是否转发了微博
        try {
          re_status = status.getJSONObject("retweeted_status");
        } catch (Exception e) {
          // TODO: handle exception
          Log.d("调试", "没有转发微博");
        }
        if (null != re_status) // 即有转发微博
        {
          wStatuses.retweeted_status.retweeted_text =
              (String) re_status.getString("text"); // 填充转发微博内容
          wStatuses.retweeted_status.retweeted_ID =
              Long.parseLong(re_status.getString("id")); // 获取该条微博的id
          wStatuses.retweeted_status.retweeted_created_at =
              (String) re_status.getString("created_at");
          // 获取微博配图,此处为了方便,不考虑多副图的情况
          JSONArray re_pic_urls = re_status.getJSONArray("pic_urls");
          if (0 != re_pic_urls.length()) {
            for (int j = 0; j < re_pic_urls.length(); j++) {
              wStatuses
                  .re_pic_urls
                  .getretweeted_Thumbnail_pics()
                  .add(re_pic_urls.getJSONObject(j).getString("thumbnail_pic"));
              // 填充weibo_status里的pic_urls
            }
            // 暂时只读取微博配图的第一个
            wStatuses.retweeted_status.retweeted_bmiddle_pic_url =
                re_status.getString("bmiddle_pic");
            // wStatuses.bmiddle_pic =
            // getNetBitmap(wStatuses.bmiddle_pic_url);
            wStatuses.retweeted_status.retweeted_thumbnail_pic =
                getNetBitmap(wStatuses.re_pic_urls.getretweeted_Thumbnail_pics().get(0));
          }
          // getNetBitmap(status
          // .getString("thumbnail_pic"));//获取微博配图的缩略版本
          JSONObject re_user = re_status.getJSONObject("user");
          wStatuses.retweeted_status.retweeted_username = (String) re_user.getString("screen_name");
          wStatuses.retweeted_status.retweeted_profile_image_url =
              (String) re_user.getString("profile_image_url"); // 头像image的地址
          // wStatuses.retweeted_status.retweeted_usericon =
          // getNetBitmap(wStatuses.profile_image_url);
        }
        Datalist.add(wStatuses);
        // getStatuses_list().add(wStatuses);
        // Log.i("调试", "第" + i + "个用户名:"
        // + getStatuses_list().get(i).username + "	\n微博:"
        // + getStatuses_list().get(i).text);
        Log.i("调试", "第" + i + "个用户名:" + Datalist.get(i).username + "	\n微博:" + Datalist.get(i).text);
      }

      System.out.println(Datalist.size());
      Log.i("时间线", "填充完毕");
      // Intent intent = new Intent("timeline_ready");
      // mainActivity.sendready();
      setReady(true);

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 25
0
  /**
   * Test list vim API call
   *
   * @throws IOException
   */
  @Test
  public void testListVimList() throws InterruptedException, IOException {

    ArrayList<String> vimUuid = new ArrayList<String>();
    JSONTokener tokener;
    JSONObject jsonObject;
    String uuid, status;

    BlockingQueue<ServicePlatformMessage> muxQueue =
        new LinkedBlockingQueue<ServicePlatformMessage>();
    BlockingQueue<ServicePlatformMessage> dispatcherQueue =
        new LinkedBlockingQueue<ServicePlatformMessage>();

    TestProducer producer = new TestProducer(muxQueue, this);
    consumer = new TestConsumer(dispatcherQueue);
    AdaptorCore core = new AdaptorCore(muxQueue, dispatcherQueue, consumer, producer, 0.05);

    core.start();
    String topic = "infrastructure.management.compute.add";

    for (int i = 0; i < 3; i++) {
      String message =
          "{\"wr_type\":\"compute\",\"tenant_ext_net\":\"ext-subnet\",\"tenant_ext_router\":\"ext-router\",\"vim_type\":\"Mock\",\"vim_address\":\"http://vim"
              + i
              + ":9999\",\"username\":\"Eve\",\"pass\":\"Operator\",\"tenant\":\"operator\"}";
      ServicePlatformMessage addVimMessage =
          new ServicePlatformMessage(
              message, "application/json", topic, UUID.randomUUID().toString(), topic);

      consumer.injectMessage(addVimMessage);
      Thread.sleep(2000);
      while (output == null) {
        synchronized (mon) {
          mon.wait(1000);
        }
      }

      tokener = new JSONTokener(output);
      jsonObject = (JSONObject) tokener.nextValue();
      uuid = jsonObject.getString("uuid");
      status = jsonObject.getString("status");
      Assert.assertTrue(status.equals("COMPLETED"));
      vimUuid.add(uuid);
      output = null;
    }

    topic = "infrastructure.management.compute.list";
    ServicePlatformMessage listVimMessage =
        new ServicePlatformMessage(null, null, topic, UUID.randomUUID().toString(), topic);
    consumer.injectMessage(listVimMessage);

    while (output == null) {
      synchronized (mon) {
        mon.wait(1000);
      }
    }
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    VimResources[] vimList = mapper.readValue(output, VimResources[].class);
    ArrayList<String> vimArrayList = new ArrayList<String>();

    for (VimResources resource : vimList) {
      Assert.assertNotNull("Resource not set 'VIM UUID'", resource.getVimUuid());
      Assert.assertNotNull("Resource not set 'tot_cores'", resource.getCoreTotal());
      Assert.assertNotNull("Resource not set 'used_cores'", resource.getCoreUsed());
      Assert.assertNotNull("Resource not set 'tot_mem'", resource.getMemoryTotal());
      Assert.assertNotNull("Resource not set 'used_mem'", resource.getMemoryUsed());
      vimArrayList.add(resource.getVimUuid());
    }

    for (String returnUiid : vimUuid) {
      Assert.assertTrue(
          "VIMs List doesn't contain vim " + returnUiid, vimArrayList.contains(returnUiid));
    }

    output = null;

    for (String regUuid : vimUuid) {
      output = null;
      String removeMessage = "{\"wr_type\":\"compute\",\"uuid\":\"" + regUuid + "\"}";
      topic = "infrastructure.management.compute.remove";
      ServicePlatformMessage removeVimMessage =
          new ServicePlatformMessage(
              removeMessage, "application/json", topic, UUID.randomUUID().toString(), topic);
      consumer.injectMessage(removeVimMessage);

      while (output == null) {
        synchronized (mon) {
          mon.wait(1000);
        }
      }

      tokener = new JSONTokener(output);
      jsonObject = (JSONObject) tokener.nextValue();
      status = jsonObject.getString("status");
      Assert.assertTrue(status.equals("COMPLETED"));
    }

    output = null;
    consumer.injectMessage(listVimMessage);
    while (output == null) {
      synchronized (mon) {
        mon.wait(1000);
      }
    }

    vimList = mapper.readValue(output, VimResources[].class);

    Assert.assertTrue("VIMs List not empty", vimList.length == 0);

    output = null;

    core.stop();
    WrapperBay.getInstance().clear();
  }
Esempio n. 26
0
  public void postData(int action, String url) throws JSONException {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    JSONObject j = new JSONObject();

    try {
      switch (action) {
        case POST_READ:
          j.put("Command", "Read");
          j.put("Dept", depts);
          Log.i(TAG, "DEPTS: " + depts);
          break;
      }

      JSONArray array = new JSONArray();
      array.put(j);

      // Post the data:
      httppost.setHeader("json", j.toString());
      httppost.getParams().setParameter("jsonpost", array);

      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);

      // for JSON:
      if (response != null) {
        InputStream is = response.getEntity().getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF8"));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
          while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
          }
        } catch (IOException e) {
          Log.e(TAG, e.toString());
          e.printStackTrace();
        } finally {
          try {
            is.close();
          } catch (IOException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
          }
        }
        responseString = sb.toString();
        Log.i(TAG, "Response: " + responseString);
      }
      JSONTokener tokener = new JSONTokener(responseString);
      Object o;
      while (tokener.more()) {
        o = tokener.nextValue();
        if (o instanceof JSONArray) {
          JSONArray result = (JSONArray) o;
          parseJSON(result);
        } else {
          // tv.setText("Cannot parse response from server; not a JSON Object");
        }
      }
      // tv.setText(reply);

    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      Log.e(TAG, "Client Protocol Exception:");
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      Log.e(TAG, "IO Exception:");
      e.printStackTrace();
    }
  }
Esempio n. 27
0
  public void onLogin(View v) {

    inicializar();
    String NombreUsuario = edittextUser.getText().toString();
    String ClaveUsuario = edittextPassword.getText().toString();
    // Toast.makeText(this, "aqui vamos", Toast.LENGTH_LONG).show();
    if (NombreUsuario.equals("") && ClaveUsuario.equals("")) {
      Toast.makeText(this, "Faltan por ingresar campos", Toast.LENGTH_LONG).show();

    } else {
      SoapObject request = new SoapObject(NAMESPACE, METODO);
      request.addProperty("request1", NombreUsuario);
      request.addProperty("request2", ClaveUsuario);

      SoapSerializationEnvelope Envoltorio = new SoapSerializationEnvelope(SoapEnvelope.VER11);
      Envoltorio.setOutputSoapObject(request);

      HttpTransportSE TransporteHttp = new HttpTransportSE(URL, 12000);

      try {
        TransporteHttp.call(SOAP_ACTION, Envoltorio);

        SoapObject result = (SoapObject) Envoltorio.bodyIn;

        if (result != null) {
          Log.e("TIPO ACCION: 2-- ", "opcion");
          //	Toast.makeText(getApplicationContext(), result.getProperty(0).toString(),
          // Toast.LENGTH_SHORT).show();

          JSONObject jsondatos = new JSONObject(result.getProperty(0).toString());
          // personas
          JSONTokener jsontokenerpersonas = new JSONTokener(jsondatos.get("persona").toString());
          JSONObject jsonpersonas = (JSONObject) jsontokenerpersonas.nextValue();
          objPersona = new Persona();
          objPersona.setDireccion(jsonpersonas.getString("direccion"));
          objPersona.setNombre(jsonpersonas.getString("nombres"));
          objPersona.setApellido(jsonpersonas.getString("apellidos"));
          objPersona.setEmail(jsonpersonas.getString("email"));
          objPersona.setDepartamento(jsonpersonas.getInt("id_departamento"));
          objPersona.setCedula(jsonpersonas.getString("cedula"));
          objPersona.setIdPersona(jsonpersonas.getInt("id_persona"));

          // datosusuarios
          JSONTokener jsontokenerdatosusuario =
              new JSONTokener(jsondatos.get("usuario").toString());
          JSONObject jsondatosusuario = (JSONObject) jsontokenerdatosusuario.nextValue();
          objUsuario = new Usuarios();
          objUsuario.setId_tipousuario(jsondatosusuario.getInt("id_tipousuario"));

          if (objUsuario.getId_tipousuario() == 2) {
            Toast.makeText(this, "Bienvenido Jefe ", Toast.LENGTH_LONG).show();
            intent = new Intent(this, MainActivity.class);
            System.out.println("Usuario");
            intent.putExtra("op", "1");
            intent.putExtra("id_persona", objPersona.getIdPersona());
            intent.putExtra("id_departamento", objPersona.getDepartamento());
            intent.putExtra(
                "nombre_persona", objPersona.getNombre() + " " + objPersona.getApellido());
            startActivity(intent);
          }
          if (objUsuario.getId_tipousuario() == 3) {
            Toast.makeText(this, "Bienvenido Empleado", Toast.LENGTH_LONG).show();
            intent = new Intent(this, MainActivity.class);
            intent.putExtra("op", "2");
            intent.putExtra("id_persona", objPersona.getIdPersona());
            intent.putExtra("id_departamento", objPersona.getDepartamento());
            intent.putExtra(
                "nombre_persona", objPersona.getNombre() + " " + objPersona.getApellido());
            startActivity(intent);
          }

        } else {
          Toast.makeText(getApplicationContext(), "No Response!", Toast.LENGTH_SHORT).show();
        }

      } catch (Exception e) {
        e.printStackTrace();
        // Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "Datos no coinciden con la BD", Toast.LENGTH_LONG).show();
      }
    }
    edittextUser.setText("");
    edittextPassword.setText("");
  }
Esempio n. 28
0
    @Override
    public void onPostExecute(String s) {
      if (mProgressDialog1 != null) {
        mProgressDialog1.dismiss();
      }
      try {
        JSONArray values = new JSONArray();
        JSONTokener tokener = new JSONTokener(s);
        values = (JSONArray) tokener.nextValue();

        Log.v(TAG, "synced contacts count is " + values.length());

        for (int i = 0; i < values.length(); i++) {
          JSONObject obj = new JSONObject();
          obj = values.getJSONObject(i);

          if (obj.getString("contact_name") != null) {
            syncedContacts.add(obj.getString("contact_name"));
          }
        }
      } catch (JSONException e) {
        e.printStackTrace();
      } catch (ClassCastException e) {
        e.printStackTrace();
      }

      allPhoneContacts =
          MainActivity.getPhoneContactNames(
              getActivity()
                  .getContentResolver()); // gets all contacts except ones marked for deletion
      Log.v(TAG, allPhoneContacts.size() + " all contacts ");
      Log.v(TAG, syncedContacts.size() + " synced contacts");
      displayList =
          MainActivity.getSyncedList(
              syncedContacts,
              allPhoneContacts); // compares synced contacts with unsynced ones to only show
                                 // unsynced contacts
      int duplicateCount = MainActivity.getDuplicates(syncedContacts, displayList);
      Log.v(
          TAG,
          "there are "
              + syncedContacts.size()
              + " synced contacts "
              + displayList.size()
              + " unsynced contacts");
      if (duplicateCount > 0) {
        {
          Toast t =
              Toast.makeText(
                  context,
                  "There are " + duplicateCount + " duplicate contacts",
                  Toast.LENGTH_SHORT);
          t.show();
        }
        DuplicateDialogFragment newFragment =
            new DuplicateDialogFragment().DuplicateDialogFragment();
        newFragment.getDuplicates(displayList);
        newFragment.getSyncedContacts(syncedContacts);
        newFragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
        newFragment.show(getActivity().getFragmentManager(), "dialog");
      }
      mArrayAdapter =
          new ArrayAdapter<String>(
              getActivity(), android.R.layout.simple_list_item_multiple_choice, displayList);
      Collections.sort(displayList);
      listContacts.setAdapter(mArrayAdapter);
      listContacts.setChoiceMode(listContacts.CHOICE_MODE_MULTIPLE);
    }
Esempio n. 29
0
        @Override
        public void handleMessage(Message msg) {
          switch (msg.what) {
            case VALIDCODE_MSG_CODE:
              djsx_tv.setVisibility(View.VISIBLE);
              yanzhengma_iv.setImageBitmap(validCodeBitmap);
              break;
            case COMMIT_ORDER_MSG_CODE:
              if (commitReturnJson.length() == 0) {
                getValidCodePic(); // 提交失败后需刷新验证码
                yanzhengma_input_et.setText("");
                progressdialog.dismiss();
                // new AlertDialog.Builder(context).setTitle("发生异常,订单提交失败!")
                // .setPositiveButton("确认", null).show();
                final CustomerAlertDialog cad = new CustomerAlertDialog(context, true);
                cad.setTitle("发生异常,订单提交失败");
                cad.setPositiveButton(
                    "知道了",
                    new OnClickListener() {
                      @Override
                      public void onClick(View arg0) {
                        cad.dismiss();
                      }
                    });
                break;
              }
              JSONTokener jsonParser;
              jsonParser = new JSONTokener(commitReturnJson);
              try {
                JSONObject jsonObject = (JSONObject) jsonParser.nextValue();
                String state = jsonObject.getString("c");

                if (state.equals("0000")) {
                  String orderID = jsonObject.getJSONObject("d").getString("msg");
                  Intent intent = new Intent(context, ActivityTrainOrderDetail.class);
                  intent.putExtra(ActivityTrainOrderDetail.ORDERRECEIPT, orderID);
                  startActivityForResult(intent, NEW_ORDER_DETAIL_CODE);

                } else {
                  // new AlertDialog.Builder(context)
                  // .setTitle(
                  // jsonObject.getJSONObject("d")
                  // .getString("msg"))
                  // .setPositiveButton("确定", null).show();
                  final CustomerAlertDialog cad = new CustomerAlertDialog(context, true);
                  cad.setTitle(jsonObject.getJSONObject("d").getString("msg"));
                  cad.setPositiveButton(
                      "知道了",
                      new OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                          cad.dismiss();
                        }
                      });
                  getValidCodePic(); // 提交失败后需刷新验证码
                  yanzhengma_input_et.setText("");
                }
                // else {
                // Toast.makeText(context, "发生异常,提交订单失败!", 0).show();
                // getValidCodePic();//提交失败后需刷新验证码
                // yanzhengma_input_et.setText("");
                // }
                progressdialog.dismiss();
              } catch (Exception e) {
                e.printStackTrace();
                getValidCodePic(); // 提交失败后需刷新验证码
                yanzhengma_input_et.setText("");
                progressdialog.dismiss();
              }
              break;
          }
        }
 JSONObject parse(String str) {
   JSONTokener jsonParser = new JSONTokener(str);
   JSONObject resp = (JSONObject) jsonParser.nextValue();
   return resp;
 }