Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

In this page you can find the example usage for org.json JSONObject getJSONObject.

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

/**
 * @see com.roiland.crm.core.service.ProjectAPI#getProjectInfo(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
 *//*from  w  w  w  .  ja  v a2s.  c om*/
@Override
public Project getProjectInfo(String userID, String dealerOrgID, String projectID, String customerID)
        throws ResponseException {
    Project project = null;
    try {
        if (userID == null || dealerOrgID == null) {
            throw new ResponseException("userID or dealerOrgID is null.");
        }
        JSONObject params = new JSONObject();
        params.put("userID", userID);
        params.put("dealerOrgID", dealerOrgID);
        params.put("projectID", projectID);
        params.put("customerID", customerID);

        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_GET_PROJECT_INFO), params, null);
        if (response.isSuccess()) {
            project = new Project();
            JSONObject result = new JSONObject(getSimpleString(response)).getJSONObject("result");
            JSONObject customerEntityresult = result.getJSONObject("customerEntity");
            JSONObject purchaseCarIntentionresult = result.getJSONObject("purchaseCarIntention");

            Customer customerEntity = new Customer();
            PurchaseCarIntention purchaseCarIntention = new PurchaseCarIntention();
            if (StringUtils.isEmpty(projectID)) {
                customerEntity.setProjectID(projectID);
            }
            customerEntity.setCustomerID(parsingString(customerEntityresult.get("customerID")));
            customerEntity.setCustName(parsingString(customerEntityresult.get("custName")));
            customerEntity.setCustFromCode(parsingString(customerEntityresult.get("custFromCode")));
            customerEntity.setCustFrom(parsingString(customerEntityresult.get("custFrom")));
            customerEntity.setCustTypeCode(parsingString(customerEntityresult.get("custTypeCode")));
            customerEntity.setCustType(parsingString(customerEntityresult.get("custType")));
            customerEntity.setInfoFromCode(parsingString(customerEntityresult.get("infoFromCode")));
            customerEntity.setInfoFrom(parsingString(customerEntityresult.get("infoFrom")));
            customerEntity.setCollectFromCode(parsingString(customerEntityresult.get("collectFromCode")));
            customerEntity.setCollectFrom(parsingString(customerEntityresult.get("collectFrom")));
            customerEntity.setCustMobile(parsingString(customerEntityresult.get("custMobile")));
            customerEntity.setCustOtherPhone(parsingString(customerEntityresult.get("custOtherPhone")));
            customerEntity.setGenderCode(parsingString(customerEntityresult.get("genderCode")));
            customerEntity.setGender(parsingString(customerEntityresult.get("gender")));
            customerEntity.setBirthday(parsingString(customerEntityresult.get("birthday")));
            customerEntity.setIdTypeCode((parsingString(customerEntityresult.get("idTypeCode"))));
            customerEntity.setIdType(parsingString(customerEntityresult.get("idType")));
            customerEntity.setIdNumber(parsingString(customerEntityresult.get("idNumber")));
            customerEntity.setProvinceCode(parsingString(customerEntityresult.get("provinceCode")));
            customerEntity.setProvince(parsingString(customerEntityresult.get("province")));
            customerEntity.setCityCode(parsingString(customerEntityresult.get("cityCode")));
            customerEntity.setCity(parsingString(customerEntityresult.get("city")));
            customerEntity.setDistrictCode(parsingString(customerEntityresult.get("districtCode")));
            customerEntity.setDistrict(parsingString(customerEntityresult.get("district")));
            customerEntity.setQq(parsingString(customerEntityresult.get("qq")));
            customerEntity.setAddress(parsingString(customerEntityresult.get("address")));
            customerEntity.setPostcode(parsingString(customerEntityresult.get("postcode")));
            customerEntity.setEmail(parsingString(customerEntityresult.get("email")));
            customerEntity.setConvContactTime(parsingString(customerEntityresult.get("convContactTime")));
            //              customerEntity.setConvContactTimeCode((customerEntityresult
            //                              .get("convContactTimeCode")));
            customerEntity
                    .setExpectContactWayCode(parsingString(customerEntityresult.get("expectContactWayCode")));
            customerEntity.setExpectContactWay((parsingString(customerEntityresult.get("expectContactWay"))));
            customerEntity.setFax(parsingString(customerEntityresult.get("fax")));
            //              customerEntity.setExistingCarCode(String
            //                      .valueOf(parsingString(customerEntityresult
            //                              .get("existingCarCode"))));
            customerEntity.setExistingCarBrand(parsingString(customerEntityresult.get("existingCarBrand")));
            customerEntity.setIndustryCode(parsingString(customerEntityresult.get("industryCode")));
            customerEntity.setPositionCode(parsingString(customerEntityresult.get("positionCode")));
            customerEntity.setEducationCode(parsingString(customerEntityresult.get("educationCode")));
            customerEntity.setExistingCar(parsingString(customerEntityresult.get("existingCar")));
            customerEntity.setIndustry(parsingString(customerEntityresult.get("industry")));
            customerEntity.setPosition(parsingString(customerEntityresult.get("position")));
            customerEntity.setEducation(parsingString(customerEntityresult.get("education")));
            customerEntity.setCustInterestCode1(parsingString(customerEntityresult.get("custInterestCode1")));
            customerEntity.setCustInterest1((parsingString(customerEntityresult.get("custInterest1"))));
            customerEntity.setCustInterestCode2((parsingString(customerEntityresult.get("custInterestCode2"))));
            customerEntity.setCustInterest2(parsingString(customerEntityresult.get("custInterest2")));
            customerEntity.setCustInterestCode3(parsingString(customerEntityresult.get("custInterestCode3")));
            customerEntity.setCustInterest3(parsingString(customerEntityresult.get("custInterest3")));
            customerEntity.setExistLisenPlate(parsingString(customerEntityresult.get("existLisenPlate")));
            customerEntity.setEnterpTypeCode(parsingString(customerEntityresult.get("enterpTypeCode")));
            customerEntity.setEnterpType(parsingString(customerEntityresult.get("enterpType")));
            customerEntity
                    .setEnterpPeopleCountCode(parsingString(customerEntityresult.get("enterpPeopleCountCode")));
            customerEntity.setEnterpPeopleCount(parsingString(customerEntityresult.get("enterpPeopleCount")));
            customerEntity
                    .setRegisteredCapitalCode(parsingString(customerEntityresult.get("registeredCapitalCode")));
            customerEntity.setRegisteredCapital(parsingString(customerEntityresult.get("registeredCapital")));
            //              customerEntity.setCompeCarModelCode(String
            //                      .valueOf(parsingString(customerEntityresult
            //                              .get("compeCarModelCode"))));
            customerEntity.setCompeCarModel(parsingString(customerEntityresult.get("compeCarModel")));
            customerEntity.setRebuyStoreCustTag(
                    Boolean.parseBoolean((parsingString(customerEntityresult.get("rebuyStoreCustTag")))));
            customerEntity.setRebuyOnlineCustTag(
                    Boolean.parseBoolean(parsingString(customerEntityresult.get("rebuyOnlineCustTag"))));
            customerEntity.setChangeCustTag(
                    Boolean.parseBoolean(parsingString(customerEntityresult.get("changeCustTag"))));
            customerEntity.setLoanCustTag(
                    Boolean.parseBoolean((parsingString(customerEntityresult.get("loanCustTag")))));
            customerEntity.setHeaderQuartCustTag(
                    Boolean.parseBoolean(parsingString(customerEntityresult.get("headerQuartCustTag"))));
            customerEntity.setRegularCustTag(
                    Boolean.parseBoolean(parsingString(customerEntityresult.get("regularCustTag"))));
            customerEntity.setRegularCustCode(parsingString(customerEntityresult.get("regularCustCode")));
            customerEntity.setRegularCust(parsingString(customerEntityresult.get("regularCust")));
            customerEntity
                    .setBigCustTag(Boolean.parseBoolean(parsingString(customerEntityresult.get("bigCustTag"))));
            customerEntity.setBigCustsCode(parsingString(customerEntityresult.get("bigCustsCode")));
            customerEntity.setBigCusts(parsingString(customerEntityresult.get("bigCusts")));
            customerEntity.setCustComment(parsingString(customerEntityresult.get("custComment")));
            //customerEntity.setHasUnexePlan(parsingString(customerEntityresult.get("hasUnexePlan")));

            purchaseCarIntention.setBrandCode(parsingString(purchaseCarIntentionresult.get("brandCode")));
            purchaseCarIntention.setBrand(parsingString(purchaseCarIntentionresult.get("brand")));

            purchaseCarIntention.setModelCode(parsingString(purchaseCarIntentionresult.get("modelCode")));
            purchaseCarIntention.setModel(parsingString(purchaseCarIntentionresult.get("model")));
            purchaseCarIntention
                    .setOutsideColorCode(parsingString(purchaseCarIntentionresult.get("outsideColorCode")));
            purchaseCarIntention.setOutsideColor(parsingString(purchaseCarIntentionresult.get("outsideColor")));
            purchaseCarIntention
                    .setInsideColorCode(parsingString(purchaseCarIntentionresult.get("insideColorCode")));
            purchaseCarIntention.setInsideColor(parsingString(purchaseCarIntentionresult.get("insideColor")));
            purchaseCarIntention.setInsideColorCheck(
                    purchaseCarIntentionresult.getBoolean("insideColorCheck") ? true : false);
            purchaseCarIntention.setCarConfigurationCode(
                    parsingString(purchaseCarIntentionresult.get("carConfigurationCode")));
            purchaseCarIntention
                    .setCarConfiguration(parsingString(purchaseCarIntentionresult.get("carConfiguration")));
            purchaseCarIntention.setSalesQuote(parsingString(purchaseCarIntentionresult.get("salesQuote")));
            purchaseCarIntention.setDealPriceIntervalCode(
                    parsingString(purchaseCarIntentionresult.get("dealPriceIntervalCode")));
            purchaseCarIntention
                    .setDealPriceInterval(parsingString(purchaseCarIntentionresult.get("dealPriceInterval")));
            purchaseCarIntention.setPaymentCode(parsingString(purchaseCarIntentionresult.get("paymentCode")));
            purchaseCarIntention.setPayment(parsingString(purchaseCarIntentionresult.get("payment")));
            purchaseCarIntention
                    .setPreorderCount(parsingString(purchaseCarIntentionresult.get("preorderCount")));
            purchaseCarIntention.setPreorderDate(purchaseCarIntentionresult.isNull("preorderDate") ? 0L
                    : purchaseCarIntentionresult.getLong("preorderDate"));
            purchaseCarIntention
                    .setFlowStatusCode(parsingString(purchaseCarIntentionresult.get("flowStatusCode")));
            purchaseCarIntention.setFlowStatus(parsingString(purchaseCarIntentionresult.get("flowStatus")));
            purchaseCarIntention.setDealPossibility(purchaseCarIntentionresult.isNull("dealPossibility") ? ""
                    : parsingString(purchaseCarIntentionresult.get("dealPossibility")));
            purchaseCarIntention.setPurchMotivationCode(
                    parsingString(purchaseCarIntentionresult.get("purchMotivationCode")));
            purchaseCarIntention
                    .setPurchMotivation(parsingString(purchaseCarIntentionresult.get("purchMotivation")));
            purchaseCarIntention.setChassisNo(parsingString(purchaseCarIntentionresult.get("chassisNo")));
            purchaseCarIntention.setEngineNo(parsingString(purchaseCarIntentionresult.get("engineNo")));
            purchaseCarIntention.setLicensePlate(parsingString(purchaseCarIntentionresult.get("licensePlate")));
            purchaseCarIntention.setLicenseProp(parsingString(purchaseCarIntentionresult.get("licenseProp")));
            purchaseCarIntention
                    .setLicensePropCode(parsingString(purchaseCarIntentionresult.get("licensePropCode")));
            purchaseCarIntention.setPickupDate(parsingString(purchaseCarIntentionresult.get("pickupDate")));
            purchaseCarIntention.setPreorderTag(parsingString(purchaseCarIntentionresult.get("preorderTag")));
            purchaseCarIntention.setGiveupTag(purchaseCarIntentionresult.getBoolean("giveupTag"));
            purchaseCarIntention.setGiveupReason(parsingString(purchaseCarIntentionresult.get("giveupReason")));
            //              purchaseCarIntention.setGiveupReasonCode(String
            //                      .valueOf(parsingString(purchaseCarIntentionresult
            //                              .get("giveupReasonCode")));
            purchaseCarIntention.setInvoiceTitle(parsingString(purchaseCarIntentionresult.get("invoiceTitle")));
            purchaseCarIntention
                    .setProjectComment(parsingString(purchaseCarIntentionresult.get("projectComment")));
            // ??
            purchaseCarIntention.setHasActiveOrder(purchaseCarIntentionresult.getBoolean("hasActiveOrder"));
            // ?
            purchaseCarIntention.setHasActiveDrive(purchaseCarIntentionresult.getBoolean("hasActiveDrive"));
            //?
            purchaseCarIntention.setHasUnexePlan(purchaseCarIntentionresult.getBoolean("hasUnexePlan"));
            //???
            purchaseCarIntention.setOrderStatus(parsingString(purchaseCarIntentionresult.get("orderStatus")));
            project.setCustomer(customerEntity);
            project.setPurchaseCarIntention(purchaseCarIntention);

            return project;
        }
        throw new ResponseException();
    } catch (IOException e) {
        Log.e(tag, "Connection network error.", e);
        throw new ResponseException(e);
    } catch (JSONException e) {
        Log.e(tag, "Parsing data error.", e);
        throw new ResponseException(e);
    }
}

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

