Example usage for org.json.simple JSONArray toJSONString

List of usage examples for org.json.simple JSONArray toJSONString

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:org.openlegacy.terminal.json.JsonSerializationUtil.java

/**
 * Returns//from  w w  w.ja v a 2s .c o m
 */
@SuppressWarnings("unchecked")
public static String toDojoFormat(Map<Object, Object> map, String searchPattern) {
    // remove '*' from searchPattern
    if (searchPattern != null) {
        searchPattern = searchPattern.replace("*", "");
    }

    JSONArray jsonArray = new JSONArray();
    Set<Entry<Object, Object>> entrySets = map.entrySet();
    for (Entry<Object, Object> entry : entrySets) {
        boolean addToArray = false;
        if (StringUtils.isEmpty(searchPattern)) {
            addToArray = true;
        } else {
            String value = (String) entry.getValue();
            if (value.startsWith(searchPattern)) {
                addToArray = true;
            }
        }
        if (addToArray) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", entry.getKey());
            jsonObject.put("name", entry.getValue());
            jsonArray.add(jsonObject);
        }
    }
    return jsonArray.toJSONString();
}

From source file:org.opensocial.Client.java

byte[] buildRpcPayload(Map<String, Request> requests) {
    if (requests.size() == 1 && requests.values().iterator().next().getCustomPayload() != null) {
        return requests.values().iterator().next().getCustomPayload();
    }/*  w  w w  . j  av a2s.c om*/

    JSONArray requestArray = new JSONArray();
    for (Map.Entry<String, Request> requestEntry : requests.entrySet()) {
        JSONObject request = new JSONObject();
        request.put("id", requestEntry.getKey());
        request.put("method", requestEntry.getValue().getRpcMethod());

        JSONObject requestParams = new JSONObject();
        for (Map.Entry<String, Object> parameter : requestEntry.getValue().getRpcPayloadParameters()
                .entrySet()) {
            requestParams.put(parameter.getKey(), parameter.getValue());
        }

        request.put("params", requestParams);
        requestArray.add(request);
    }

    try {
        return requestArray.toJSONString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}

From source file:org.owasp.dependencytrack.controller.DashboardController.java

/**
 * Returns a json reponse of vulnerability trends.
 * @param days the number of days back to get statistics for
 * @return a String/*  ww w .  jav a  2s. co  m*/
 */
@RequiresPermissions("vulnerabilities")
@RequestMapping(value = "/vulnerabilityTrend/{days}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
@SuppressWarnings("unchecked")
public String vulnerabilityTrend(@PathVariable("days") Integer days) {
    final VulnerabilityTrend.Timespan timespan = VulnerabilityTrend.Timespan.getTimespan(days);
    final VulnerabilityTrend trend = vulnerabilityService.getVulnerabilityTrend(timespan, -1);
    final JSONArray jsonArray = new JSONArray();
    for (Map.Entry<Date, VulnerabilitySummary> entry : trend.getTrend().entrySet()) {
        final VulnerabilitySummary vs = entry.getValue();
        final JSONObject jsonObject = new JSONObject();
        jsonObject.put("date", entry.getKey().toString());
        jsonObject.put("high", vs.getHigh());
        jsonObject.put("medium", vs.getMedium());
        jsonObject.put("low", vs.getLow());
        jsonObject.put("total", vs.getHigh() + vs.getMedium() + vs.getLow());
        jsonArray.add(jsonObject);
    }
    return jsonArray.toJSONString();
}

From source file:org.pentaho.di.sharepoint.steps.input.SharepointListInputDialog.java

/**
 * Get the list of fields in the Excel workbook and put the result in the fields table view.
 *///ww  w.j a  va 2  s  .  c o  m
public void getFields() {
    RowMetaInterface fields = new RowMeta();

    SharepointListInputMeta info = new SharepointListInputMeta();

    int clearFields = SWT.YES;
    if (wFields.nrNonEmpty() > 0) {
        MessageBox messageBox = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_QUESTION);
        messageBox.setMessage(
                BaseMessages.getString(PKG, "SharepointListInputDialog.ClearFieldList.DialogMessage"));
        messageBox.setText(BaseMessages.getString(PKG, "SharepointListInputDialog.ClearFieldList.DialogTitle"));
        clearFields = messageBox.open();
        if (clearFields == SWT.CANCEL) {
            return;
        }
    }
    //Set Sharepoint objects
    SharepointConnection sp;
    JSONArray result = null;
    try {
        getInfo(info);
        //Create Connection..
        sp = new SharepointConnection(info.getSite(), info.getUsername(), info.getPassword(), info.getDomain());

        //Since this is just a preview just take the first 10 records
        String list = info.getList();
        int qIndex = list.indexOf("?");
        if (qIndex > 0) {
            list = list.substring(0, qIndex);
        }
        result = (JSONArray) sp.getList(list + "/fields").get("results");

    } catch (Exception e) {
        new ErrorDialog(shell, BaseMessages.getString(PKG, "System.Dialog.Error.Title"),
                BaseMessages.getString(PKG, "SharepointListInputDialog.ErrorReadingFile2.DialogMessage",
                        info.getList(), e.toString()),
                e);

    }
    //Parse the List Values..

    try {
        for (int i = 0; i < result.size(); i++) {
            try {
                //Read Definition
                JSONObject f = (JSONObject) result.get(i);
                int type = Integer.parseInt(f.get("FieldTypeKind").toString());

                //Set PDI properties
                String fieldname = f.get("StaticName").toString();
                int fieldtype = ValueMetaInterface.TYPE_STRING;

                //Map Types http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.fieldtype(v=office.15).aspx

                switch (type) {

                case 1:
                    fieldtype = ValueMetaInterface.TYPE_INTEGER;
                    break;
                case 4:
                    fieldtype = ValueMetaInterface.TYPE_DATE;
                    break;
                case 8:
                    fieldtype = ValueMetaInterface.TYPE_BOOLEAN;
                    break;
                case 9:
                case 10:
                    fieldtype = ValueMetaInterface.TYPE_NUMBER;
                    break;
                }

                ValueMetaInterface field = ValueMetaFactory.createValueMeta(fieldname, fieldtype);
                fields.addValueMeta(field);
            } catch (ArrayIndexOutOfBoundsException aioobe) {

            }
        }

    }

    catch (Exception e) {
        new ErrorDialog(shell, BaseMessages.getString(PKG, "System.Dialog.Error.Title"),
                BaseMessages.getString(PKG, "SharepointListInputDialog.ErrorReadingFile2.DialogMessage",
                        result.toJSONString(), e.toString()),
                e);
    }

    if (fields.size() > 0) {
        if (clearFields == SWT.YES) {
            wFields.clearAll(false);
        }
        for (int j = 0; j < fields.size(); j++) {
            ValueMetaInterface field = fields.getValueMeta(j);
            String mask = "";
            if (field.getType() == ValueMetaInterface.TYPE_DATE) {
                mask = "yyyy-MM-dd HH:mm:ss";
            }
            wFields.add(
                    new String[] { field.getName(), field.getName(), field.getTypeDesc(), mask, "none", "N" });
        }
        wFields.removeEmptyRows();
        wFields.setRowNums();
        wFields.optWidth(true);
        input.setChanged();
    } else {
        MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
        mb.setMessage(
                BaseMessages.getString(PKG, "SharepointListInputDialog.UnableToFindFields.DialogMessage"));
        mb.setText(BaseMessages.getString(PKG, "SharepointListInputDialog.UnableToFindFields.DialogTitle"));
        mb.open();
    }

}

From source file:org.projasource.dbimport.bindings.SqlQueryExecutor.java

public String list(final String sql, final Object[] params) throws SQLException {
    return execute(sql, params, new RSCallback() {
        public String fetchResultSet(ResultSet rs) throws SQLException {
            final JSONArray result = new JSONArray();
            final List<String> fields = new ArrayList<String>();
            for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                fields.add(rs.getMetaData().getColumnName(i));
            }//from w  w w.  j a  va 2 s.c  o  m
            while (rs.next()) {
                final JSONObject row = new JSONObject();
                for (final String nm : fields) {
                    row.put(nm, rs.getString(nm));
                }
                result.add(row);
            }
            return result.toJSONString();
        }
    });
}

