Example usage for org.json JSONArray toString

List of usage examples for org.json JSONArray toString

Introduction

In this page you can find the example usage for org.json JSONArray toString.

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONArray.

Usage

From source file:org.seadpdt.impl.RepoServicesImpl.java

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)//  ww  w  . j  av  a  2 s.  co  m
public Response getRepositoryList() {
    FindIterable<Document> iter = repositoriesCollection.find();
    iter.projection(new Document("orgidentifier", 1).append("repositoryURL", 1).append("repositoryName", 1)
            .append("lastUpdate", 1).append("_id", 0));
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        array.put(new JSONObject(cursor.next().toJson()));
    }
    return Response.ok(array.toString()).cacheControl(control).build();

}

From source file:nl.spellenclubeindhoven.dominionshuffle.LoadSaveActivity.java

public boolean saveSlot(int number, String name, CardSelector cardSelector) {
    try {//  w  w  w.  java  2 s. co  m
        boolean result = DataReader.writeStringToFile(this, String.format("slot%d.json", number),
                getCardSelector().toJson());
        if (result == false) {
            return false;
        }
    } catch (JSONException ignore) {
        return false;
    }

    // Save slotname (if saving the selection worked)
    adapter.getItem(number).name = name;
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < adapter.getCount(); i++) {
        jsonArray.put(adapter.getItem(i).name);
    }

    return DataReader.writeStringToFile(this, "slots.json", jsonArray.toString());
}

From source file:com.fuse.billing.android.IabHelper.java

public String querySkuDetailsAsJsonString(String itemType, String skuArrayJsonString) throws IabException {
    try {//w  w  w .jav  a2  s.co m
        JSONArray skuJsonArray = new JSONArray(skuArrayJsonString);
        List<String> skuList = new ArrayList<String>();
        for (int i = 0; i < skuJsonArray.length(); i++) {
            skuList.add(skuJsonArray.getString(i));
        }
        List<SkuDetails> skuDetailsList = new ArrayList<SkuDetails>();
        int r = querySkuDetails(itemType, skuList, skuDetailsList);
        if (r != BILLING_RESPONSE_RESULT_OK) {
            throw new IabException(r, "Error querying sku details");
        }
        JSONArray skuDetailsJsonArray = new JSONArray();
        for (SkuDetails skuDetails : skuDetailsList) {
            skuDetailsJsonArray.put(skuDetails.toJSON());
        }
        return skuDetailsJsonArray.toString();
    } catch (RemoteException e) {
        throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e);
    } catch (JSONException e) {
        throw new IabException(IABHELPER_BAD_RESPONSE,
                "Error parsing JSON response while querying sku details.", e);
    }
}

From source file:com.fuse.billing.android.IabHelper.java

public String queryPurchasesAsJsonString(String itemType) throws IabException {
    try {//  w  w  w  .  ja  v  a  2 s.  c  o  m
        List<Purchase> purchases = new ArrayList<Purchase>();
        int r = queryPurchases(purchases, itemType);
        if (r != BILLING_RESPONSE_RESULT_OK) {
            throw new IabException(r, "Error refreshing inventory (querying owned items).");
        }
        // Yup, there will be some redundant (de)serialization going on here.
        // We don't care as it's very little data.
        JSONArray jsonArray = new JSONArray();
        for (Purchase purchase : purchases) {
            jsonArray.put(purchase.toJSON());
        }
        return jsonArray.toString();
    } catch (RemoteException e) {
        throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e);
    } catch (JSONException e) {
        throw new IabException(IABHELPER_BAD_RESPONSE,
                "Error parsing JSON response while refreshing inventory.", e);
    }
}

From source file:org.exoplatform.social.addons.storage.RDBMSIdentityStorageImpl.java