/**
 * @see com.roiland.crm.core.service.ProjectAPI#createProject(java.lang.String, java.lang.String, com.roiland.crm.core.model.Project, com.roiland.crm.core.model.TracePlan)
 *//* w ww .jav  a 2s  .c o m*/
@Override
public Boolean createProject(String userID, String dealerOrgID, Project project, TracePlan tracePlan)
        throws ResponseException {
    try {
        if (userID == null || dealerOrgID == null) {
            throw new ResponseException("userID or dealerOrgID is null.");
        }
        JSONObject params = new JSONObject();

        params.put("userID", userID);
        params.put("dealerOrgID", dealerOrgID);
        //??
        Log.d(tag, "createProject() >> customerID ================== " + project.getCustomer().getCustomerID());
        params.put("customerID", project.getCustomer().getCustomerID());
        params.put("custName", project.getCustomer().getCustName());
        params.put("custFromCode", StringUtils.convertNull(project.getCustomer().getCustFromCode()));
        params.put("custTypeCode", StringUtils.convertNull(project.getCustomer().getCustTypeCode()));
        params.put("infoFromCode", StringUtils.convertNull(project.getCustomer().getInfoFromCode()));
        params.put("collectFromCode", StringUtils.convertNull(project.getCustomer().getCollectFromCode()));
        params.put("custMobile", StringUtils.convertNull(project.getCustomer().getCustMobile()));
        params.put("custOtherPhone", StringUtils.convertNull(project.getCustomer().getCustOtherPhone()));
        params.put("genderCode", StringUtils.convertNull(project.getCustomer().getGenderCode()));
        params.put("birthday", StringUtils.isEmpty(project.getCustomer().getBirthday()) ? ""
                : Long.parseLong(project.getCustomer().getBirthday()));
        params.put("idTypeCode", StringUtils.convertNull(project.getCustomer().getIdTypeCode()));
        params.put("idNumber", StringUtils.convertNull(project.getCustomer().getIdNumber()));
        params.put("provinceCode", StringUtils.convertNull(project.getCustomer().getProvinceCode()));
        params.put("cityCode", StringUtils.convertNull(project.getCustomer().getCityCode()));
        params.put("districtCode", StringUtils.convertNull(project.getCustomer().getDistrictCode()));
        params.put("qq", StringUtils.convertNull(project.getCustomer().getQq()));
        params.put("address", StringUtils.convertNull(project.getCustomer().getAddress()));
        params.put("postcode", StringUtils.convertNull(project.getCustomer().getPostcode()));
        params.put("email", StringUtils.convertNull(project.getCustomer().getEmail()));
        params.put("convContactTime", StringUtils.convertNull(project.getCustomer().getConvContactTime()));
        params.put("convContactTimeCode",
                StringUtils.convertNull(project.getCustomer().getConvContactTimeCode()));
        params.put("expectContactWayCode",
                StringUtils.convertNull(project.getCustomer().getExpectContactWayCode()));
        params.put("fax", StringUtils.convertNull(project.getCustomer().getFax()));
        params.put("existingCarCode", StringUtils.convertNull(project.getCustomer().getExistingCarCode()));
        params.put("existingCar", StringUtils.convertNull(project.getCustomer().getExistingCar()));
        params.put("existingCarBrand", StringUtils.convertNull(project.getCustomer().getExistingCarBrand()));
        params.put("industryCode", StringUtils.convertNull(project.getCustomer().getIndustryCode()));
        params.put("positionCode", StringUtils.convertNull(project.getCustomer().getPositionCode()));
        params.put("educationCode", StringUtils.convertNull(project.getCustomer().getEducationCode()));
        params.put("industry", StringUtils.convertNull(project.getCustomer().getIndustry()));
        params.put("position", StringUtils.convertNull(project.getCustomer().getPosition()));
        params.put("education", StringUtils.convertNull(project.getCustomer().getEducation()));
        params.put("custInterestCode1", StringUtils.convertNull(project.getCustomer().getCustInterestCode1()));
        params.put("custInterestCode2", StringUtils.convertNull(project.getCustomer().getCustInterestCode2()));
        params.put("custInterestCode3", StringUtils.convertNull(project.getCustomer().getCustInterestCode3()));
        params.put("existLisenPlate", StringUtils.convertNull(project.getCustomer().getExistLisenPlate()));
        params.put("enterpTypeCode", StringUtils.convertNull(project.getCustomer().getEnterpTypeCode()));
        params.put("enterpPeopleCountCode",
                StringUtils.convertNull(project.getCustomer().getEnterpPeopleCountCode()));
        params.put("registeredCapitalCode",
                StringUtils.convertNull(project.getCustomer().getRegisteredCapitalCode()));
        params.put("compeCarModelCode", project.getCustomer().getCompeCarModelCode());
        params.put("rebuyStoreCustTag", project.getCustomer().getRebuyStoreCustTag());
        params.put("rebuyOnlineCustTag", project.getCustomer().getRebuyOnlineCustTag());
        params.put("changeCustTag", project.getCustomer().getChangeCustTag());
        params.put("loanCustTag", project.getCustomer().getLoanCustTag());
        params.put("headerQuartCustTag", project.getCustomer().getHeaderQuartCustTag());
        params.put("regularCustTag", project.getCustomer().getRegularCustTag());
        params.put("regularCustCode", StringUtils.convertNull(project.getCustomer().getRegularCustCode()));
        params.put("regularCust", StringUtils.convertNull(project.getCustomer().getRegularCust()));
        params.put("bigCustTag", project.getCustomer().getBigCustTag());
        params.put("bigCusts", StringUtils.convertNull(project.getCustomer().getBigCusts()));
        params.put("bigCustsCode", StringUtils.convertNull(project.getCustomer().getBigCustsCode()));
        params.put("custComment", StringUtils.convertNull(project.getCustomer().getCustComment()));
        params.put("dormancy",
                (project.getCustomer().getDormancy() != null ? project.getCustomer().getDormancy() : false));
        params.put("updateCustInfo", project.getCustomer().isUpdateCustInfo());

        params.put("brandCode", StringUtils.convertNull(project.getPurchaseCarIntention().getBrandCode()));
        params.put("modelCode", StringUtils.convertNull(project.getPurchaseCarIntention().getModelCode()));
        params.put("outsideColorCode",
                StringUtils.convertNull(project.getPurchaseCarIntention().getOutsideColorCode()));
        params.put("insideColorCode",
                StringUtils.convertNull(project.getPurchaseCarIntention().getInsideColorCode()));
        params.put("insideColorCheck", project.getPurchaseCarIntention().isInsideColorCheck());
        params.put("carConfigurationCode",
                StringUtils.convertNull(project.getPurchaseCarIntention().getCarConfigurationCode()));
        params.put("salesQuote", "".equals(project.getPurchaseCarIntention().getSalesQuote()) ? null
                : project.getPurchaseCarIntention().getSalesQuote());
        params.put("dealPriceInterval",
                StringUtils.convertNull(project.getPurchaseCarIntention().getDealPriceInterval()));
        params.put("dealPriceIntervalCode",
                StringUtils.convertNull(project.getPurchaseCarIntention().getDealPriceIntervalCode()));
        params.put("payment", StringUtils.convertNull(project.getPurchaseCarIntention().getPayment()));
        params.put("paymentCode", StringUtils.convertNull(project.getPurchaseCarIntention().getPaymentCode()));
        params.put("preorderCount",
                StringUtils.isEmpty(project.getPurchaseCarIntention().getPreorderCount()) ? 1
                        : Integer.parseInt(project.getPurchaseCarIntention().getPreorderCount()));
        params.put("preorderDate", project.getPurchaseCarIntention().getPreorderDate());
        params.put("flowStatusCode",
                StringUtils.convertNull(project.getPurchaseCarIntention().getFlowStatusCode()));
        params.put("flowStatus", StringUtils.convertNull(project.getPurchaseCarIntention().getFlowStatus()));
        params.put("dealPossibility",
                StringUtils.convertNull(project.getPurchaseCarIntention().getDealPossibility()));
        params.put("purchMotivationCode",
                "".equals(project.getPurchaseCarIntention().getPurchMotivationCode()) ? null
                        : project.getPurchaseCarIntention().getPurchMotivationCode());
        params.put("chassisNo", StringUtils.convertNull(project.getPurchaseCarIntention().getChassisNo()));
        params.put("engineNo", StringUtils.convertNull(project.getPurchaseCarIntention().getEngineNo()));
        params.put("licensePlate",
                StringUtils.convertNull(project.getPurchaseCarIntention().getLicensePlate()));
        params.put("licensePropCode",
                StringUtils.convertNull(project.getPurchaseCarIntention().getLicensePropCode()));
        params.put("licenseProp", StringUtils.convertNull(project.getPurchaseCarIntention().getLicenseProp()));
        params.put("pickupDate", parsingLong(project.getPurchaseCarIntention().getPickupDate()));
        if (parsingLong(project.getPurchaseCarIntention().getPickupDate()) == 0)
            params.put("pickupDate", null);
        else
            params.put("pickupDate", parsingLong(project.getPurchaseCarIntention().getPickupDate()));
        params.put("preorderTag", Boolean.parseBoolean(project.getPurchaseCarIntention().getPreorderTag()));
        params.put("giveupTag",
                project.getPurchaseCarIntention().isGiveupTag() != null
                        ? project.getPurchaseCarIntention().isGiveupTag()
                        : null);
        params.put("giveupReason",
                StringUtils.convertNull(project.getPurchaseCarIntention().getGiveupReason()));
        params.put("giveupReasonCode",
                StringUtils.convertNull(project.getPurchaseCarIntention().getGiveupReasonCode()));
        params.put("invoiceTitle",
                StringUtils.convertNull(project.getPurchaseCarIntention().getInvoiceTitle()));
        params.put("projectComment",
                StringUtils.convertNull(project.getPurchaseCarIntention().getProjectComment()));
        params.put("isInsideColorCheck",
                project.getPurchaseCarIntention().isInsideColorCheck() != null
                        ? project.getPurchaseCarIntention().isInsideColorCheck() ? "1" : "0"
                        : "0");
        params.put("abandonFlag",
                project.getPurchaseCarIntention().getAbandonFlag() != null
                        ? project.getPurchaseCarIntention().getAbandonFlag()
                        : "0");

        if (tracePlan != null) {
            params.put("activityTypeCode", tracePlan.getActivityTypeCode());
            params.put("executeTime", tracePlan.getExecuteTime());
            params.put("executeStatus", tracePlan.getExecuteStatus());
            params.put("executeStatusCode", tracePlan.getExecuteStatusCode());
            params.put("activityContent", StringUtils.convertNull(tracePlan.getActivityContent()));
            params.put("contactResultCode", StringUtils.convertNull(tracePlan.getContactResultCode()));
            params.put("custFeedback", StringUtils.convertNull(tracePlan.getCustFeedback()));
            params.put("collcustomerId", tracePlan.getCollcustomerId());
        }
        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_CREATE_PROJECT), params, null);

        if (response.isSuccess()) {
            String data = getSimpleString(response);
            JSONObject result = new JSONObject(data);

            String node = null;
            String error = null;
            JSONArray nodeArray = result.names();
            if (nodeArray != null) {
                for (int i = 0; i < nodeArray.length(); i++) {
                    node = nodeArray.get(i).toString();
                    if (node.equalsIgnoreCase("success")) {

                        Boolean success = Boolean.parseBoolean(result.getString("success"));
                        if (success) {
                            project.setProjectID(result.getString("projectID"));
                            project.getCustomer().setProjectID(result.getString("projectID"));
                            project.getCustomer().setCustomerID(result.getString("customerID"));
                            return true;
                        }
                    } else if (node.equalsIgnoreCase("validate_error")) {
                        error = parsingValidation(result.getJSONObject(node));
                        throw new ResponseException(error);
                    }
                }
            }
        }
        throw new ResponseException(500);
    } catch (IOException e) {
        Log.e(tag, "Connection network error.", e);
        throw new ResponseException(e);
    } catch (JSONException e) {
        Log.e(tag, "Parsing data error.", e);
        throw new ResponseException(e);
    }
}

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