From source file:org.streaminer.stream.histogram.spdt.Gap.java

@Override
public String toString() {
    JSONArray jsonArray = new JSONArray();
    jsonArray.add(_weight);//from w  ww . j  a va2 s  . com
    jsonArray.add(_startBin);
    jsonArray.add(_endBin);
    return jsonArray.toJSONString();
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImpl.java

/**
 * This method replaces the groupId field's value to the role id instead of the name passed by the user
 *
 * @param permissionString - the permission json string which contains role names in groupId field
 * @return permission string with replaced groupId
 * @throws ParseException         - if there is an error parsing the json string
 * @throws APIManagementException - if there is an error getting the IdentityProvider instance
 *///from   w w  w.ja v  a 2 s  .  com
private String replaceGroupNamesWithId(String permissionString) throws ParseException, APIManagementException {
    JSONArray updatedPermissionArray = new JSONArray();
    JSONParser jsonParser = new JSONParser();
    JSONArray originalPermissionArray = (JSONArray) jsonParser.parse(permissionString);
    try {
        for (Object permissionObj : originalPermissionArray) {
            JSONObject jsonObject = (JSONObject) permissionObj;
            String groupName = (String) jsonObject.get(APIMgtConstants.Permission.GROUP_ID);
            String groupId = getIdentityProvider().getRoleId(groupName);
            JSONObject updatedPermissionJsonObj = new JSONObject();
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.GROUP_ID, groupId);
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.PERMISSION,
                    jsonObject.get(APIMgtConstants.Permission.PERMISSION));
            updatedPermissionArray.add(updatedPermissionJsonObj);
        }
    } catch (IdentityProviderException e) {
        String errorMessage = "There are invalid roles in the permission string";
        log.error(errorMessage, e);
        throw new APIManagementException(errorMessage, e, ExceptionCodes.UNSUPPORTED_ROLE);
    }
    return updatedPermissionArray.toJSONString();
}