private void mapToProfileEntity(Profile profile, IdentityEntity entity) {
    Map<String, String> entityProperties = entity.getProperties();
    if (entityProperties == null) {
        entityProperties = new HashMap<>();
    }/*  ww  w .  j a  v  a 2s.c o m*/

    String providerId = profile.getIdentity().getProviderId();
    if (!OrganizationIdentityProvider.NAME.equals(providerId)
            && !SpaceIdentityProvider.NAME.equals(providerId)) {
        entityProperties.put(Profile.URL, profile.getUrl());
        entityProperties.put(Profile.AVATAR_URL, profile.getAvatarUrl());
    }

    Map<String, Object> properties = profile.getProperties();
    for (Map.Entry<String, Object> e : properties.entrySet()) {
        if (Profile.AVATAR.equalsIgnoreCase(e.getKey())) {
            AvatarAttachment attachment = (AvatarAttachment) e.getValue();
            byte[] bytes = attachment.getImageBytes();
            String fileName = attachment.getFileName();
            if (fileName == null) {
                fileName = entity.getRemoteId() + "_avatar";
            }

            try {
                Long avatarId = entity.getAvatarFileId();
                FileItem fileItem;
                if (avatarId != null) {//update avatar file
                    fileItem = new FileItem(avatarId, fileName, attachment.getMimeType(), socialNameSpace,
                            bytes.length, new Date(), entity.getRemoteId(), false,
                            new ByteArrayInputStream(bytes));
                    fileService.updateFile(fileItem);
                } else {//create new  avatar file
                    fileItem = new FileItem(null, fileName, attachment.getMimeType(), socialNameSpace,
                            bytes.length, new Date(), entity.getRemoteId(), false,
                            new ByteArrayInputStream(bytes));
                    fileItem = fileService.writeFile(fileItem);
                    entity.setAvatarFileId(fileItem.getFileInfo().getId());
                }
            } catch (Exception ex) {
                LOG.warn("Can not store avatar for " + entity.getProviderId() + " " + entity.getRemoteId(), ex);
            }

        } else if (Profile.EXPERIENCES.equalsIgnoreCase(e.getKey())) {

            List<Map<String, String>> exps = (List<Map<String, String>>) e.getValue();
            Set<ProfileExperienceEntity> experiences = new HashSet<>();

            for (Map<String, String> exp : exps) {
                ProfileExperienceEntity ex = new ProfileExperienceEntity();
                ex.setCompany(exp.get(Profile.EXPERIENCES_COMPANY));
                ex.setPosition(exp.get(Profile.EXPERIENCES_POSITION));
                ex.setStartDate(exp.get(Profile.EXPERIENCES_START_DATE));
                ex.setEndDate(exp.get(Profile.EXPERIENCES_END_DATE));
                ex.setSkills(exp.get(Profile.EXPERIENCES_SKILLS));
                ex.setDescription(exp.get(Profile.EXPERIENCES_DESCRIPTION));

                experiences.add(ex);
            }

            entity.setExperiences(experiences);

        } else if (Profile.CONTACT_IMS.equals(e.getKey()) || Profile.CONTACT_PHONES.equals(e.getKey())
                || Profile.CONTACT_URLS.equals(e.getKey())) {

            List<Map<String, String>> list = (List<Map<String, String>>) e.getValue();
            JSONArray arr = new JSONArray();
            for (Map<String, String> map : list) {
                JSONObject json = new JSONObject(map);
                arr.put(json);
            }

            entityProperties.put(e.getKey(), arr.toString());

        } else if (!Profile.EXPERIENCES_SKILLS.equals(e.getKey())) {
            Object val = e.getValue();
            if (val != null) {
                entityProperties.put(e.getKey(), String.valueOf(val));
            }
        }
    }

    entity.setProperties(entityProperties);

    Date created = profile.getCreatedTime() <= 0 ? new Date() : new Date(profile.getCreatedTime());
    entity.setCreatedDate(created);
}