/**
 * @see com.roiland.crm.core.service.ProjectAPI#updateProjectInfo(java.lang.String, java.lang.String, com.roiland.crm.core.model.Project)
 *//*from w  w  w .java  2  s.  c o  m*/
@Override
public Boolean updateProjectInfo(String userID, String dealerOrgID, Project project) throws ResponseException {
    try {
        if (userID == null || dealerOrgID == null) {
            throw new ResponseException("userID or dealerOrgID is null.");
        }
        JSONObject params = new JSONObject();
        params.put("userID", userID);
        params.put("dealerOrgID", dealerOrgID);
        params.put("projectID", project.getCustomer().getProjectID());
        params.put("customerID", project.getCustomer().getCustomerID());

        params.put("custName", project.getCustomer().getCustName());
        params.put("custFromCode", project.getCustomer().getCustFromCode());
        params.put("custTypeCode", project.getCustomer().getCustTypeCode());
        params.put("infoFromCode", project.getCustomer().getInfoFromCode());
        params.put("collectFromCode", project.getCustomer().getCollectFromCode());
        params.put("custMobile", project.getCustomer().getCustMobile());
        params.put("custOtherPhone", project.getCustomer().getCustOtherPhone());
        params.put("genderCode", project.getCustomer().getGenderCode());
        Log.d(tag, "updateProjectInfo() >> birthday ================== " + project.getCustomer().getBirthday());
        params.put("birthday", StringUtils.isEmpty(project.getCustomer().getBirthday()) ? ""
                : Long.parseLong(project.getCustomer().getBirthday()));
        params.put("idTypeCode", project.getCustomer().getIdTypeCode());
        params.put("idNumber", project.getCustomer().getIdNumber());
        params.put("provinceCode", project.getCustomer().getProvinceCode());
        params.put("cityCode", project.getCustomer().getCityCode());
        params.put("districtCode", project.getCustomer().getDistrictCode());
        params.put("qq", project.getCustomer().getQq());
        params.put("address", project.getCustomer().getAddress());
        params.put("postcode", project.getCustomer().getPostcode());
        params.put("email", project.getCustomer().getEmail());
        params.put("convContactTime", project.getCustomer().getConvContactTime());
        params.put("convContactTimeCode", project.getCustomer().getConvContactTimeCode());
        params.put("expectContactWayCode", project.getCustomer().getExpectContactWayCode());
        params.put("fax", project.getCustomer().getFax());
        params.put("existingCarCode", project.getCustomer().getExistingCarCode());
        params.put("existingCar", project.getCustomer().getExistingCar());
        params.put("existingCarBrand", project.getCustomer().getExistingCarBrand());
        params.put("industryCode", project.getCustomer().getIndustryCode());
        params.put("positionCode", project.getCustomer().getPositionCode());
        params.put("educationCode", project.getCustomer().getEducationCode());
        params.put("industry", project.getCustomer().getIndustry());
        params.put("position", project.getCustomer().getPosition());
        params.put("education", project.getCustomer().getEducation());
        params.put("custInterestCode1", project.getCustomer().getCustInterestCode1());
        params.put("custInterestCode2", project.getCustomer().getCustInterestCode2());
        params.put("custInterestCode3", project.getCustomer().getCustInterestCode3());
        params.put("existLisenPlate", project.getCustomer().getExistLisenPlate());
        params.put("enterpTypeCode", project.getCustomer().getEnterpTypeCode());
        params.put("enterpPeopleCountCode", project.getCustomer().getEnterpPeopleCountCode());
        params.put("registeredCapitalCode", project.getCustomer().getRegisteredCapitalCode());
        params.put("compeCarModelCode", project.getCustomer().getCompeCarModelCode());
        params.put("rebuyStoreCustTag", project.getCustomer().getRebuyStoreCustTag());
        params.put("rebuyOnlineCustTag", project.getCustomer().getRebuyOnlineCustTag());
        params.put("changeCustTag", project.getCustomer().getChangeCustTag());
        params.put("loanCustTag", project.getCustomer().getLoanCustTag());
        params.put("headerQuartCustTag", project.getCustomer().getHeaderQuartCustTag());
        params.put("regularCustTag", project.getCustomer().getRegularCustTag());
        params.put("regularCustCode", StringUtils.convertNull(project.getCustomer().getRegularCustCode()));
        params.put("regularCust", StringUtils.convertNull(project.getCustomer().getRegularCust()));
        params.put("bigCustTag", project.getCustomer().getBigCustTag());
        params.put("bigCusts", project.getCustomer().getBigCusts());
        params.put("bigCustsCode", project.getCustomer().getBigCustsCode());
        params.put("custComment", project.getCustomer().getCustComment());
        params.put("dormancy",
                (project.getCustomer().getDormancy() != null ? project.getCustomer().getDormancy() : false));
        params.put("brandCode", project.getPurchaseCarIntention().getBrandCode());
        params.put("modelCode", project.getPurchaseCarIntention().getModelCode());
        params.put("outsideColorCode", project.getPurchaseCarIntention().getOutsideColorCode());
        params.put("insideColorCode", project.getPurchaseCarIntention().getInsideColorCode());
        params.put("insideColorCheck", project.getPurchaseCarIntention().isInsideColorCheck() ? true : false);
        params.put("carConfigurationCode", project.getPurchaseCarIntention().getCarConfigurationCode());
        params.put("salesQuote", "".equals(project.getPurchaseCarIntention().getSalesQuote()) ? null
                : project.getPurchaseCarIntention().getSalesQuote());
        params.put("dealPriceInterval", project.getPurchaseCarIntention().getDealPriceInterval());
        params.put("dealPriceIntervalCode", project.getPurchaseCarIntention().getDealPriceIntervalCode());
        params.put("payment", project.getPurchaseCarIntention().getPayment());
        params.put("paymentCode", project.getPurchaseCarIntention().getPaymentCode());
        params.put("preorderCount",
                StringUtils.isEmpty(project.getPurchaseCarIntention().getPreorderCount()) ? 1
                        : Integer.parseInt(project.getPurchaseCarIntention().getPreorderCount()));
        params.put("preorderDate", project.getPurchaseCarIntention().getPreorderDate());
        params.put("flowStatusCode", project.getPurchaseCarIntention().getFlowStatusCode());
        params.put("flowStatus", project.getPurchaseCarIntention().getFlowStatus());
        params.put("dealPossibility", project.getPurchaseCarIntention().getDealPossibility());
        params.put("purchMotivationCode",
                "".equals(project.getPurchaseCarIntention().getPurchMotivationCode()) ? null
                        : project.getPurchaseCarIntention().getPurchMotivationCode());
        params.put("chassisNo", project.getPurchaseCarIntention().getChassisNo());
        params.put("engineNo", project.getPurchaseCarIntention().getEngineNo());
        params.put("licensePlate", project.getPurchaseCarIntention().getLicensePlate());
        params.put("licensePropCode", project.getPurchaseCarIntention().getLicensePropCode());
        params.put("licenseProp", project.getPurchaseCarIntention().getLicenseProp());
        params.put("pickupDate", parsingLong(project.getPurchaseCarIntention().getPickupDate()));
        if (parsingLong(project.getPurchaseCarIntention().getPickupDate()) == 0)
            params.put("pickupDate", "null");
        else
            params.put("pickupDate", parsingLong(project.getPurchaseCarIntention().getPickupDate()));
        params.put("preorderTag", Boolean.parseBoolean(project.getPurchaseCarIntention().getPreorderTag()));
        params.put("giveupTag",
                project.getPurchaseCarIntention().isGiveupTag() != null
                        ? project.getPurchaseCarIntention().isGiveupTag()
                        : false);
        params.put("giveupReason", project.getPurchaseCarIntention().getGiveupReason());
        params.put("giveupReasonCode", project.getPurchaseCarIntention().getGiveupReasonCode());
        params.put("invoiceTitle", project.getPurchaseCarIntention().getInvoiceTitle());
        params.put("projectComment", project.getPurchaseCarIntention().getProjectComment());
        params.put("isInsideColorCheck",
                project.getPurchaseCarIntention().isInsideColorCheck() != null
                        ? project.getPurchaseCarIntention().isInsideColorCheck() ? "1" : "0"
                        : "0");

        RLHttpResponse response = getHttpClient()
                .executePostJSON((getURLAddress(URLContact.METHOD_UPDATE_PROJECT_INFO)), params, null);
        if (response.isSuccess()) {
            String data = getSimpleString(response);
            JSONObject result = new JSONObject(data);
            String node = null;
            String error = null;
            JSONArray nodeArray = result.names();
            if (nodeArray != null) {
                for (int i = 0; i < nodeArray.length(); i++) {
                    node = nodeArray.get(i).toString();
                    if (node.equalsIgnoreCase("success")) {

                        Boolean success = Boolean.parseBoolean(result.getString("success"));
                        if (success) {
                            return true;
                        }
                    } else if (node.equalsIgnoreCase("validate_error")) {
                        error = parsingValidation(result.getJSONObject(node));
                        throw new ResponseException(error);
                    }
                }
            }
        }
        throw new ResponseException(500);
    } catch (IOException e) {
        Log.e(tag, "Connection network error.", e);
        throw new ResponseException(e);
    } catch (JSONException e) {
        Log.e(tag, "Parsing data error.", e);
        throw new ResponseException(e);
    }

}

