Example usage for org.json JSONObject names

List of usage examples for org.json JSONObject names

Introduction

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

Prototype

public JSONArray names() 

Source Link

Document

Produce a JSONArray containing the names of the elements of this JSONObject.

Usage

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

@Override
public Contacter updateContacter(String userID, String dealerOrgID, Contacter contacter)
        throws ResponseException {
    // ?// w w  w .  j  a va  2 s  . com
    Contacter returnContacter = 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", contacter.getProjectID());
        params.put("customerID", contacter.getCustomerID());
        params.put("contacterID", contacter.getContacterID());
        params.put("contName", contacter.getContName());
        params.put("contMobile", contacter.getContMobile());
        params.put("contOtherPhone", contacter.getContOtherPhone());
        params.put("isPrimContanter", Boolean.parseBoolean(contacter.getIsPrimContanter()));
        params.put("contGenderCode", contacter.getContGenderCode());
        params.put("contBirthday", contacter.getContBirthday());
        params.put("idNumber", contacter.getIdNumber());
        params.put("ageScopeCode", contacter.getAgeScopeCode());
        params.put("contTypeCode", contacter.getContTypeCode());
        params.put("contRelationCode", contacter.getContRelationCode());
        if (contacter.getLicenseValid() == 0)
            params.put("licenseValid", null);
        else
            params.put("licenseValid", contacter.getLicenseValid());

        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_UPDATE_CONTACTER), params, null);

        if (response.isSuccess()) {
            returnContacter = contacter;
            JSONObject result = new JSONObject(getSimpleString(response));
            // ??
            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) {
                        //                             // ?ID
                        //                                returnContacter.setContacterID(result.getString("contacterID"));
                        //                            }
                    } else if (node.equalsIgnoreCase("validate_error")) {
                        error = parsingValidation(result.getJSONObject(node));
                        throw new ResponseException(error);
                    }
                }
            }
            return returnContacter;
        }
        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.getMessage());
    }
}

From source file:org.official.json.CDL.java

/**
 * Produce a comma delimited text from a JSONArray of JSONObjects. The
 * first row will be a list of names obtained by inspecting the first
 * JSONObject.//from  w  ww . j a v  a2 s .c om
 * @param ja A JSONArray of JSONObjects.
 * @return A comma delimited text.
 * @throws JSONException
 */
public static String toString(JSONArray ja) throws JSONException {
    JSONObject jo = ja.optJSONObject(0);
    if (jo != null) {
        JSONArray names = jo.names();
        if (names != null) {
            return rowToString(names) + toString(names, ja);
        }
    }
    return null;
}

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)
 *//*ww w  .  j  a v a  2  s  .c  om*/
@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)
 *//* w  w  w.java2  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:fi.harism.lucidchat.api.ChatConnection.java