From source file:com.redoute.datamap.servlet.GetDistinctValueFromTableColumn.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String table = policy.sanitize(request.getParameter("table"));
    String colName = policy.sanitize(request.getParameter("colName"));

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
    IDatamapService datamapService = appContext.getBean(IDatamapService.class);
    IPictureService pictureService = appContext.getBean(IPictureService.class);
    IDatamapLocationTypeService datamapLocationTypeService = appContext
            .getBean(IDatamapLocationTypeService.class);

    if (table != null && colName != null) {
        try {/*w w w  .jav a  2  s .c  o  m*/
            JSONArray valueList = new JSONArray();
            try {
                if (table.equals("Datamap")) {
                    for (String value : datamapService.findDistinctValuesfromColumn(colName)) {
                        valueList.put(value);
                    }
                }
                if (table.equals("Picture")) {
                    for (String value : pictureService.findDistinctValuesfromColumn(colName)) {
                        valueList.put(value);
                    }
                }
                if (table.equals("DatamapLocationType")) {
                    for (String value : datamapLocationTypeService.findDistinctValuesfromColumn(colName)) {
                        valueList.put(value);
                    }
                }

            } catch (Exception ex) {
                response.setContentType("text/html");
                response.getWriter().print(ex);

            }
            response.setContentType("application/json");
            response.getWriter().print(valueList.toString());
        } catch (Exception e) {
            Logger.log(GetDistinctValueFromTableColumn.class.getName(), Level.FATAL, "" + e);
            response.setContentType("text/html");
            response.getWriter().print(e.getMessage());
        }
    }
}