From source file:com.roiland.crm.sm.core.service.impl.ProjectAPIImpl.java

/**
 * /*  www  .j  a  va 2 s .  co m*/
 * @see com.roiland.crm.sm.core.service.ProjectAPI#getOppoFunnel(long, long)
 */
public OppoFunnel getOppoFunnel(long startDate, long endDate) throws ResponseException {
    //??
    OppoFunnel oppoFunnel = null;
    try {
        JSONObject params = new JSONObject();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_GET_SEARCH_PROJECT_FUNNEL), params, null);
        if (response.isSuccess()) {
            JSONObject jsonBean = new JSONObject(getSimpleString(response));
            JSONObject info = jsonBean.getJSONObject("info");
            //??
            oppoFunnel = new OppoFunnel();
            oppoFunnel.setRecordNum(parsingLong(info.getString("recordNum")));
            oppoFunnel.setRevenueNum(parsingLong(info.getString("revenueNum")));
            oppoFunnel.setWeightTotalCount(parsingIntFloat(info.getString("winNum")));
            oppoFunnel.setFirstNum(parsingLong(info.getString("firstNum")));
            oppoFunnel.setNeedNum(parsingLong(info.getString("needNum")));
            oppoFunnel.setDisplayNum(parsingLong(info.getString("displayNum")));
            oppoFunnel.setDriveNum(parsingLong(info.getString("driveNum")));
            oppoFunnel.setOrderNum(parsingLong(info.getString("orderNum")));
            oppoFunnel.setPriceNum(parsingLong(info.getString("priceNum")));
        }

    } catch (IOException e) {
        throw new ResponseException(e);
    } catch (JSONException e) {
        throw new ResponseException(e);
    }
    return oppoFunnel;
}