From source file:org.wso2.carbon.apimgt.core.impl.APIPublisherImpl.java

/**
 * This method replaces the groupId field's value of the api permissions string to the role name before sending to
 * frontend//from   w w w  .ja  va  2  s.  com
 *
 * @param permissionString - permissions string containing role ids in the groupId field
 * @return the permission string replacing the groupId field's value to role name
 * @throws ParseException - if there is an error parsing the permission json
 * @throws APIManagementException - if there is an error getting the IdentityProvider instance
 */
private String replaceGroupIdWithName(String permissionString) throws ParseException, APIManagementException {
    JSONArray updatedPermissionArray = new JSONArray();
    JSONParser jsonParser = new JSONParser();
    JSONArray originalPermissionArray = (JSONArray) jsonParser.parse(permissionString);

    for (Object permissionObj : originalPermissionArray) {
        JSONObject jsonObject = (JSONObject) permissionObj;
        String groupId = (String) jsonObject.get(APIMgtConstants.Permission.GROUP_ID);
        try {
            String groupName = getIdentityProvider().getRoleName(groupId);
            JSONObject updatedPermissionJsonObj = new JSONObject();
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.GROUP_ID, groupName);
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.PERMISSION,
                    jsonObject.get(APIMgtConstants.Permission.PERMISSION));
            updatedPermissionArray.add(updatedPermissionJsonObj);
        } catch (IdentityProviderException e) {
            //lets the execution continue after logging the exception
            String errorMessage = "Error occurred while calling SCIM endpoint to retrieve role name of role "
                    + "with Id " + groupId;
            log.warn(errorMessage, e);
        }
    }
    return updatedPermissionArray.toJSONString();
}

