List of usage examples for org.json.simple JSONArray toJSONString
public String toJSONString()
From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java
public static NativeArray jsFunction_getSubscriberCountByAPIs(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws APIManagementException { NativeArray myn = new NativeArray(0); String providerName = null;//from w ww . j a va 2 s. co m APIProvider apiProvider = getAPIProvider(thisObj); if (args == null || args.length == 0) { handleException("Invalid input parameters."); } boolean isTenantFlowStarted = false; try { providerName = APIUtil.replaceEmailDomain((String) args[0]); String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerName)); if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { isTenantFlowStarted = true; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } if (providerName != null) { List<API> apiSet; if (providerName.equals("__all_providers__")) { apiSet = apiProvider.getAllAPIs(); } else { apiSet = apiProvider.getAPIsByProvider(APIUtil.replaceEmailDomain(providerName)); } Map<String, Long> subscriptions = new TreeMap<String, Long>(); for (API api : apiSet) { if (api.getStatus() == APIStatus.CREATED) { continue; } long count = apiProvider.getAPISubscriptionCountByAPI(api.getId()); if (count == 0) { continue; } String[] apiData = { api.getId().getApiName(), api.getId().getVersion(), api.getId().getProviderName() }; JSONArray jsonArray = new JSONArray(); jsonArray.add(0, apiData[0]); jsonArray.add(1, apiData[1]); jsonArray.add(2, apiData[2]); String key = jsonArray.toJSONString(); Long currentCount = subscriptions.get(key); if (currentCount != null) { subscriptions.put(key, currentCount + count); } else { subscriptions.put(key, count); } } List<APISubscription> subscriptionData = new ArrayList<APISubscription>(); for (Map.Entry<String, Long> entry : subscriptions.entrySet()) { APISubscription sub = new APISubscription(); sub.name = entry.getKey(); sub.count = entry.getValue(); subscriptionData.add(sub); } int i = 0; for (APISubscription sub : subscriptionData) { NativeObject row = new NativeObject(); row.put("apiName", row, sub.name); row.put("count", row, sub.count); myn.put(i, myn, row); i++; } } } catch (Exception e) { handleException("Error while getting subscribers of the provider: " + providerName, e); } finally { if (isTenantFlowStarted) { PrivilegedCarbonContext.endTenantFlow(); } } return myn; }
From source file:org.wso2.carbon.apimgt.impl.soaptorest.util.SequenceUtils.java
/** * Gets parameter definitions from swagger * * @param swaggerObj swagger json//from ww w .j a v a 2s.com * @param resource rest resource object * @param method http method * @return parameter mapping for a resource from the swagger definitions */ public static List<JSONObject> getResourceParametersFromSwagger(JSONObject swaggerObj, JSONObject resource, String method) { Map content = (HashMap) resource.get(method); JSONArray parameters = (JSONArray) content.get(SOAPToRESTConstants.Swagger.PARAMETERS); List<JSONObject> mappingList = new ArrayList<>(); for (Object param : parameters) { String inputType = String.valueOf(((JSONObject) param).get(SOAPToRESTConstants.Swagger.IN)); if (inputType.equals(SOAPToRESTConstants.Swagger.BODY)) { JSONObject schema = (JSONObject) ((JSONObject) param).get(SOAPToRESTConstants.Swagger.SCHEMA); String definitionPath = String.valueOf(schema.get(SOAPToRESTConstants.Swagger.REF)); String definition = definitionPath.replaceAll(SOAPToRESTConstants.Swagger.DEFINITIONS_ROOT, SOAPToRESTConstants.EMPTY_STRING); JSONObject definitions = (JSONObject) ((JSONObject) swaggerObj .get(SOAPToRESTConstants.Swagger.DEFINITIONS)).get(definition); JSONObject properties = (JSONObject) definitions.get(SOAPToRESTConstants.Swagger.PROPERTIES); for (Object property : properties.entrySet()) { Map.Entry entry = (Map.Entry) property; String paramName = String.valueOf(entry.getKey()); JSONObject value = (JSONObject) entry.getValue(); JSONArray propArray = new JSONArray(); if (value.get(SOAPToRESTConstants.Swagger.REF) != null) { String propDefinitionRef = String.valueOf(value.get(SOAPToRESTConstants.Swagger.REF)) .replaceAll(SOAPToRESTConstants.Swagger.DEFINITIONS_ROOT, SOAPToRESTConstants.EMPTY_STRING); getNestedDefinitionsFromSwagger( (JSONObject) swaggerObj.get(SOAPToRESTConstants.Swagger.DEFINITIONS), propDefinitionRef, propDefinitionRef, propArray); JSONObject refObj = new JSONObject(); refObj.put(paramName, propArray); if (log.isDebugEnabled()) { log.debug("Properties for from resource parameter: " + paramName + " are: " + propArray.toJSONString()); } mappingList.add(refObj); } else if (String.valueOf(value.get(SOAPToRESTConstants.Swagger.TYPE)) .equals(SOAPToRESTConstants.ParamTypes.ARRAY)) { JSONObject arrObj = new JSONObject(); arrObj.put(((Map.Entry) property).getKey(), ((Map.Entry) property).getValue()); mappingList.add(arrObj); if (log.isDebugEnabled()) { log.debug("Properties for from array type resource parameter: " + ((Map.Entry) property).getKey() + " are: " + arrObj.toJSONString()); } } } } else { JSONObject queryObj = new JSONObject(); queryObj.put(((JSONObject) param).get(SOAPToRESTConstants.Swagger.NAME), param); mappingList.add(queryObj); if (log.isDebugEnabled()) { log.debug("Properties for from query type resource parameter: " + queryObj.toJSONString()); } } } return mappingList; }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtilTest.java
@Test public void testIsProductionEndpointsInvalidJSON() throws Exception { Log log = Mockito.mock(Log.class); PowerMockito.mockStatic(LogFactory.class); Mockito.when(LogFactory.getLog(Mockito.any(Class.class))).thenReturn(log); API api = Mockito.mock(API.class); Mockito.when(api.getEndpointConfig()).thenReturn("</SomeXML>"); Assert.assertFalse("Unexpected production endpoint found", APIUtil.isProductionEndpointsExists(api)); JSONObject productionEndpoints = new JSONObject(); productionEndpoints.put("url", "https:\\/\\/localhost:9443\\/am\\/sample\\/pizzashack\\/v1\\/api\\/"); productionEndpoints.put("config", null); JSONArray jsonArray = new JSONArray(); jsonArray.add(productionEndpoints);// ww w . j ava2s . c o m Mockito.when(api.getEndpointConfig()).thenReturn(jsonArray.toJSONString()); Assert.assertFalse("Unexpected production endpoint found", APIUtil.isProductionEndpointsExists(api)); }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtilTest.java
@Test public void testIsSandboxEndpointsInvalidJSON() throws Exception { Log log = Mockito.mock(Log.class); PowerMockito.mockStatic(LogFactory.class); Mockito.when(LogFactory.getLog(Mockito.any(Class.class))).thenReturn(log); API api = Mockito.mock(API.class); Mockito.when(api.getEndpointConfig()).thenReturn("</SomeXML>"); Assert.assertFalse("Unexpected sandbox endpoint found", APIUtil.isSandboxEndpointsExists(api)); JSONObject sandboxEndpoints = new JSONObject(); sandboxEndpoints.put("url", "https:\\/\\/localhost:9443\\/am\\/sample\\/pizzashack\\/v1\\/api\\/"); sandboxEndpoints.put("config", null); JSONArray jsonArray = new JSONArray(); jsonArray.add(sandboxEndpoints);/* w w w . java 2s . c o m*/ Mockito.when(api.getEndpointConfig()).thenReturn(jsonArray.toJSONString()); Assert.assertFalse("Unexpected sandbox endpoint found", APIUtil.isSandboxEndpointsExists(api)); }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtilTierTest.java
/** * Test whether the APIUtil properly converts the billing plan and the custom attributes in the SubscriptionPolicy * when constructing the Tier object./*from w w w. ja v a 2s . c o m*/ */ @Test public void testBillingPlanAndCustomAttr() throws Exception { SubscriptionPolicy policy = new SubscriptionPolicy("JUnitTest"); JSONArray jsonArray = new JSONArray(); JSONObject json1 = new JSONObject(); json1.put("name", "key1"); json1.put("value", "value1"); jsonArray.add(json1); JSONObject json2 = new JSONObject(); json2.put("name", "key2"); json2.put("value", "value2"); jsonArray.add(json2); policy.setCustomAttributes(jsonArray.toJSONString().getBytes()); policy.setBillingPlan("FREE"); Tier tier = new Tier("JUnitTest"); APIUtil.setBillingPlanAndCustomAttributesToTier(policy, tier); Assert.assertTrue("Expected FREE but received " + tier.getTierPlan(), "FREE".equals(tier.getTierPlan())); if ("key1".equals(tier.getTierAttributes().get("name"))) { Assert.assertTrue( "Expected to have 'value1' as the value of 'key1' but found " + tier.getTierAttributes().get("value"), tier.getTierAttributes().get("value").equals("value1")); } if ("key2".equals(tier.getTierAttributes().get("name"))) { Assert.assertTrue( "Expected to have 'value2' as the value of 'key2' but found " + tier.getTierAttributes().get("value"), tier.getTierAttributes().get("value").equals("value2")); } }
From source file:org.wso2.carbon.apimgt.rest.api.admin.utils.mappings.throttling.SubscriptionThrottlePolicyMappingUtil.java
/** * Converts a single Subscription Policy DTO into a model object * * @param dto Subscription policy DTO object * @return Converted Subscription policy model object * @throws UnsupportedThrottleLimitTypeException */// w w w .j a v a 2s .c o m @SuppressWarnings("unchecked") public static SubscriptionPolicy fromSubscriptionThrottlePolicyDTOToModel(SubscriptionThrottlePolicyDTO dto) throws UnsupportedThrottleLimitTypeException { //update mandatory fields such as tenantDomain etc. dto = CommonThrottleMappingUtil.updateDefaultMandatoryFieldsOfThrottleDTO(dto); SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(dto.getPolicyName()); subscriptionPolicy = CommonThrottleMappingUtil.updateFieldsFromDTOToPolicy(dto, subscriptionPolicy); subscriptionPolicy.setBillingPlan(dto.getBillingPlan()); subscriptionPolicy.setRateLimitTimeUnit(dto.getRateLimitTimeUnit()); subscriptionPolicy.setRateLimitCount(dto.getRateLimitCount()); subscriptionPolicy.setStopOnQuotaReach(dto.getStopOnQuotaReach()); List<CustomAttributeDTO> customAttributes = dto.getCustomAttributes(); if (customAttributes != null && customAttributes.size() > 0) { JSONArray customAttrJsonArray = new JSONArray(); for (CustomAttributeDTO customAttributeDTO : customAttributes) { JSONObject attrJsonObj = new JSONObject(); attrJsonObj.put(RestApiConstants.THROTTLING_CUSTOM_ATTRIBUTE_NAME, customAttributeDTO.getName()); attrJsonObj.put(RestApiConstants.THROTTLING_CUSTOM_ATTRIBUTE_VALUE, customAttributeDTO.getValue()); customAttrJsonArray.add(attrJsonObj); } subscriptionPolicy.setCustomAttributes(customAttrJsonArray.toJSONString().getBytes()); } if (StringUtils.isNotBlank(dto.getMonetization().getMonetizationPlan().name())) { String tierMonetizationPlan = dto.getMonetization().getMonetizationPlan().toString(); subscriptionPolicy.setMonetizationPlan(tierMonetizationPlan); if (dto.getMonetization().getProperties() != null) { Map<String, String> tierMonetizationProperties = new HashMap<>(); Map<String, String> props = dto.getMonetization().getProperties(); for (Map.Entry<String, String> entry : props.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); tierMonetizationProperties.put(key, value); } subscriptionPolicy.setMonetizationPlanProperties(tierMonetizationProperties); } } if (dto.getDefaultLimit() != null) { subscriptionPolicy .setDefaultQuotaPolicy(CommonThrottleMappingUtil.fromDTOToQuotaPolicy(dto.getDefaultLimit())); } return subscriptionPolicy; }
From source file:org.wso2.carbon.apimgt.swagger.migration.utils.ResourceUtil.java
/** * @param resource api-doc related to 1.1 definition * @param allParameters12 map containing all the parameters extracted * from each resource of swagger 1.2 * @return JSON string of the updated Swagger 1.1 definition *///from ww w. j a v a2 s . c o m public static String getUpdatedSwagger11Resource(JSONObject resource, Map<String, JSONArray> allParameters12) { log.info("===================== getUpdatedSwagger11Resource ========================="); String resourcePath = (String) resource.get(Constants.API_DOC_11_RESOURCE_PATH); String apiVersion = (String) resource.get(Constants.API_DOC_11_API_VERSION); String resourcePathPrefix = resourcePath + "/" + apiVersion; log.info("resourcePath for 1.1 : " + resourcePath); log.info("apiVersion : " + apiVersion); log.info("resourcePathPrefix : " + resourcePathPrefix); JSONArray apis = (JSONArray) resource.get(Constants.API_DOC_11_APIS); for (Object api : apis) { JSONObject apiInfo = (JSONObject) api; log.info("\n\napiInfo : " + apiInfo.toJSONString()); String path = (String) apiInfo.get(Constants.API_DOC_11_PATH); path = path.substring(resourcePathPrefix.length()); JSONArray operations = (JSONArray) apiInfo.get(Constants.API_DOC_11_OPERATIONS); log.info("\n\noperations : " + operations.toJSONString()); for (Object operation1 : operations) { JSONObject operation = (JSONObject) operation1; log.info("\n\noperation : " + operation); String method = (String) operation.get(Constants.API_DOC_11_METHOD); String key = path + "_" + method.toLowerCase(); log.info("\nkey : " + key); //if there are parameters already in this JSONArray existingParams = (JSONArray) operation.get(Constants.API_DOC_11_PARAMETERS); log.info("\nexistingParams : " + existingParams); //maintain the list of original parameters to avoid duplicates JSONArray originalParams = existingParams; JSONArray parameters; if (allParameters12.containsKey(key)) { log.info("\nallParameters12.containsKey(key) : " + key); parameters = allParameters12.get(key); log.info("\nparameters : " + parameters.toJSONString()); //setting the 'type' to 'string' if this variable is missing for (int m = 0; m < parameters.size(); m++) { JSONObject para = (JSONObject) parameters.get(m); log.info("\n\npara : " + para.toJSONString()); if (noSuchParameter(originalParams, (String) para.get(Constants.API_DOC_11_PARAM_NAME), (String) para.get(Constants.API_DOC_11_PARAM_TYPE))) { log.info("\nnoSuchParameter"); String dataType = ""; if (para.containsKey(Constants.API_DOC_12_DATA_TYPE)) { log.info("\npara.containsKey(Constants.API_DOC_12_DATA_TYPE)"); dataType = (String) para.get(Constants.API_DOC_12_DATA_TYPE); } log.info("\ndataType : " + dataType); para.put(Constants.API_DOC_11_DATA_TYPE, dataType); para.remove(Constants.API_DOC_12_DATA_TYPE); existingParams.add(existingParams.size(), para); } } } log.info("\nexistingParams after loop : " + existingParams); operation.put(Constants.API_DOC_12_PARAMETERS, existingParams); } } return resource.toJSONString(); }
From source file:org.wso2.carbon.apimgt.swagger.migration.utils.ResourceUtil.java
/** * Get all the parameters related to each resource. The parameter array is * an array which is part of the operations object inside each resource. * * @param resource resource doc which contains swagger 1.2 info for one resource of the API * @return map of parameter array related to all the http methods for each * resource. the key for/*ww w .j a v a2 s. co m*/ * the map is resourcepath_httpmethod */ public static Map<String, JSONArray> getAllParametersForResources12(JSONObject resource) { Map<String, JSONArray> parameters = new HashMap<String, JSONArray>(); log.info("\ngetAllParametersForResources12"); String key; JSONArray apis = (JSONArray) resource.get(Constants.API_DOC_12_APIS); log.info("\napis : " + apis.toJSONString()); for (Object api : apis) { JSONObject apiInfo = (JSONObject) api; String path = (String) apiInfo.get(Constants.API_DOC_12_PATH); JSONArray operations = (JSONArray) apiInfo.get(Constants.API_DOC_12_OPERATIONS); for (Object operation1 : operations) { JSONObject operation = (JSONObject) operation1; String httpMethod = (String) operation.get(Constants.API_DOC_12_METHOD); JSONArray parameterArray = (JSONArray) operation.get(Constants.API_DOC_12_PARAMETERS); // get the key by removing the "apiVersion" and "resourcePath" // from the "path" variable // and concat the http method String keyPrefix = path; if (keyPrefix.isEmpty()) { keyPrefix = "/*"; } key = keyPrefix + "_" + httpMethod.toLowerCase(); log.info("\nkey : " + key); log.info("\nparameterArray : " + parameterArray.toJSONString()); parameters.put(key, parameterArray); } } return parameters; }
From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRdbmsClientImpl.java
/** * Returns a list of APIUsageDTO objects that contain information related to APIs that * belong to a particular provider and the number of total API calls each API has processed * up to now. This method does not distinguish between different API versions. That is all * versions of a single API are treated as one, and their individual request counts are summed * up to calculate a grand total per each API. * //from w w w . j a v a 2s . co m * @param providerName Name of the API provider * @return a List of APIUsageDTO objects - possibly empty * @throws org.wso2.carbon.apimgt.usage.client.exception.APIMgtUsageQueryServiceClientException if an error occurs * while contacting backend services */ @Override public List<APIUsageDTO> getProviderAPIUsage(String providerName, String fromDate, String toDate, int limit) throws APIMgtUsageQueryServiceClientException { Collection<APIUsage> usageData = getAPIUsageData( APIUsageStatisticsClientConstants.API_VERSION_USAGE_SUMMARY, fromDate, toDate); List<API> providerAPIs = getAPIsByProvider(providerName); Map<String, APIUsageDTO> usageByAPIs = new TreeMap<String, APIUsageDTO>(); for (APIUsage usage : usageData) { for (API providerAPI : providerAPIs) { if (providerAPI.getId().getApiName().equals(usage.getApiName()) && providerAPI.getId().getVersion().equals(usage.getApiVersion()) && providerAPI.getContext().equals(usage.getContext())) { String[] apiData = { usage.getApiName(), usage.getApiVersion(), providerAPI.getId().getProviderName() }; JSONArray jsonArray = new JSONArray(); jsonArray.add(0, apiData[0]); jsonArray.add(1, apiData[1]); jsonArray.add(2, apiData[2]); String apiName = jsonArray.toJSONString(); APIUsageDTO usageDTO = usageByAPIs.get(apiName); if (usageDTO != null) { usageDTO.setCount(usageDTO.getCount() + usage.getRequestCount()); } else { usageDTO = new APIUsageDTO(); usageDTO.setApiName(apiName); usageDTO.setCount(usage.getRequestCount()); usageByAPIs.put(apiName, usageDTO); } } } } return getAPIUsageTopEntries(new ArrayList<APIUsageDTO>(usageByAPIs.values()), limit); }
From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java
/** * Returns a list of APIUsageDTO objects that contain information related to APIs that * belong to a particular provider and the number of total API calls each API has processed * up to now. This method does not distinguish between different API versions. That is all * versions of a single API are treated as one, and their individual request counts are summed * up to calculate a grand total per each API. * * @param providerName Name of the API provider * @return a List of APIUsageDTO objects - possibly empty * @throws org.wso2.carbon.apimgt.usage.client.exception.APIMgtUsageQueryServiceClientException if an error occurs * while contacting * backend services *//* w w w.jav a 2 s . c o m*/ @Override public List<APIUsageDTO> getProviderAPIUsage(String providerName, String fromDate, String toDate, int limit) throws APIMgtUsageQueryServiceClientException { String tenantDomain = MultitenantUtils.getTenantDomain(providerName); if (providerName.contains(APIUsageStatisticsClientConstants.ALL_PROVIDERS)) { providerName = APIUsageStatisticsClientConstants.ALL_PROVIDERS; } Collection<APIUsage> usageData = getAPIUsageData(APIUsageStatisticsClientConstants.API_VERSION_PER_APP_AGG, tenantDomain, fromDate, toDate); List<API> providerAPIs = getAPIsByProvider(providerName); Map<String, APIUsageDTO> usageByAPIs = new TreeMap<String, APIUsageDTO>(); for (APIUsage usage : usageData) { for (API providerAPI : providerAPIs) { if (providerAPI.getId().getApiName().equals(usage.getApiName()) && providerAPI.getId().getVersion().equals(usage.getApiVersion()) && providerAPI.getContext().equals(usage.getContext())) { String[] apiData = { usage.getApiName(), usage.getApiVersion(), providerAPI.getId().getProviderName() }; JSONArray jsonArray = new JSONArray(); jsonArray.add(0, apiData[0]); jsonArray.add(1, apiData[1]); jsonArray.add(2, apiData[2]); String apiName = jsonArray.toJSONString(); APIUsageDTO usageDTO = usageByAPIs.get(apiName); if (usageDTO != null) { usageDTO.setCount(usageDTO.getCount() + usage.getRequestCount()); } else { usageDTO = new APIUsageDTO(); usageDTO.setApiName(apiName); usageDTO.setCount(usage.getRequestCount()); usageByAPIs.put(apiName, usageDTO); } } } } return getAPIUsageTopEntries(new ArrayList<APIUsageDTO>(usageByAPIs.values()), limit); }