From source file:org.wso2.emm.agent.services.PolicyTester.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public PolicyTester(Context context, JSONArray recJArray, int type, String msgID) {
    this.context = context;
    devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
    appList = new ApplicationManager(context);
    deviceInfo = new DeviceInfo(context);
    deviceState = new PhoneState(context);

    if (type == POLICY_MONITOR_TYPE_NO_ENFORCE_RETURN) {
        IS_ENFORCE = false;/* w w  w.j  a  v a2s.  c  o m*/
    } else if (type == POLICY_MONITOR_TYPE_NO_ENFORCE_MESSAGE_RETURN) {
        IS_ENFORCE = false;
    } else if (type == POLICY_MONITOR_TYPE_ENFORCE_RETURN) {
        IS_ENFORCE = true;
    } else {
        IS_ENFORCE = false;
        type = POLICY_MONITOR_TYPE_NO_ENFORCE_MESSAGE_RETURN;
    }

    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
    policy = mainPref.getString("policy", "");

    try {
        JSONArray jArray = null;
        if (recJArray != null) {
            jArray = recJArray;
        } else {
            jArray = new JSONArray(policy);
        }
        Log.e("POLICY ARAY : ", jArray.toString());
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject policyObj = (JSONObject) jArray.getJSONObject(i);
            if (policyObj.getString("data") != null && policyObj.getString("data") != "") {
                testPolicy(policyObj.getString("code"), policyObj.getString("data"));
            }
        }

        JSONObject rootObj = new JSONObject();
        try {
            if (deviceInfo.isRooted()) {
                rootObj.put("status", false);
            } else {
                rootObj.put("status", true);
            }
            rootObj.put("code", "notrooted");
            finalArray.put(rootObj);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Log.e("MONITOR POLICY : ", policy);
        Log.e("MONITOR USER MESSAGE : ", usermessage);
        //Display an alert to the user about policy violation
        if (policy != null && policy != "") {
            if (usermessage != null && usermessage != ""
                    && type == POLICY_MONITOR_TYPE_NO_ENFORCE_MESSAGE_RETURN) {
                Intent intent = new Intent(context, AlertActivity.class);
                intent.putExtra("message", usermessage);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        }

        returnJSON.put("code", CommonUtilities.OPERATION_POLICY_MONITOR);
        returnJSON.put("data", finalArray);

        Map<String, String> params = new HashMap<String, String>();
        params.put("code", CommonUtilities.OPERATION_POLICY_MONITOR);
        params.put("msgID", msgID);
        params.put("status", "200");
        params.put("data", finalArray.toString());

        //ServerUtilities.pushData(params, context);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:br.ufc.mdcc.mpos.net.profile.model.Network.java

public static String arrayToString(long... vlrs) {
    JSONArray jsonArray = new JSONArray();

    if (vlrs != null) {
        for (long vlr : vlrs) {
            jsonArray.put(vlr);/* w  ww  .jav a  2 s .  c  o m*/
        }
    }

    return jsonArray.toString();
}

From source file:org.apache.giraph.graph.BspServiceMaster.java

/**
 * Save the supplied aggregator values./*from   w ww.ja  va2 s  .co m*/
 *
 * @param superstep superstep for which to save values
 */
private void saveAggregatorValues(long superstep) {
    Map<String, Aggregator<Writable>> aggregatorMap = getAggregatorMap();
    if (aggregatorMap.size() > 0) {
        String mergedAggregatorPath = getMergedAggregatorPath(getApplicationAttempt(), superstep);
        byte[] zkData = null;
        JSONArray aggregatorArray = new JSONArray();
        for (Map.Entry<String, Aggregator<Writable>> entry : aggregatorMap.entrySet()) {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                DataOutput output = new DataOutputStream(outputStream);
                entry.getValue().getAggregatedValue().write(output);

                JSONObject aggregatorObj = new JSONObject();
                aggregatorObj.put(AGGREGATOR_NAME_KEY, entry.getKey());
                aggregatorObj.put(AGGREGATOR_VALUE_KEY, Base64.encodeBytes(outputStream.toByteArray()));
                aggregatorArray.put(aggregatorObj);
                if (LOG.isInfoEnabled()) {
                    LOG.info("saveAggregatorValues: " + "Trying to add aggregatorObj " + aggregatorObj + "("
                            + entry.getValue().getAggregatedValue() + ") to merged aggregator path "
                            + mergedAggregatorPath);
                }
            } catch (IOException e) {
                throw new IllegalStateException("saveAggregatorValues: " + "IllegalStateException", e);
            } catch (JSONException e) {
                throw new IllegalStateException("saveAggregatorValues: JSONException", e);
            }
        }
        try {
            zkData = aggregatorArray.toString().getBytes();
            getZkExt().createExt(mergedAggregatorPath, zkData, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,
                    true);
        } catch (KeeperException.NodeExistsException e) {
            LOG.warn("saveAggregatorValues: " + mergedAggregatorPath + " already exists!");
        } catch (KeeperException e) {
            throw new IllegalStateException("saveAggregatorValues: KeeperException", e);
        } catch (InterruptedException e) {
            throw new IllegalStateException("saveAggregatorValues: IllegalStateException", e);
        }
        if (LOG.isInfoEnabled()) {
            LOG.info("saveAggregatorValues: Finished " + "loading " + mergedAggregatorPath
                    + " with aggregator values " + aggregatorArray);
        }
    }
}

From source file:com.ikota.flickrclient.data.model.FlickerPhotoInfo.java

private void init(String json) throws JSONException {
    Gson gson = new Gson();
    JSONObject root = new JSONObject(json);
    JSONObject photo_json = root.getJSONObject("photo");
    this.photo = gson.fromJson(photo_json.toString(), Photo.class);
    this.owner = gson.fromJson(photo_json.getJSONObject("owner").toString(), Owner.class);
    this.title = photo_json.getJSONObject("title").getString("_content");
    this.description = photo_json.getJSONObject("description").getString("_content");
    this.dates = photo_json.getJSONObject("dates").getString("taken");
    this.views = photo_json.getInt("views");
    this.comments = photo_json.getJSONObject("comments").getInt("_content");
    JSONArray tag_array = photo_json.getJSONObject("tags").getJSONArray("tag");
    Type listType = new TypeToken<List<Tag>>() {
    }.getType();// w w w  .j  ava  2 s.  c  om
    tags = gson.fromJson(tag_array.toString(), listType);
}