From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java

public static NativeArray jsFunction_getScopes(Context cx, Scriptable thisObj, Object[] args, Function funObj)
        throws APIManagementException {
    NativeArray myn = new NativeArray(0);

    if (args == null || !isStringValues(args)) {
        handleException("Invalid number of parameters or their types.");
    }/*from  ww  w . jav a  2 s  .c  o  m*/
    String providerName = args[0].toString();
    //        String providerNameTenantFlow = args[0].toString();
    providerName = APIUtil.replaceEmailDomain(providerName);
    String scopeKey = args[1].toString();

    if (scopeKey != null && providerName != null) {
        Set<Scope> scopeSet = APIUtil.getScopeByScopeKey(scopeKey, providerName);
        JSONArray scopesNative = new JSONArray();
        for (Scope scope : scopeSet) {
            JSONObject scopeNative = new JSONObject();
            scopeNative.put("id", scope.getId());
            scopeNative.put("key", scope.getKey());
            scopeNative.put("name", scope.getName());
            scopeNative.put("roles", scope.getRoles());
            scopeNative.put("description", scope.getDescription());
            scopesNative.add(scopeNative);
        }
        myn.put(41, myn, scopesNative.toJSONString());
    } else {
        handleException("Scope Key or Provider Name not valid.");
    }
    return myn;
}

From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java

/**
 * This method is to functionality of getting an existing API to API-Provider based
 *
 * @param cx      Rhino context// www.j a v a  2 s  .  co m
 * @param thisObj Scriptable object
 * @param args    Passing arguments
 * @param funObj  Function object
 * @return a native array
 * @throws APIManagementException Wrapped exception by org.wso2.carbon.apimgt.api.APIManagementException
 */