From source file:com.tapfortap.phonegap.TapForTapPhoneGapPlugin.java

private void setAdOptions(JSONObject options) throws JSONException {
    adView.setLayoutParams(getLayoutParamsForOptions(options));
    if (options.has("gender")) {
        String gender = options.getString("gender");
        if (gender.equals("male"))
            TapForTap.setGender(TapForTap.Gender.MALE);
        else if (gender.equals("female"))
            TapForTap.setGender(TapForTap.Gender.FEMALE);
        else/*w  ww  .j  a  va 2  s .  co m*/
            TapForTap.setGender(TapForTap.Gender.NONE);
    }
    if (options.has("age")) {
        TapForTap.setAge(options.getInt("age"));
    }
    if (options.has("location")) {
        JSONObject locationObject = options.getJSONObject("location");
        Location location = new Location("user");
        location.setLatitude(locationObject.getDouble("latitude"));
        location.setLongitude(locationObject.getDouble("longitude"));
        TapForTap.setLocation(location);
    }
}

From source file:xanthanov.droid.funrun.PlaceSearcher.java

private GooglePlace parseGmapResult(JSONObject gmapResult) throws JSONException {
    String name = gmapResult.getString("name");
    String icon = gmapResult.getString("icon");

    JSONObject coords = gmapResult.getJSONObject("geometry").getJSONObject("location");

    String lat = coords.getString("lat");
    String lng = coords.getString("lng");

    double[] latLng = new double[] { Double.parseDouble(lat), Double.parseDouble(lng) };

    URL iconUrl = null;/*from   ww  w.  j a va2s . co m*/

    try {
        iconUrl = new URL(icon);
    } catch (MalformedURLException e) {
        System.err.println("Google Maps API returned invalid URL string: " + icon);
        e.printStackTrace();
        return null;
    }

    return new GooglePlace(name, latLng, iconUrl);
}

