Example #1
0
  /**
   * Reads the properties from the App.config file.
   *
   * @author S Downie
   * @param The activity
   */
  private void parse(Activity in_activity) {
    if (PackageFileUtils.doesFileExist(in_activity, k_configFilePath)) {
      String stringContents = PackageFileUtils.readTextFile(in_activity, k_configFilePath);

      try {
        JSONObject root = new JSONObject(stringContents);
        if (root.has("PreferredSurfaceFormat") == true) {
          m_surfaceFormat = root.getString("PreferredSurfaceFormat");
        }

        if (root.has("Android") == true) {
          JSONObject android = root.getJSONObject("Android");

          if (android.has("PreferredSurfaceFormat") == true) {
            m_surfaceFormat = android.getString("PreferredSurfaceFormat");
          }

          if (android.has("GooglePlay") == true) {
            JSONObject googlePlay = android.getJSONObject("GooglePlay");

            if (googlePlay.has("RequiresGooglePlayServices") == true) {
              m_requiresGooglePlayServices = googlePlay.getBoolean("RequiresGooglePlayServices");
            }
          }
        }
      } catch (Exception e) {
        Logging.logFatal("Could not load App.config!");
      }
    } else {
      Logging.logFatal("App.config does not exist!");
    }
  }
  private static List<Box> parseBoundingBoxes(JSONArray jPositions) throws JSONException {
    List<Box> boxes = new ArrayList<Box>();
    for (int i = 0; i < jPositions.length(); i++) {
      JSONObject jBox = jPositions.getJSONObject(i);

      Point topLeft = null;
      Point bottomRight = null;
      Integer page = null;

      if (jBox.has("page")) {
        page = jBox.getInt("page");
      }
      if (jBox.has("top_left")) {
        JSONObject jTopLeft = jBox.getJSONObject("top_left");
        topLeft = new Point(jTopLeft.getDouble("x"), jTopLeft.getDouble("y"));
      }
      if (jBox.has("bottom_right")) {
        JSONObject jBottomRight = jBox.getJSONObject("bottom_right");
        bottomRight = new Point(jBottomRight.getDouble("x"), jBottomRight.getDouble("y"));
      }

      Box box = new Box(topLeft, bottomRight, page);
      boxes.add(box);
    }
    return boxes;
  }
  private NetmeraDeviceDetail jsonArraytoNetmeraDeviceDetail(JSONArray array)
      throws JSONException, NetmeraException {
    NetmeraDeviceDetail deviceDetail = new NetmeraDeviceDetail(senderID);
    JSONObject obj = array.getJSONObject(0);

    if (obj.has("tags")) {
      JSONArray tags = obj.getJSONArray("tags");
      ArrayList<String> group = new ArrayList<String>();
      for (int i = 0; i < tags.length(); i++) {
        group.add(tags.getString(i));
      }

      deviceDetail.setDeviceGroups(group);
    }

    if (obj.has("location")) {
      JSONObject location = obj.getJSONObject("location");
      NetmeraGeoLocation geoLocation = new NetmeraGeoLocation();
      double latitude = location.getDouble("latitude");
      double longitude = location.getDouble("longitude");
      geoLocation.setLatitude(latitude);
      geoLocation.setLongitude(longitude);
      deviceDetail.setDeviceLocation(geoLocation);
    }
    return deviceDetail;
  }
  @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"));
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) {
        jb.append(line);
      }
      reader.close();
    } catch (Exception e) {
      /* report an error */
    }

    try {
      JSONObject input = new JSONObject(jb.toString());
      JSONArray array = null;
      if (input.has("lat") && input.has("lon")) {
        double lat = (Double) input.get("lat");
        double lon = (Double) input.get("lon");
        array = connection.GetRestaurantsNearLoationViaYelpAPI(lat, lon);
      }
      response.setContentType("application/json");
      response.addHeader("Access-Control-Allow-Origin", "*");
      PrintWriter out = response.getWriter();
      out.print(array);
      out.flush();
      out.close();
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
    @Override
    protected String doInBackground(String... params) {
      // TODO Auto-generated method stub
      docDetails = (DocumentDetails) documentView.getTag();
      DeleteDocument deleteDoc = new DeleteDocument(docDetails.szDocumentID, mContext);
      String response = deleteDoc.getResponse();
      try {
        JSONObject jObject = new JSONObject(response);

        if (jObject.has("success") && jObject.getString("success").equals("true")) {
          DriverAccountDetails driverAccount = new DriverAccountDetails(mContext);
          driverAccount.retriveAccountDetails(mContext);
          return "success";
        } else {
          if (jObject.has("errors")) {
            JSONArray jErrorsArray = jObject.getJSONArray("errors");

            String errorMessage = jErrorsArray.getJSONObject(0).getString("message");
            return errorMessage;
          }
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return response;
    }
  @Test
  public void testToString() throws Exception {
    ProductBagApi bags = new ProductBagApi(new MockContext());
    bags.addProduct("some bag name", new Product.Builder("product name", "product sku", 1).build());
    bags.addProduct(
        "some bag name", new Product.Builder("product name 2", "product sku 2", 1).build());
    bags.addProduct(
        "some bag name 2", new Product.Builder("product name 3", "product sku 3", 1).build());
    bags.addProduct("some bag name 3", null);
    JSONObject json = new JSONObject(bags.toString());
    assertTrue(json.has("some bag name"));
    JSONObject bag1 = json.getJSONObject("some bag name");
    assertTrue(bag1.has("pl"));
    JSONArray products1 = bag1.getJSONArray("pl");
    assertEquals(2, products1.length());
    JSONObject bag2 = json.getJSONObject("some bag name 2");
    assertTrue(bag2.has("pl"));
    JSONArray products2 = bag2.getJSONArray("pl");
    assertEquals(1, products2.length());

    JSONObject bag3 = json.getJSONObject("some bag name 3");
    assertTrue(bag3.has("pl"));
    JSONArray products3 = bag3.getJSONArray("pl");
    assertEquals(0, products3.length());
  }
  @SuppressWarnings("unchecked")
  public MobeelizerJsonEntity(final String json) throws JSONException {
    JSONObject jsonObject = new JSONObject(json);
    model = jsonObject.getString("model");
    guid = jsonObject.getString("guid");

    if (jsonObject.has("owner")) {
      owner = jsonObject.getString("owner");
    }

    if (jsonObject.has("conflictState")) {
      conflictState = ConflictState.valueOf(jsonObject.getString("conflictState"));
    } else {
      conflictState = ConflictState.NO_IN_CONFLICT;
    }

    if (jsonObject.has("fields")) {
      JSONObject jsonFields = jsonObject.getJSONObject("fields");
      Iterator<String> keys = jsonFields.keys();
      fields = new HashMap<String, String>();

      while (keys.hasNext()) {
        String key = keys.next();
        fields.put(key, jsonFields.isNull(key) ? null : jsonFields.getString(key));
      }
    }
  }
Example #9
0
 public static Video parse(JSONObject o) throws NumberFormatException, JSONException {
   Video v = new Video();
   if (o.has("vid")) v.vid = o.getLong("vid");
   if (o.has("id")) // video.getUserVideos
   v.vid = Long.parseLong(o.getString("id"));
   v.owner_id = o.getLong("owner_id");
   v.title = Api.unescape(o.getString("title"));
   v.duration = o.getLong("duration");
   v.description = Api.unescape(o.optString("description"));
   if (o.has("image")) v.image = o.optString("image");
   v.image_big = o.optString("image_medium");
   if (o.has("thumb")) // video.getUserVideos
   v.image = o.optString("thumb");
   v.link = o.optString("link");
   v.date = o.optLong("date");
   v.player = o.optString("player");
   if (o.has("views")) {
     v.views = o.getLong("views");
   }
   JSONObject files = o.optJSONObject("files");
   if (files != null) {
     v.external = files.optString("external");
     v.mp4_240 = files.optString("mp4_240");
     v.mp4_360 = files.optString("mp4_360");
     v.mp4_480 = files.optString("mp4_480");
     v.mp4_720 = files.optString("mp4_720");
     v.flv_320 = files.optString("flv_320");
   }
   return v;
 }
  @Test
  public void testParsableByValues() throws Exception {
    final Configuration config = configurationFactory.getConfig(getFile(BASE_DIR + "config.yaml"));
    PJsonObject requestData = loadJsonRequestData();

    Template template = config.getTemplate("main");
    Values values =
        new Values(
            requestData,
            template,
            this.parser,
            config.getDirectory(),
            httpClientFactory,
            config.getDirectory());

    assertTrue(values.getBoolean("field1"));
    assertFalse(values.getBoolean("field2"));
    assertFalse(values.getBoolean("field3"));

    JSONObject field2Config =
        AbstractAttributeTest.getClientConfig(template.getAttributes().get("field2"), template);
    assertFalse(field2Config.has(ReflectiveAttribute.JSON_ATTRIBUTE_DEFAULT));

    JSONObject field3Config =
        AbstractAttributeTest.getClientConfig(template.getAttributes().get("field3"), template);
    assertTrue(field3Config.has(ReflectiveAttribute.JSON_ATTRIBUTE_DEFAULT));
    assertFalse(field3Config.getBoolean(ReflectiveAttribute.JSON_ATTRIBUTE_DEFAULT));
  }
    @Override
    protected String doInBackground(String... params) {
      // TODO Auto-generated method stub
      GetPaymentStatus getPaymentStatus = null;
      Log.e(TAG, "job id to check payment for:  " + szReturnedBookingId);
      if (szReturnedBookingId != null && !szReturnedBookingId.isEmpty()) {
        getPaymentStatus = new GetPaymentStatus(_context, szReturnedBookingId);
      } else {
        getPaymentStatus = new GetPaymentStatus(_context, sJobId);
      }
      String response = getPaymentStatus.getPaymentStatus();

      if (Constants.isDebug) Log.e(TAG, "GetPaymentStatusTask response::> " + response);

      try {
        JSONObject jObject = new JSONObject(response);
        if (jObject.has("success") && jObject.getString("success").equals("true")) {
          return "true";
        } else if (jObject.has("success") && jObject.getString("success").equals("false")) {
          return "false";
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return response;
    }
Example #12
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);
    	}
    }
    */
  }
Example #13
0
  @Override
  protected void getMessage(String message) {
    try {
      JSONObject jsonObject = new JSONObject(message);

      if (jsonObject.has(Constants.JSON_COLOR)) { // Sphero color and position
        position = jsonObject.getInt(Constants.JSON_SPHERO_NUMBER);

        String color = jsonObject.getString(Constants.JSON_COLOR);
        int rgb = Color.parseColor(color);
        spheroColor.setBackgroundColor(rgb);

        String sphero_position = getString(R.string.sphero_position);
        double positionX = jsonObject.getDouble(Constants.JSON_POSITION_X);
        double positionY = jsonObject.getDouble(Constants.JSON_POSITION_Y);
        sphero_position = String.format(sphero_position, positionX, positionY);
        TextView locationTv = (TextView) findViewById(R.id.locationTV);
        locationTv.setText(sphero_position);
      } else if (jsonObject.has(Constants.JSON_STABILIZATION)) { // Sphero stabilized
        int charge = jsonObject.getInt(Constants.JSON_CHARGE_VALUE);

        np.setValue(charge);
        LinearLayout ln = (LinearLayout) findViewById(R.id.linearLayout);
        ln.setVisibility(View.VISIBLE);
      }
    } catch (JSONException e) {
      Log.e(Constants.LOG_TAG, "Error parsing JSON", e);
    }
  }
Example #14
0
  public String parse(String s, BadgeDetailData badgeDetailData) {
    JSONObject jAData = null;
    String msg = "";
    int errCode = -1;

    try {
      jAData = new JSONObject(s);
      if (jAData.has("code")) {
        errCode = jAData.getInt("code");
      } else if (jAData.has("errcode")) {
        errCode = jAData.getInt("errcode");
      } else if (jAData.has("errorCode")) {
        errCode = jAData.getInt("errorCode");
      }
      if (jAData.has("jsession")) {
        UserNow.current().jsession = jAData.getString("jsession");
      }
      if (errCode == JSONMessageType.SERVER_CODE_OK) {
        JSONObject content = jAData.getJSONObject("content");
        badgeDetailData.id = content.optInt("id");
        badgeDetailData.name = content.optString("name");
        badgeDetailData.pic = content.optString("pic");
        badgeDetailData.intro = content.optString("intro");
        badgeDetailData.getCount = content.optInt("getCount");
        badgeDetailData.getTime = content.optInt("getTime");
      } else msg = jAData.getString("msg");
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return msg;
  }
Example #15
0
  public Properties pair(String applicationName) throws CommunicationException {
    HueMethod method = new HueMethod(this);
    HashMap<String, Object> auth = new HashMap<String, Object>();

    auth.put("username", generateKey());
    auth.put("devicetype", applicationName);
    try {
      JSONObject result = method.post("", new JSONObject(auth));
      Properties properties = new Properties();

      properties.put("accessKey", accessKey);
      if (result != null && result.has("success")) {
        result = result.getJSONObject("success");
        if (result.has("username")) {
          accessKey = result.getString("username");
          endpoint = "http://" + ipAddress + "/api/" + accessKey + "/";
          properties.put("accessKey", accessKey);
          return properties;
        }
      }
      throw new HueException("Failed to receive authentication key");
    } catch (JSONException e) {
      throw new HueException(e);
    }
  }
Example #16
0
 /**
  * 获取可升级应用
  *
  * @param install已安装应用
  * @return
  */
 public List<ApplicationBean> getNativeUpdateAppsList(List<ApplicationBean> install) {
   List<ApplicationBean> tempList = new ArrayList<ApplicationBean>();
   try {
     String josnString = mNetUtil.connect(con.getApplicationContext(), install);
     JSONObject json = new JSONObject(josnString);
     if (!json.has("appList")) {
       return null;
     }
     JSONArray arr = json.getJSONArray("appList");
     if (null == arr || arr.length() < 1) {
       return null;
     }
     JSONObject updObj;
     ApplicationBean tempApp;
     for (int i = 0; i < arr.length(); i++) {
       tempApp = new ApplicationBean();
       updObj = arr.getJSONObject(i);
       if (updObj.has("id")) {
         tempApp.setId(updObj.getInt("id"));
       }
       tempApp.setPkgName(updObj.getString("packageName"));
       tempApp.setAppName(updObj.getString("appName"));
       tempApp.setVersion(updObj.getString("versionCode"));
       tempApp.setTypeName(updObj.getString("typeName"));
       tempApp.setUrl(RequestParam.SERVICE_IMAGE_URL + updObj.getString("url"));
       tempApp.setIconUrl(RequestParam.SERVICE_IMAGE_URL + updObj.getString("icon"));
       tempList.add(tempApp);
     }
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
   return tempList;
 }
  private CompleteDNS getCompleteDNS(@Nonnull String providerDnsZoneId, boolean withSubdomains)
      throws CloudException, InternalException {
    Logger std = NovaOpenStack.getLogger(RackspaceCloudDNS.class, "std");

    if (std.isTraceEnabled()) {
      std.trace("ENTER: " + RackspaceCloudDNS.class.getName() + ".getCompleteDNS()");
    }
    try {
      ProviderContext ctx = provider.getContext();

      if (ctx == null) {
        std.error("No context exists for this request");
        throw new InternalException("No context exists for this request");
      }
      String query = providerDnsZoneId + "?showRecords=true";

      if (withSubdomains) {
        query = query + "&showSubdomains=true";
      }
      NovaMethod method = new NovaMethod(provider);
      JSONObject response = method.getResource(SERVICE, RESOURCE, query, false);

      if (response == null) {
        return null;
      }
      try {
        DNSZone zone = toZone(ctx, response);

        if (zone != null) {
          CompleteDNS dns = new CompleteDNS();

          dns.domain = zone;
          dns.subdomains = new ArrayList<DNSZone>();

          JSONObject subdomains =
              (response.has("subdomains") ? response.getJSONObject("subdomains") : null);

          if (subdomains != null) {
            JSONArray domains =
                (subdomains.has("domains") ? subdomains.getJSONArray("domains") : null);

            if (domains != null) {
              listSubdomains(ctx, dns.subdomains, zone, domains);
            }
          }
          return dns;
        }
      } catch (JSONException e) {
        std.error("getCompleteDNS(): JSON error parsing response: " + e.getMessage());
        e.printStackTrace();
        throw new CloudException(
            CloudErrorType.COMMUNICATION, 200, "invalidResponse", "JSON error parsing " + response);
      }
      return null;
    } finally {
      if (std.isTraceEnabled()) {
        std.trace("exit - " + RackspaceCloudDNS.class.getName() + ".getCompleteDNS()");
      }
    }
  }
  /** parse an acknowledge to a token sent, analyze for permissions, disconnect on error */
  protected void parseVideoTokenResponse(JSONArray arg) {
    // TODO dk: parse all the other things that come with the response? TURN
    // Server, etc?
    boolean success = false;
    String message = "";
    try {
      success = "success".equalsIgnoreCase(arg.getString(0));
      if (success) {
        JSONObject obj = arg.getJSONObject(1);
        boolean subscribe = false;
        boolean publish = false;
        if (obj.has("permissions")) {
          JSONObject permissions = obj.getJSONObject("permissions");
          subscribe = permissions.has("subscribe") && permissions.getBoolean("subscribe");
          publish = permissions.has("publish") && permissions.getBoolean("publish");
        }
        mPermissionSubscribe = subscribe;
        mPermissionPublish = publish;
      } else {
        message = arg.get(1).toString();
      }
    } catch (JSONException e) {
      log(e.getMessage());
    }

    if (!success) {
      log("Token failed: " + message);
      disconnect();
    }
  }
Example #19
0
  public void parseJSONObject(JSONObject obj) {
    try {
      status = obj.getInt("status");

      if (obj.has("id")) {
        ID = obj.getString("id");
      }
      name = obj.getString("name");
      email = obj.getString("email");
      if (obj.has("publicKey")) {
        publicKey = obj.getString("publicKey");
      }
      if (obj.has("fileLink")) {
        fileLink = obj.getString("fileLink");
      }
      if (obj.has("fileKey")) {
        fileKey = obj.getString("fileKey");
      }

      nonce = obj.getString("nonce");
      if (obj.has("nonce2")) {
        nonce2 = obj.getString("nonce2");
      }

      JSONArray groupMemberList = obj.getJSONArray("groups");

      for (int n = 0; n < groupMemberList.length(); n++) {
        String groupID = groupMemberList.getString(n);
        groups.add(groupID);
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
  /**
   * Parses a chrome message into a JsonPrintMessageInterface object.
   *
   * @param message
   * @return a concrete JsonPrintMessageInterface object.
   * @throws JSONException
   * @throws IOException
   */
  public JsonPrintMessageInterface parse(MessageInterface message)
      throws JSONException, IOException {

    JSONObject json = new JSONObject(message.getBody());
    String printerName = json.getString("printerName");
    String printerType = json.getString("printerType");
    DocumentInterface document = null;

    if (json.has("filePath")) {
      String filePath = json.getString("filePath");
      try {
        URL fileUrl = new URL(filePath);
        document = loadRemoteFile(fileUrl, json.getString("cookie"));
      } catch (MalformedURLException $ex) {
        document = loadLocalFile(filePath);
      }
    } else {
      document = new Base64Document(json.getString("fileContent"));
    }

    JsonPrintMessage printMessage = new JsonPrintMessage(message);
    printMessage.setPrinterName(printerName);
    printMessage.setPrinterType(printerType);
    printMessage.setDocument(document);

    if (json.has("requestId")) {
      printMessage.setRequestId(json.getString("requestId"));
    }
    return printMessage;
  }
Example #21
0
 /**
  * [刷新widget,更新头像地址,图片缓存]<br>
  * 刷新widget,更新头像地址,图片缓存,并返回新的头像路径与名称
  *
  * @param context 上下文
  * @param jsonStr 网络返回结果
  * @param userid 用户userId
  * @return 用户信息,其中仅包括新的头像路径与名称
  */
 public static UserInfo refreshWidget(Context context, String jsonStr, String userid) {
   UserInfo userInfo = null;
   try {
     JSONObject jObject = new JSONObject(jsonStr);
     String code;
     if (jObject.has(UserInfoUtil.KEY_JASON_RETCODE)) {
       code = jObject.getString(UserInfoUtil.KEY_JASON_RETCODE);
       if (!TextUtils.isEmpty(code)
           && Integer.parseInt(code) == HttpStatus.SC_OK
           && jObject.has(UserInfoUtil.KEY_JASON_DATA)) {
         jObject = jObject.getJSONObject(UserInfoUtil.KEY_JASON_DATA);
         if (jObject.has(UserInfoUtil.KEY_USER_HEADPIC_PATH)
             && jObject.has(UserInfoUtil.KEY_USER_HEADPIC_NAME)) {
           userInfo = new UserInfo();
           String headPath = jObject.getString(UserInfoUtil.KEY_USER_HEADPIC_PATH);
           userInfo.setHeadPicPath(headPath);
           String headName = jObject.getString(UserInfoUtil.KEY_USER_HEADPIC_NAME);
           userInfo.setHeadPicName(headName);
           MemberDao dao = new MemberDao(SmartHomeApplication.getInstance());
           dao.update(userid, headPath, headName);
           dao.close();
           Intent intent = new Intent(FsConstants.WIDGET_MEMBERS_CHANGE);
           context.sendBroadcast(intent);
         }
       }
     }
   } catch (JSONException e) {
     log("------refreshWidget------" + e.toString());
   }
   return userInfo;
 }
Example #22
0
 /**
  * 解析google事件列表
  *
  * @param cal
  * @param json
  * @return
  * @throws JSONException
  */
 private List<FDEvent> getGoogleEventsByJson(FDCalendar cal, String json) throws JSONException {
   List<FDEvent> events = new ArrayList<FDEvent>();
   if (StringUtil.isBlank(json) || json.length() < 5) return events;
   JSONObject jObj = new JSONObject(json);
   JSONObject obj = null;
   if (jObj.has("data")) {
     obj = jObj.getJSONObject("data");
     String itemsJson = jObj.getJSONObject("data").toString();
     //			System.out.println("items : "+itemsJson);
     //			System.out.println("obj : "+obj);
   }
   // 当json返回为空或是数字时,不作处理,返回无数据集合出去
   if (obj == null) {
     return events;
   }
   if (obj != null) {
     if (obj.has("items")) {
       setItemsToList(cal, events, obj);
     } else if (obj.has("data")) {
       JSONObject itemsJson = obj.getJSONObject("data");
       if (itemsJson.has("items")) {
         setItemsToList(cal, events, itemsJson);
       }
     }
   }
   return events;
 }
Example #23
0
 @NonNull
 public static List<TinderPurchase> m8933c(@NonNull JSONObject jSONObject) {
   List<TinderPurchase> arrayList = new ArrayList();
   try {
     JSONArray jSONArray = jSONObject.getJSONArray("results");
     for (int i = 0; i < jSONArray.length(); i++) {
       JSONObject jSONObject2 = jSONArray.getJSONObject(i);
       TinderPurchase tinderPurchase = new TinderPurchase();
       if (jSONObject2.has("_id")) {
         tinderPurchase.setId(jSONObject2.getString("_id"));
       }
       if (jSONObject2.has("product_id")) {
         tinderPurchase.setProductId(jSONObject2.getString("product_id"));
       }
       if (jSONObject2.has("product_type")) {
         tinderPurchase.setProductType(jSONObject2.getString("product_type"));
       }
       if (jSONObject2.has("purchase_type")) {
         tinderPurchase.setPurchaseType(jSONObject2.getString("purchase_type"));
       }
       if (jSONObject2.has("create_date")) {
         tinderPurchase.setCreateDate(jSONObject2.getString("create_date"));
       }
       arrayList.add(tinderPurchase);
     }
   } catch (Exception e) {
     C3095y.m9471a(e.getMessage());
   }
   return arrayList;
 }
  public void configure(JSONObject config) throws JSONException {
    if (config.has("pairingLevel")) {
      String pairingLevel = config.getString("pairingLevel");

      if ("off".equals(pairingLevel)) {
        discoveryManager.setPairingLevel(PairingLevel.OFF);
      } else if ("on".equals(pairingLevel)) {
        discoveryManager.setPairingLevel(PairingLevel.ON);
      }
    }

    if (config.has("capabilityFilters")) {
      JSONArray filters = config.getJSONArray("capabilityFilters");
      ArrayList<CapabilityFilter> capabilityFilters = new ArrayList<CapabilityFilter>();

      for (int i = 0; i < filters.length(); i++) {
        JSONArray filter = filters.getJSONArray(i);
        CapabilityFilter capabilityFilter = new CapabilityFilter();

        for (int j = 0; j < filter.length(); j++) {
          capabilityFilter.addCapability(filter.getString(j));
        }

        capabilityFilters.add(capabilityFilter);
      }

      discoveryManager.setCapabilityFilters(capabilityFilters);
    }
  }
 private JSONArray constructResponse(Cursor c, String parameters) throws JSONException {
   JSONObject params = new JSONObject(parameters);
   c.moveToFirst();
   String[] columnNames = c.getColumnNames();
   JSONArray json = new JSONArray();
   String addressFieldName = null;
   if (params.has("addressFieldName") && null != params.getString("addressFieldName")) {
     addressFieldName =
         CaseFormat.LOWER_UNDERSCORE.to(
             CaseFormat.LOWER_CAMEL, params.getString("addressFieldName"));
   }
   while ((!c.isAfterLast())) {
     JSONObject obj = new JSONObject();
     for (int i = 0; i < columnNames.length; i++) {
       if (columnNames[i].equals("birthdate")) {
         obj.put(
             "age", Years.yearsBetween(DateTime.parse(c.getString(i)), new DateTime()).getYears());
       } else if (params.has("addressFieldName") && columnNames[i].equals(addressFieldName)) {
         JSONObject address = new JSONObject();
         address.put(params.getString("addressFieldName"), c.getString(i));
         obj.put("addressFieldValue", address);
       } else if (params.has("extraIdentifiers") && columnNames[i].equals("extraIdentifiers")) {
         JSONObject extraIdentifiers = new JSONObject();
         extraIdentifiers.put("extraIdentifiers", c.getString(i));
         obj.put("extraIdentifiers", extraIdentifiers);
       } else {
         obj.put(columnNames[i], c.getString(i));
       }
     }
     json.put(obj);
     c.moveToNext();
   }
   c.close();
   return json;
 }
  public PagedResult<User> readUsers(String source) throws ReviewboardException {

    try {
      JSONObject rootObject = checkedGetJSonRootObject(source);

      int totalResults = rootObject.getInt("total_results");

      JSONArray jsonUsers = rootObject.getJSONArray("users");
      List<User> users = new ArrayList<User>();

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

        JSONObject jsonUser = jsonUsers.getJSONObject(i);

        User user = new User();
        user.setId(jsonUser.getInt("id"));
        user.setUrl(jsonUser.getString("url"));
        user.setUsername(jsonUser.getString("username"));
        // some fields are not set for private profiles
        user.setEmail(jsonUser.has("email") ? jsonUser.getString("email") : "");
        user.setFirstName(jsonUser.has("first_name") ? jsonUser.getString("first_name") : "");
        user.setLastName(jsonUser.has("last_name") ? jsonUser.getString("last_name") : "");

        users.add(user);
      }

      return PagedResult.create(users, totalResults);
    } catch (JSONException e) {
      throw new ReviewboardException(e.getMessage(), e);
    }
  }
 public ModelAwardHistory(JSONObject object) throws JSONException {
   if (object != null) {
     jsonObject = object;
     if (object.has("id")) {
       if (!object.optString("id").equalsIgnoreCase("null")) {
         id = object.optString("id");
       }
     }
     if (object.has("winDate")) {
       if (!object.optString("winDate").equalsIgnoreCase("null")) {
         winDate = object.optString("winDate");
       }
     }
     if (object.has("orderNumber")) {
       if (!object.optString("orderNumber").equalsIgnoreCase("null")) {
         orderNumber = object.optString("orderNumber");
       }
     }
     if (object.has("prizeId")) {
       if (!object.optString("prizeId").equalsIgnoreCase("null")) {
         prizeId = object.optString("prizeId");
       }
     }
     if (object.has("winMoney")) {
       if (!object.optString("winMoney").equalsIgnoreCase("null")) {
         winMoney = object.optDouble("winMoney");
       }
     }
     isGrant = object.optInt("isGrant");
     award = new ModelAward(object.optJSONObject("prize"));
   }
 }
Example #28
0
  static void processEntityView(JSONObject entity, DbContext ctx) {
    ViewEntityModel viewModel =
        ctx.currentVersion()
            .newViewModel(
                entity.getString("name"), !entity.has("render") || entity.getBoolean("render"));
    viewModel.setRootModel(ctx.getModel(entity.getString("rootModel")));
    viewModel.setRootAlias(entity.getString("rootAlias"));
    if (entity.has("groupBy")) viewModel.setGroupBy(entity.getString("groupBy"));

    EntityModelVersion v = viewModel.currentVersion();

    if (entity.has("models")) {
      JSONArray models = entity.getJSONArray("models");
      // add the models
      for (int m = 0; m < models.length(); m++) {
        JSONObject child = models.getJSONObject(m);
        EntityModel childModel = ctx.getModel(child.getString("name"));
        ViewEntityModel.Relationship relationship =
            ViewEntityModel.Relationship.valueOf(child.getString("type"));
        String alias = child.has("alias") ? child.getString("alias") : child.getString("name");
        viewModel.addModel(childModel, relationship, alias, child.getString("selection"));
      }
    }
    // process model properties
    processViewModel(ctx, entity, viewModel, v);
  }
Example #29
0
 /**
  * Adds the card to the view
  *
  * @param sharedPreferences the shared preferences
  * @param key the key
  */
 private void addCard(SharedPreferences sharedPreferences, String key) {
   String json = sharedPreferences.getString(key, null);
   if (json != null) {
     try {
       JSONObject jsonData = new JSONObject(json);
       if (jsonData.has(IMAGE_KEY)) {
         String image = jsonData.getString(IMAGE_KEY);
         List<ITopic> cards = getSourceTopicModel();
         if (key.equals(POOL_KEY)) {
           cards.add(0, Cards.pool(image, getActivity()));
           removeDuplicates(POOL_KEY, cards);
         } else if (key.equals(FOOD_KEY)) {
           cards.add(0, Cards.food(image, getActivity()));
           removeDuplicates(FOOD_KEY, cards);
         }
       } else if (jsonData.has(MESSAGE_KEY)) {
         String message = jsonData.getString(MESSAGE_KEY);
         List<ITopic> cards = getSourceTopicModel();
         cards.add(0, Cards.test(message, getActivity()));
       }
       UI.execute(this::filterModel);
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
 }
Example #30
0
    public void assertMatch(JSONObject json) {
      assertEquals(mPayloadType, json.optInt("type"));
      assertEquals(mClockRate, json.optInt("clockRate"));
      assertEquals(mEncodingName, json.optString("encodingName"));
      if (mChannels > 0) {
        assertEquals(mChannels, json.optInt("channels"));
      }
      if (mNackPli != null) {
        json.has("nackpli");
        assertEquals((boolean) mNackPli, json.optBoolean("nackpli"));
      }
      if (mNack != null) {
        json.has("nack");
        assertEquals((boolean) mNack, json.optBoolean("nack"));
      }
      if (mCcmFir != null) {
        json.has("ccmfir");
        assertEquals((boolean) mCcmFir, json.optBoolean("ccmfir"));
      }
      JSONObject jsonParameters = json.optJSONObject("parameters");
      if (mParameters != null) {
        assertNotNull(jsonParameters);
        assertEquals(mParameters.size(), jsonParameters.length());

        for (Map.Entry<String, Object> parameter : mParameters.entrySet()) {
          assertTrue(jsonParameters.has(parameter.getKey()));
          assertEquals(parameter.getValue(), jsonParameters.opt(parameter.getKey()));
        }
      } else {
        assertTrue(jsonParameters == null || jsonParameters.length() == 0);
      }
    }