public static NativeArray jsFunction_getAPI(Context cx, Scriptable thisObj, Object[] args, Function funObj)
        throws APIManagementException {
    NativeArray myn = new NativeArray(0);

    if (args == null || !isStringValues(args)) {
        handleException("Invalid number of parameters or their types.");
    }
    String providerName = args[0].toString();
    String providerNameTenantFlow = args[0].toString();
    providerName = APIUtil.replaceEmailDomain(providerName);
    String apiName = args[1].toString();
    String version = args[2].toString();

    APIIdentifier apiId = new APIIdentifier(providerName, apiName, version);
    APIProvider apiProvider = getAPIProvider(thisObj);
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils
                .getTenantDomain(APIUtil.replaceEmailDomainBack(providerNameTenantFlow));
        String userTenantDomain = MultitenantUtils.getTenantDomain(
                APIUtil.replaceEmailDomainBack(((APIProviderHostObject) thisObj).getUsername()));
        if (!tenantDomain.equals(userTenantDomain)) {
            throw new APIManagementException(
                    "Invalid Operation: Cannot access API:" + apiId + "from current tenant.");
        }
        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }

        API api = null;
        try {
            api = apiProvider.getAPI(apiId);
        } catch (APIManagementException e) {
            handleException("Cannot find the requested API- " + apiName + "-" + version, e);
        }

        if (api != null) {
            Set<URITemplate> uriTemplates = api.getUriTemplates();

            myn.put(0, myn, checkValue(api.getId().getApiName()));
            myn.put(1, myn, checkValue(api.getDescription()));
            myn.put(2, myn, checkValue(api.getUrl()));
            myn.put(3, myn, checkValue(api.getWsdlUrl()));
            myn.put(4, myn, checkValue(api.getId().getVersion()));
            StringBuilder tagsSet = new StringBuilder("");
            for (int k = 0; k < api.getTags().toArray().length; k++) {
                tagsSet.append(api.getTags().toArray()[k].toString());
                if (k != api.getTags().toArray().length - 1) {
                    tagsSet.append(",");
                }
            }
            myn.put(5, myn, checkValue(tagsSet.toString()));
            StringBuilder tiersSet = new StringBuilder("");
            StringBuilder tiersDisplayNamesSet = new StringBuilder("");
            StringBuilder tiersDescSet = new StringBuilder("");
            Set<Tier> tierSet = api.getAvailableTiers();
            Iterator it = tierSet.iterator();
            int j = 0;
            while (it.hasNext()) {
                Object tierObject = it.next();
                Tier tier = (Tier) tierObject;
                tiersSet.append(tier.getName());
                tiersDisplayNamesSet.append(tier.getDisplayName());
                tiersDescSet.append(tier.getDescription());
                if (j != tierSet.size() - 1) {
                    tiersSet.append(",");
                    tiersDisplayNamesSet.append(",");
                    tiersDescSet.append(",");
                }
                j++;
            }

            myn.put(6, myn, checkValue(tiersSet.toString()));
            myn.put(7, myn, checkValue(api.getStatus().toString()));
            myn.put(8, myn, getWebContextRoot(api.getThumbnailUrl()));
            myn.put(9, myn, api.getContext());
            myn.put(10, myn, checkValue(Long.valueOf(api.getLastUpdated().getTime()).toString()));
            myn.put(11, myn, getSubscriberCount(apiId, thisObj));

            if (uriTemplates.size() != 0) {
                NativeArray uriTempArr = new NativeArray(uriTemplates.size());
                Iterator i = uriTemplates.iterator();
                List<NativeArray> uriTemplatesArr = new ArrayList<NativeArray>();
                while (i.hasNext()) {
                    List<String> utArr = new ArrayList<String>();
                    URITemplate ut = (URITemplate) i.next();
                    utArr.add(ut.getUriTemplate());
                    utArr.add(ut.getMethodsAsString().replaceAll("\\s", ","));
                    utArr.add(ut.getAuthTypeAsString().replaceAll("\\s", ","));
                    utArr.add(ut.getThrottlingTiersAsString().replaceAll("\\s", ","));
                    NativeArray utNArr = new NativeArray(utArr.size());
                    for (int p = 0; p < utArr.size(); p++) {
                        utNArr.put(p, utNArr, utArr.get(p));
                    }
                    uriTemplatesArr.add(utNArr);
                }

                for (int c = 0; c < uriTemplatesArr.size(); c++) {
                    uriTempArr.put(c, uriTempArr, uriTemplatesArr.get(c));
                }

                myn.put(12, myn, uriTempArr);
            }

            myn.put(13, myn, checkValue(api.getSandboxUrl()));
            myn.put(14, myn, checkValue(tiersDescSet.toString()));
            myn.put(15, myn, checkValue(api.getBusinessOwner()));
            myn.put(16, myn, checkValue(api.getBusinessOwnerEmail()));
            myn.put(17, myn, checkValue(api.getTechnicalOwner()));
            myn.put(18, myn, checkValue(api.getTechnicalOwnerEmail()));
            myn.put(19, myn, checkValue(api.getWadlUrl()));
            myn.put(20, myn, checkValue(api.getVisibility()));
            myn.put(21, myn, checkValue(api.getVisibleRoles()));
            myn.put(22, myn, checkValue(api.getVisibleTenants()));
            myn.put(23, myn, checkValue(api.getEndpointUTUsername()));
            myn.put(24, myn, checkValue(api.getEndpointUTPassword()));
            myn.put(25, myn, checkValue(Boolean.toString(api.isEndpointSecured())));
            myn.put(26, myn, APIUtil.replaceEmailDomainBack(checkValue(api.getId().getProviderName())));
            myn.put(27, myn, checkTransport("http", api.getTransports()));
            myn.put(28, myn, checkTransport("https", api.getTransports()));
            Set<APIStore> storesSet = apiProvider.getExternalAPIStores(api.getId());
            if (storesSet != null && storesSet.size() != 0) {
                NativeArray apiStoresArray = new NativeArray(0);
                int i = 0;
                for (APIStore store : storesSet) {
                    NativeObject storeObject = new NativeObject();
                    storeObject.put("name", storeObject, store.getName());
                    storeObject.put("displayName", storeObject, store.getDisplayName());
                    storeObject.put("published", storeObject, store.isPublished());
                    apiStoresArray.put(i, apiStoresArray, storeObject);
                    i++;
                }
                myn.put(29, myn, apiStoresArray);
            }
            myn.put(30, myn, checkValue(api.getInSequence()));
            myn.put(31, myn, checkValue(api.getOutSequence()));

            myn.put(32, myn, checkValue(api.getSubscriptionAvailability()));
            myn.put(33, myn, checkValue(api.getSubscriptionAvailableTenants()));

            //@todo need to handle backword compatibility
            myn.put(34, myn, checkValue(api.getEndpointConfig()));

            myn.put(35, myn, checkValue(api.getResponseCache()));
            myn.put(36, myn, checkValue(Integer.toString(api.getCacheTimeout())));
            myn.put(37, myn, checkValue(tiersDisplayNamesSet.toString()));

            myn.put(38, myn, checkValue(api.getFaultSequence()));

            //todo implement resource load

            if (uriTemplates.size() != 0) {
                JSONArray resourceArray = new JSONArray();
                Iterator i = uriTemplates.iterator();
                List<NativeArray> uriTemplatesArr = new ArrayList<NativeArray>();
                while (i.hasNext()) {
                    JSONObject resourceObj = new JSONObject();
                    URITemplate ut = (URITemplate) i.next();

                    resourceObj.put("url_pattern", ut.getUriTemplate());
                    resourceObj.put("http_verbs", JSONValue.parse(ut.getResourceMap()));

                    resourceArray.add(resourceObj);
                }

                myn.put(40, myn, JSONValue.toJSONString(resourceArray));
            }

            Set<Scope> scopes = api.getScopes();
            JSONArray scopesNative = new JSONArray();
            for (Scope scope : scopes) {
                JSONObject scopeNative = new JSONObject();
                scopeNative.put("id", scope.getId());
                scopeNative.put("key", scope.getKey());
                scopeNative.put("name", scope.getName());
                scopeNative.put("roles", scope.getRoles());
                scopeNative.put("description", scope.getDescription());
                scopesNative.add(scopeNative);
            }
            myn.put(41, myn, scopesNative.toJSONString());
            myn.put(42, myn, checkValue(Boolean.toString(api.isDefaultVersion())));
            myn.put(43, myn, api.getImplementation());
            myn.put(44, myn, APIUtil.writeEnvironmentsToArtifact(api));
            //get new key manager
            KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance();
            Map registeredResource = keyManager.getResourceByApiId(api.getId().toString());
            myn.put(45, myn, JSONObject.toJSONString(registeredResource));
            myn.put(46, myn, checkValue(api.getProductionMaxTps()));
            myn.put(47, myn, checkValue(api.getSandboxMaxTps()));
            myn.put(48, myn, checkValue(Boolean.toString(api.isEndpointAuthDigest())));
            CORSConfiguration corsConfigurationDto = api.getCorsConfiguration();
            if (corsConfigurationDto == null) {
                corsConfigurationDto = new CORSConfiguration(false, Collections.EMPTY_LIST, false,
                        Collections.EMPTY_LIST, Collections.EMPTY_LIST);
            }
            String corsJson = APIUtil.getCorsConfigurationJsonFromDto(corsConfigurationDto);
            myn.put(49, myn, corsJson);

            StringBuilder policiesSet = new StringBuilder("");

            myn.put(50, myn, checkValue(policiesSet.toString()));
            myn.put(51, myn, checkValue(api.getApiLevelPolicy()));

        } else {
            handleException("Cannot find the requested API- " + apiName + "-" + version);
        }
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return myn;
}