From source file:fi.harism.lucidchat.api.ChatConnection.java

/**
 * Handle server event messages.// www .  j  av a2 s  .c o m
 */
private void handleEvent(String message) {
    try {
        // We receive always JSON messages.
        JSONObject json = new JSONObject(message);
        // Get event type from JSON.
        String event = json.optString("event");

        // Handle session_created event.
        if (event.equals("session_created")) {

            // Here we expect that server sends user_auth only when new
            // session is created. In case where old session was continues
            // user_auth ought not to be present.
            if (!json.has("user_auth")) {
                // Notify server about connection.
                mObserver.onServerMessage(new Message(Message.TYPE_LOG,
                        "Session resumed userId=" + mUserId + " sessionId=" + mSessionId));
                mObserver.onConnect(mUserId, mUserAuth, mSessionId);
            } else {
                // New session was created.
                mUserId = json.getString("user_id");
                mUserAuth = json.getString("user_auth");
                mSessionId = json.getString("session_id");
                mObserver.onServerMessage(new Message(Message.TYPE_LOG,
                        "Session created userId=" + mUserId + " sessionId=" + mSessionId));
                mObserver.onConnect(mUserId, mUserAuth, mSessionId);
                // If autojoin is enabled send join message.
                if (mAutojoin) {
                    sendJoinChannel(NINCHAT_LOUNGE);
                }
            }
        }

        // Handle user_updated and user_found events.
        if (event.equals("user_updated") || event.equals("user_found")) {
            String userId = json.getString("user_id");
            // If update was sent for ourself.
            if (userId.equals(mUserId)) {
                // We do nothing on updates sent to self at the moment.
            } else {
                // Notify observer about user updated event.
                JSONObject userAttrs = json.getJSONObject("user_attrs");
                String name = userAttrs.optString("name");
                String realName = userAttrs.optString("realname");
                boolean connected = userAttrs.optBoolean("connected");
                mObserver.onUserUpdated(new User(userId, name, realName, connected));
            }
        }

        // Handle channel_updated event.
        if (event.equals("channel_updated")) {
            String channelId = json.getString("channel_id");
            JSONObject channelAttrs = json.getJSONObject("channel_attrs");
            String name = channelAttrs.optString("name");
            String topic = channelAttrs.optString("topic");
            mObserver.onChannelUpdated(new Channel(channelId, name, topic));
        }

        // Handle search_results event.
        if (event.equals("search_results")) {
            mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Search results event"));
            Vector<Channel> channelList = new Vector<Channel>();
            // Parse channels from search results.
            JSONObject channels = json.optJSONObject("channels");
            if (channels != null) {
                JSONArray names = channels.names();
                for (int i = 0; i < names.length(); ++i) {
                    String channelId = names.getString(i);
                    JSONObject channelAttrs = channels.getJSONObject(channelId).getJSONObject("channel_attrs");
                    String name = channelAttrs.optString("name");
                    String topic = channelAttrs.optString("topic");
                    channelList.add(new Channel(channelId, name, topic));
                }
            }
            // Parse users from search results.
            Vector<User> userList = new Vector<User>();
            JSONObject users = json.optJSONObject("users");
            if (users != null) {
                JSONArray names = users.names();
                for (int i = 0; i < names.length(); ++i) {
                    String userId = names.getString(i);
                    if (!userId.equals(mUserId)) {
                        JSONObject user = users.getJSONObject(userId);
                        String name = user.optString("name");
                        String realName = user.optString("realname");
                        boolean connected = user.optBoolean("connected");
                        userList.add(new User(userId, name, realName, connected));
                    }
                }
            }
            mObserver.onSearchResults(channelList, userList);
        }

        // Handle channel_joined event.
        if (event.equals("channel_joined")) {
            mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Channel joined event"));

            String channelId = json.getString("channel_id");
            Vector<User> userList = new Vector<User>();
            JSONObject channelMembers = json.getJSONObject("channel_members");
            JSONArray names = channelMembers.names();
            for (int i = 0; i < names.length(); ++i) {
                String userId = names.getString(i);
                JSONObject userAttrs = channelMembers.getJSONObject(userId).getJSONObject("user_attrs");
                if (!userId.equals(mUserId)) {
                    String name = userAttrs.optString("name");
                    String realName = userAttrs.optString("realname");
                    boolean connected = userAttrs.optBoolean("connected");
                    userList.add(new User(userId, name, realName, connected));
                }
            }

            JSONObject channelAttrs = json.getJSONObject("channel_attrs");
            String name = channelAttrs.getString("name");
            String topic = channelAttrs.getString("topic");

            mObserver.onChannelJoined(new Channel(channelId, name, topic), userList);
        }

        // Message receiving happens with 2 callbacks. First
        // message_received is sent from server and then an empty JSON with
        // message only.
        if (event.equals("message_received")) {
            // Check message_type. We handle only text messages.
            if (json.optString("message_type").equals("ninchat.com/text")) {
                mMessage = json;
            }
            if (json.optString("message_type").equals("ninchat.com/info")) {
                mMessage = json;
            }
        }
        // Second part of text message receiving.
        if (mMessage != null && mMessage.optString("message_type").equals("ninchat.com/text")
                && json.has("text")) {
            // Message time is in seconds after epoch.
            long messageTime = mMessage.getLong("message_time") * 1000;
            String messageUserName = mMessage.getString("message_user_name");
            String channelId = mMessage.optString("channel_id");
            String userId = mMessage.optString("user_id");
            String text = json.getString("text");
            mMessage = null;

            // If channel_id exists notify observer about channel message.
            if (channelId.length() > 0) {
                mObserver.onChannelMessage(channelId,
                        new Message(Message.TYPE_CONVERSATION, messageTime, messageUserName, text));
            }
            // If user_id exists notify observer about private message.
            if (userId.length() > 0) {
                User user = new User(userId, messageUserName, "", true);
                mObserver.onUserMessage(user,
                        new Message(Message.TYPE_CONVERSATION, messageTime, messageUserName, text));
            }
        }
        if (mMessage != null && mMessage.optString("message_type").equals("ninchat.com/info")
                && json.has("info")) {
            String info = json.getString("info");
            if (info.equals("join")) {
                String channelId = mMessage.getString("channel_id");
                String userId = json.getString("user_id");
                String userName = json.getString("user_name");
                mObserver.onInfoJoin(channelId, userId, userName);
            }
            if (info.equals("part")) {
                String channelId = mMessage.getString("channel_id");
                String userId = json.getString("user_id");
                String userName = json.getString("user_name");
                mObserver.onInfoPart(channelId, userId, userName);
            }

            mMessage = null;
        }

        // Handle channel_parted event.
        if (event.equals("channel_parted")) {
            String channelId = json.getString("channel_id");
            mObserver.onChannelParted(channelId);
        }

        // Handle channel_member_joined.
        if (event.equals("channel_member_joined")) {
            String channelId = json.getString("channel_id");
            String userId = json.getString("user_id");
            JSONObject userAttrs = json.getJSONObject("user_attrs");
            String name = userAttrs.getString("name");
            String realname = userAttrs.optString("realname");
            boolean connected = userAttrs.optBoolean("connected");
            mObserver.onUserJoin(channelId, new User(userId, name, realname, connected));
        }

        // Handle channel_member_parted.
        if (event.equals("channel_member_parted")) {
            String channelId = json.getString("channel_id");
            String userId = json.getString("user_id");
            mObserver.onUserPart(channelId, userId);
        }

        // Handle second phase of delete_user.
        if (event.equals("user_deleted")) {
            mWSC.disconnect();
        }

    } catch (JSONException ex) {
        ex.printStackTrace();
    }
}