/**
 * Handle server event messages.//w  w w .j  ava  2  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:de.eorganization.crawler.server.servlets.JSONImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {//w  w  w  .j  a  v a2 s .  c o  m

        resp.setContentType("text/plain");

        InputStream stream = req.getInputStream();

        log.info("Got Upload " + req.getContentType() + " (" + req.getContentLength() + " bytes) from "
                + req.getRemoteAddr());

        String amiId = req.getHeader("AMI-ID");
        log.info("Got AMI ID:" + amiId);
        String repository = req.getHeader("REPO");
        log.info("Got REPO:" + repository);
        if (amiId == null || repository == null || "".equals(amiId) || "".equals(repository)) {
            log.severe("AMI ID and REPO HTTP Header required.");
            return;
        }

        // Gson gson = new Gson();
        // log.info("Parsed Gson " + gson.fromJson(new
        // InputStreamReader(stream), JsonObject.class));

        String jsonString = IOUtils.toString(stream);
        log.info("Got JSON String "
                + jsonString.substring(0, jsonString.length() > 128 ? 128 : jsonString.length() - 1));
        JSONObject json = new JSONObject();
        try {
            json = new JSONObject(jsonString);
            log.fine("Parsed Json " + json);
            log.finer("Json has keys: " + json.names());
        } catch (JSONException e) {
            log.severe("No JSON sent or wrong format.");
            return;
        }

        JSONObject software = json.optJSONObject("software");
        if (software != null) {
            log.finer("Software JSON " + software);

            JSONArray softwareNames = software.names();
            log.finer("Key Array JSON " + softwareNames);
            for (int i = 0; i < softwareNames.length(); i++) {
                log.fine("software " + softwareNames.getString(i) + " with version "
                        + software.getJSONObject(softwareNames.getString(i)).getString("version"));

                Map<String, String> softAttributes = new HashMap<String, String>();
                JSONArray softwareAttributes = software.getJSONObject(softwareNames.getString(i)).names();
                for (int j = 0; j < softwareAttributes.length(); j++)
                    softAttributes.put(softwareAttributes.getString(j),
                            software.getJSONObject(softwareNames.getString(i))
                                    .getString(softwareAttributes.getString(j)));

                Software soft = AmiManager.saveSoftware(amiId, repository, softwareNames.getString(i),
                        software.getJSONObject(softwareNames.getString(i)).getString("version"),
                        softAttributes);
                if (soft != null) {
                    log.fine("Saved/restored software " + soft);
                    // soft.getAttributes().putAll(softAttributes);
                    // AmiManager.updateSoftware(soft);
                    // log.fine("Saved object " + soft);
                } else
                    log.severe("Not able to save software information for given Ami Id " + amiId + "!");

            }
            List<String> names = new ArrayList<String>();
            for (int i = 0; i < softwareNames.length(); i++)
                names.add(softwareNames.getString(i));
            AmiManager.updateSoftwareNames(names);
            log.info("Saved " + softwareNames.length() + " software objects");

        }

        JSONObject languages = json.optJSONObject("languages");
        if (languages != null) {
            log.finer("Languages JSON " + languages);

            JSONArray languagesNames = languages.names();
            log.finer("Key Array JSON " + languagesNames);
            for (int i = 0; i < languagesNames.length(); i++) {
                log.fine("languages " + languagesNames.getString(i) + " with version "
                        + languages.getJSONObject(languagesNames.getString(i)).getString("version"));

                Map<String, String> langAttributes = new HashMap<String, String>();
                JSONArray languageAttributes = languages.getJSONObject(languagesNames.getString(i)).names();
                for (int j = 0; j < languageAttributes.length(); j++)
                    langAttributes.put(languageAttributes.getString(j),
                            languages.getJSONObject(languagesNames.getString(i))
                                    .getString(languageAttributes.getString(j)));

                Language lang = AmiManager.saveLanguage(amiId, repository, languagesNames.getString(i),
                        languages.getJSONObject(languagesNames.getString(i)).getString("version"),
                        langAttributes);
                if (lang != null) {
                    log.fine("Saved/restored programming language " + lang);
                    lang.getAttributes().putAll(langAttributes);
                    AmiManager.updateLanguage(lang);
                    log.fine("Saved object " + lang);
                } else
                    log.severe("Not able to save programming language information for given Ami Id " + amiId
                            + "!");

            }
            log.info("Saved " + languagesNames.length() + " programming language objects");
        }

        resp.getWriter().println(
                "Saving software packages and programming languages for " + amiId + " (" + repository + ").");

    } catch (JSONException e) {
        log.severe("Error while parsing JSON upload" + e.getMessage() + ", trace: " + e.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", e);
        e.printStackTrace();

    } catch (Exception ex) {
        log.severe("Unexpected error" + ex.getMessage() + ", trace: " + ex.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", ex);
        ex.printStackTrace();
    }

    // log.info("returning to referer " + req.getHeader("referer"));
    // resp.sendRedirect(req.getHeader("referer") != null &&
    // !"".equals(req.getHeader("referer")) ? req.getHeader("referer") :
    // "localhost:8088");
}

From source file:org.dasein.cloud.joyent.compute.Machine.java

private VirtualMachine toVirtualMachine(JSONObject ob) throws CloudException, InternalException {
    if (ob == null) {
        return null;
    }// w w w.  j a  v a  2 s  .  co  m
    try {
        VirtualMachine vm = new VirtualMachine();

        vm.setClonable(false);
        vm.setImagable(false);
        vm.setLastPauseTimestamp(-1L);
        vm.setPersistent(true);
        vm.setProviderDataCenterId(provider.getContext().getRegionId() + "a");
        vm.setProviderOwnerId(provider.getContext().getAccountNumber());
        vm.setProviderRegionId(provider.getContext().getRegionId());
        vm.setTerminationTimestamp(-1L);

        if (ob.has("id")) {
            vm.setProviderVirtualMachineId(ob.getString("id"));
        }
        if (ob.has("name")) {
            vm.setName(ob.getString("name"));
        }
        if (ob.has("ips")) {
            JSONArray ips = ob.getJSONArray("ips");
            ArrayList<String> pubIp = new ArrayList<String>();
            ArrayList<String> privIp = new ArrayList<String>();

            for (int i = 0; i < ips.length(); i++) {
                String addr = ips.getString(i);
                boolean pub = false;

                if (!addr.startsWith("10.") && !addr.startsWith("192.168.")) {
                    if (addr.startsWith("172.")) {
                        String[] nums = addr.split("\\.");

                        if (nums.length != 4) {
                            pub = true;
                        } else {
                            try {
                                int x = Integer.parseInt(nums[1]);

                                if (x < 16 || x > 31) {
                                    pub = true;
                                }
                            } catch (NumberFormatException ignore) {
                                // ignore
                            }
                        }
                    } else {
                        pub = true;
                    }
                }
                if (pub) {
                    pubIp.add(addr);
                } else {
                    privIp.add(addr);
                }
            }
            if (!pubIp.isEmpty()) {
                vm.setPublicIpAddresses(pubIp.toArray(new String[pubIp.size()]));
            }
            if (!privIp.isEmpty()) {
                vm.setPrivateIpAddresses(privIp.toArray(new String[privIp.size()]));
            }
        }
        if (ob.has("metadata")) {
            JSONObject md = ob.getJSONObject("metadata");
            JSONArray names = md.names();

            if (names != null) {
                for (int i = 0; i < names.length(); i++) {
                    String name = names.getString(i);

                    if (name.equals("dsnDescription")) {
                        vm.setDescription(md.getString(name));
                    } else if (name.equals("dsnTrueImage")) {
                        vm.setProviderMachineImageId(md.getString(name));
                    } else if (name.equals("dsnTrueProduct")) {
                        vm.setProductId(md.getString(name));
                    } else {
                        vm.addTag(name, md.getString(name));
                    }
                }
            }
        }
        if (vm.getProviderMachineImageId() == null && ob.has("dataset")) {
            vm.setProviderMachineImageId(getImageIdFromUrn(ob.getString("dataset")));
        }
        if (ob.has("created")) {
            vm.setCreationTimestamp(provider.parseTimestamp(ob.getString("created")));
        }
        vm.setPausable(false); // can't ever pause/resume joyent vms
        vm.setRebootable(false);
        if (ob.has("state")) {
            vm.setCurrentState(toState(ob.getString("state")));

            if (VmState.RUNNING.equals(vm.getCurrentState())) {
                vm.setRebootable(true);
            } else if (VmState.STOPPED.equals(vm.getCurrentState())) {
                vm.setImagable(true);
            }
        }
        vm.setLastBootTimestamp(vm.getCreationTimestamp());
        if (vm.getName() == null) {
            vm.setName(vm.getProviderVirtualMachineId());
        }
        if (vm.getDescription() == null) {
            vm.setDescription(vm.getName());
        }
        discover(vm);
        boolean isVMSmartOs = (vm.getPlatform().equals(Platform.SMARTOS));
        if (vm.getProductId() == null) {
            VirtualMachineProduct d = null;
            int disk, ram;

            disk = ob.getInt("disk");
            ram = ob.getInt("memory");
            for (VirtualMachineProduct prd : listProducts(vm.getArchitecture())) {
                d = prd;
                boolean isProductSmartOs = prd.getName().contains("smartos");
                if (prd.getRootVolumeSize().convertTo(Storage.MEGABYTE).intValue() == disk
                        && prd.getRamSize().intValue() == ram) {
                    if (isVMSmartOs && !isProductSmartOs) {
                        continue;
                    }
                    if (!isVMSmartOs && isProductSmartOs) {
                        continue;
                    }
                    vm.setProductId(prd.getProviderProductId());
                    break;
                }
            }
            if (vm.getProductId() == null) {
                vm.setProductId(d.getProviderProductId());
            }
        }
        return vm;
    } catch (JSONException e) {
        throw new CloudException(e);
    }
}

From source file:org.chromium.ChromeStorage.java

private JSONObject getStoredValuesForKeys(CordovaArgs args, boolean useDefaultValues) {
    JSONObject ret = new JSONObject();
    try {// ww w .j  a  va  2s  .  co  m
        String namespace = args.getString(0);
        JSONObject jsonObject = (JSONObject) args.optJSONObject(1);
        JSONArray jsonArray = args.optJSONArray(1);
        boolean isNull = args.isNull(1);
        List<String> keys = new ArrayList<String>();

        if (jsonObject != null) {
            keys = toStringList(jsonObject.names());
            // Ensure default values of keys are maintained
            if (useDefaultValues) {
                ret = jsonObject;
            }
        } else if (jsonArray != null) {
            keys = toStringList(jsonArray);
        } else if (isNull) {
            keys = null;
        }

        if (keys != null && keys.isEmpty()) {
            ret = new JSONObject();
        } else {
            JSONObject storage = getStorage(namespace);

            if (keys == null) {
                // return the whole storage if the key given is null
                ret = storage;
            } else {
                // return the storage for the keys specified
                for (String key : keys) {
                    if (storage.has(key)) {
                        Object value = storage.get(key);
                        ret.put(key, value);
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Storage is corrupted!", e);
        ret = null;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Could not retrieve storage", e);
        ret = null;
    }

    return ret;
}

From source file:org.chromium.ChromeStorage.java

private void set(final CordovaArgs args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override//from  ww  w . j a va  2s .  c o m
        public void run() {
            try {
                String namespace = args.getString(0);
                JSONObject jsonObject = (JSONObject) args.getJSONObject(1);
                JSONArray keyArray = jsonObject.names();
                JSONObject oldValues = new JSONObject();

                if (keyArray != null) {
                    List<String> keys = toStringList(keyArray);
                    JSONObject storage = getStorage(namespace);
                    for (String key : keys) {
                        Object oldValue = storage.opt(key);
                        if (oldValue != null) {
                            oldValues.put(key, oldValue);
                        }
                        storage.put(key, jsonObject.get(key));
                    }
                    setStorage(namespace, storage);
                }
                callbackContext.success(oldValues);
            } catch (Exception e) {
                Log.e(LOG_TAG, "Could not update storage", e);
                callbackContext.error("Could not update storage");
            }
        }
    });
}

From source file:org.chromium.ChromeStorage.java

private void remove(final CordovaArgs args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override/*  www  . j av a  2 s  .c  o  m*/
        public void run() {
            try {
                String namespace = args.getString(0);
                JSONObject jsonObject = (JSONObject) args.optJSONObject(1);
                JSONArray jsonArray = args.optJSONArray(1);
                boolean isNull = args.isNull(1);
                List<String> keys = new ArrayList<String>();
                JSONObject oldValues = new JSONObject();

                if (jsonObject != null) {
                    keys = toStringList(jsonObject.names());
                } else if (jsonArray != null) {
                    keys = toStringList(jsonArray);
                } else if (isNull) {
                    keys = null;
                }

                if (keys != null && !keys.isEmpty()) {
                    JSONObject storage = getStorage(namespace);
                    for (String key : keys) {
                        Object oldValue = storage.opt(key);
                        if (oldValue != null) {
                            oldValues.put(key, oldValue);
                        }
                        storage.remove(key);
                    }
                    setStorage(namespace, storage);
                }
                callbackContext.success(oldValues);
            } catch (Exception e) {
                Log.e(LOG_TAG, "Could not update storage", e);
                callbackContext.error("Could not update storage");
            }
        }
    });
}