From source file:com.kwang.sunshine.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from   w  ww  .j  av a 2 s .c o m*/
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";
    final String OWM_COORD_LAT = "lat";
    final String OWM_COORD_LONG = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_DATETIME = "dt";
    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
    String cityName = cityJson.getString(OWM_CITY_NAME);
    JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD);
    double cityLatitude = coordJSON.getLong(OWM_COORD_LAT);
    double cityLongitude = coordJSON.getLong(OWM_COORD_LONG);

    Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

    // Insert the location into the database.
    long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    // Get and insert the new weather information into the database
    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

    String[] resultStrs = new String[numDays];

    for (int i = 0; i < weatherArray.length(); i++) {
        // These are the values that will be collected.

        long dateTime;
        double pressure;
        int humidity;
        double windSpeed;
        double windDirection;

        double high;
        double low;

        String description;
        int weatherId;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        dateTime = dayForecast.getLong(OWM_DATETIME);

        pressure = dayForecast.getDouble(OWM_PRESSURE);
        humidity = dayForecast.getInt(OWM_HUMIDITY);
        windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
        windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

        // Description is in a child array called "weather", which is 1 element long.
        // That element also contains a weather code.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);
        weatherId = weatherObject.getInt(OWM_WEATHER_ID);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);

        ContentValues weatherValues = new ContentValues();

        weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID);
        weatherValues.put(WeatherEntry.COLUMN_DATETEXT,
                WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
        weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
        weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
        weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
        weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
        weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
        weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
        weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
        weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

        cVVector.add(weatherValues);

        String highAndLow = formatHighLows(high, low);
        String day = getReadableDateString(dateTime);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    if (cVVector.size() > 0) {
        ContentValues[] cvArray = new ContentValues[cVVector.size()];
        cVVector.toArray(cvArray);
        int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data");
        // Use a DEBUG variable to gate whether or not you do this, so you can easily
        // turn it on and off, and so that it's easy to see what you can rip out if
        // you ever want to remove it.
        if (DEBUG) {
            Cursor weatherCursor = mContext.getContentResolver().query(WeatherEntry.CONTENT_URI, null, null,
                    null, null);

            if (weatherCursor.moveToFirst()) {
                ContentValues resultValues = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(weatherCursor, resultValues);
                Log.v(LOG_TAG, "Query succeeded! **********");
                for (String key : resultValues.keySet()) {
                    Log.v(LOG_TAG, key + ": " + resultValues.getAsString(key));
                }
            } else {
                Log.v(LOG_TAG, "Query failed! :( **********");
            }
        }
    }

    return resultStrs;
}

From source file:ai.susi.mind.SusiThought.java

/**
 * create a clone of a json object as a SusiThought object
 * @param json the 'other' thought, probably an exported and re-imported thought
 *///w  w w. j a  v a 2 s  .  c o  m
public SusiThought(JSONObject json) {
    this();
    if (json.has(this.metadata_name))
        this.put(this.metadata_name, json.getJSONObject(this.metadata_name));
    if (json.has(this.data_name))
        this.setData(json.getJSONArray(this.data_name));
    if (json.has("actions"))
        this.put("actions", json.getJSONArray("actions"));
}

From source file:org.wso2.carbon.identity.authenticator.instagram.InstagramAuthenticator.java

/**
 * Get subject attributes.// w w  w.j  av a  2 s. c  o  m
 *
 * @param userObj                 OAuthClientResponse
 * @param authenticatorProperties Map<String, String>
 * @return Map<ClaimMapping, String> Claim mappings.
 */
@Override
protected Map<ClaimMapping, String> getSubjectAttributes(OAuthClientResponse userObj,
        Map<String, String> authenticatorProperties) {
    Map<ClaimMapping, String> claims = new HashMap<>();
    try {
        String accessToken = userObj.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN);
        String url = getUserInfoEndpoint(userObj, authenticatorProperties);
        String json = sendRequest(url, accessToken);
        JSONObject obj = new JSONObject(json);
        String userData = obj.getJSONObject("data").toString();
        if (StringUtils.isBlank(json)) {
            if (log.isDebugEnabled()) {
                log.debug("Unable to fetch user claims. Proceeding without user claims");
            }
            return claims;
        }
        Map<String, Object> jsonObject = JSONUtils.parseJSON(userData);
        for (Map.Entry<String, Object> data : jsonObject.entrySet()) {
            String key = data.getKey();
            claims.put(ClaimMapping.build(key, key, null, false), jsonObject.get(key).toString());
            if (log.isDebugEnabled()) {
                log.debug("Adding claims from end-point data mapping : " + key + " - "
                        + jsonObject.get(key).toString());
            }
        }
    } catch (Exception e) {
        log.error("Error occurred while accessing user info endpoint", e);
    }
    return claims;
}