Example usage for org.json.simple JSONArray isEmpty

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

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:org.jitsi.videobridge.rest.JSONDeserializer.java

public static void deserializeSctpConnections(JSONArray sctpConnections,
        ColibriConferenceIQ.Content contentIQ) {
    if ((sctpConnections != null) && !sctpConnections.isEmpty()) {
        for (Object sctpConnection : sctpConnections) {
            deserializeSctpConnection((JSONObject) sctpConnection, contentIQ);
        }// w  w w . j av  a  2 s . c  o  m
    }
}

From source file:org.jitsi.videobridge.rest.JSONDeserializer.java

public static void deserializeSourceGroups(JSONArray sourceGroups, ColibriConferenceIQ.Channel channelIQ) {
    if ((sourceGroups != null) && !sourceGroups.isEmpty()) {
        for (Object sourceGroup : sourceGroups)
            deserializeSourceGroup(sourceGroup, channelIQ);
    }/*from  w  w w  .  j  av  a  2 s . com*/
}

From source file:org.jitsi.videobridge.rest.JSONDeserializer.java

public static void deserializeSources(JSONArray sources, ColibriConferenceIQ.Channel channelIQ) {
    if ((sources != null) && !sources.isEmpty()) {
        for (Object source : sources)
            deserializeSource(source, channelIQ);
    }//w ww  .j  a  va2s  . c om
}

From source file:org.jitsi.videobridge.rest.JSONDeserializer.java

public static void deserializeSSRCs(JSONArray ssrcs, ColibriConferenceIQ.Channel channelIQ) {
    if ((ssrcs != null) && !ssrcs.isEmpty()) {
        for (Object ssrc : ssrcs) {
            int ssrcIQ;

            try {
                ssrcIQ = deserializeSSRC(ssrc);
            } catch (NumberFormatException nfe) {
                continue;
            }//  w w  w.j a v  a2  s .  co m

            channelIQ.addSSRC(ssrcIQ);
        }
    }
}

From source file:org.opencastproject.scheduler.endpoint.SchedulerRestService.java

@PUT
@Produces(MediaType.TEXT_PLAIN)//from  www .j a  v  a 2  s . com
@Path("bulkaction")
@RestQuery(name = "bulkaction", description = "Updates the dublin core catalog of a set of recordings.", returnDescription = "No body returned.", restParameters = {
        @RestParameter(name = "idlist", description = "JSON Array of ids.", isRequired = true, type = Type.STRING),
        @RestParameter(name = "dublinecore", description = "The dublin core catalog of updated fields", isRequired = true, type = Type.STRING) }, reponses = {
                @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "Events were updated successfully.") })
public Response bulkUpdate(@FormParam("idlist") String idList, @FormParam("dublincore") String dublinCore) {
    JSONParser parser = new JSONParser();
    JSONArray ids = new JSONArray();
    DublinCoreCatalog eventCatalog;
    try {
        if (idList != null && !idList.isEmpty()) {
            ids = (JSONArray) parser.parse(idList);
        }
    } catch (ParseException e) {
        logger.warn("Unable to parse json id list: {}", e);
        return Response.status(Status.BAD_REQUEST).build();
    }
    if (StringUtils.isNotEmpty(dublinCore)) {
        try {
            eventCatalog = parseDublinCore(dublinCore);
        } catch (Exception e) {
            logger.warn("Could not parse Dublin core catalog: {}", e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    } else {
        logger.warn("Cannot add event without dublin core catalog.");
        return Response.status(Status.BAD_REQUEST).build();
    }
    if (!ids.isEmpty() && eventCatalog != null) {
        try {
            service.updateEvents(mlist(ids).map(Misc.<Object, Long>cast()).value(), eventCatalog);
            return Response.noContent().type("").build(); // remove content-type, no message-body.
        } catch (Exception e) {
            logger.warn("Unable to update event with id " + ids.toString() + ": {}", e);
            return Response.serverError().build();
        }
    } else {
        return Response.status(Status.BAD_REQUEST).build();
    }
}

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

/**
 * This returns the json string containing the role permissions for a given API
 *
 * @param connection - DB connection/*from  ww w .j a  v a 2s .c  o m*/
 * @param apiId      - apiId of the API
 * @return permission string
 * @throws SQLException - if error occurred while getting permissionMap of API from DB
 */
private String getPermissionsStringForApi(Connection connection, String apiId) throws SQLException {
    JSONArray permissionArray = new JSONArray();
    Map<String, Integer> permissionMap = getPermissionMapForApi(connection, apiId);
    for (Map.Entry<String, Integer> entry : permissionMap.entrySet()) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(APIMgtConstants.Permission.GROUP_ID, entry.getKey());
        jsonObject.put(APIMgtConstants.Permission.PERMISSION,
                APIUtils.constructApiPermissionsListForValue(entry.getValue()));
        permissionArray.add(jsonObject);
    }
    if (!permissionArray.isEmpty()) {
        return permissionArray.toString();
    } else {
        return "";
    }
}

From source file:org.wso2.carbon.apimgt.impl.definitions.APIDefinitionFromOpenAPISpec.java

/**
 * This method generates swagger 2.0 definition to the given api
 *
 * @param api api/*from   ww w.ja  v a2  s.c om*/
 * @return swagger v2.0 doc as string
 * @throws APIManagementException
 */
@Override
@SuppressWarnings("unchecked")
public String generateAPIDefinition(API api) throws APIManagementException {
    APIIdentifier identifier = api.getId();
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();

    Environment environment = (Environment) config.getApiGatewayEnvironments().values().toArray()[0];
    String endpoints = environment.getApiGatewayEndpoint();
    String[] endpointsSet = endpoints.split(",");
    Set<URITemplate> uriTemplates = api.getUriTemplates();
    Set<Scope> scopes = api.getScopes();

    if (endpointsSet.length < 1) {
        throw new APIManagementException(
                "Error in creating JSON representation of the API" + identifier.getApiName());
    }

    JSONObject swaggerObject = new JSONObject();

    //Create info object
    JSONObject infoObject = new JSONObject();
    infoObject.put(APIConstants.SWAGGER_TITLE, identifier.getApiName());
    if (api.getDescription() != null) {
        infoObject.put(APIConstants.SWAGGER_DESCRIPTION, api.getDescription());
    }

    //Create contact object and map business owner info
    JSONObject contactObject = new JSONObject();
    if (api.getBusinessOwner() != null) {
        contactObject.put(APIConstants.SWAGGER_NAME, api.getBusinessOwner());
    }
    if (api.getBusinessOwnerEmail() != null) {
        contactObject.put(APIConstants.SWAGGER_EMAIL, api.getBusinessOwnerEmail());
    }
    if (api.getBusinessOwner() != null || api.getBusinessOwnerEmail() != null) {
        //put contact object to info object
        infoObject.put(APIConstants.SWAGGER_CONTACT, contactObject);
    }

    //Create licence object # no need for this since this is not mandatory
    //JSONObject licenceObject = new JSONObject();
    //infoObject.put("license", licenceObject);

    infoObject.put(APIConstants.SWAGGER_VER, identifier.getVersion());

    //add info object to swaggerObject
    swaggerObject.put(APIConstants.SWAGGER_INFO, infoObject);

    JSONObject pathsObject = new JSONObject();

    for (URITemplate uriTemplate : uriTemplates) {
        addOrUpdatePathsFromURITemplate(pathsObject, uriTemplate);
    }

    swaggerObject.put(APIConstants.SWAGGER_PATHS, pathsObject);
    swaggerObject.put(APIConstants.SWAGGER, APIConstants.SWAGGER_V2);

    JSONObject securityDefinitionObject = new JSONObject();
    JSONObject scopesObject = new JSONObject();

    JSONArray xWso2ScopesArray = new JSONArray();
    JSONObject xWso2ScopesObject;

    JSONObject swaggerScopesObject;//++++++++
    JSONArray xScopesArray = new JSONArray();//+++++++
    JSONObject securityDefinitionJsonObject = new JSONObject();//+++++++
    JSONObject securityDefinitionAttr = new JSONObject();

    if (scopes != null) {
        for (Scope scope : scopes) {
            xWso2ScopesObject = new JSONObject();
            swaggerScopesObject = new JSONObject();//++++++
            swaggerScopesObject.put(scope.getName(), scope.getDescription());//+++++
            xWso2ScopesObject.put(APIConstants.SWAGGER_SCOPE_KEY, scope.getKey());
            xWso2ScopesObject.put(APIConstants.SWAGGER_NAME, scope.getName());
            xWso2ScopesObject.put(APIConstants.SWAGGER_ROLES, scope.getRoles());
            xWso2ScopesObject.put(APIConstants.SWAGGER_DESCRIPTION, scope.getDescription());

            xWso2ScopesArray.add(xWso2ScopesObject);
            xScopesArray.add(swaggerScopesObject);//+++++++++++++
        }
    }

    securityDefinitionJsonObject.put(APIConstants.SWAGGER_SECURITY_TYPE, APIConstants.SWAGGER_SECURITY_OAUTH2);
    securityDefinitionJsonObject.put(APIConstants.SWAGGER_SECURITY_OAUTH2_TOKEN_URL, "https://test.com");//+++
    securityDefinitionJsonObject.put(APIConstants.SWAGGER_SECURITY_OAUTH2_FLOW,
            APIConstants.SWAGGER_SECURITY_OAUTH2_PASSWORD);//++++
    if (!xScopesArray.isEmpty()) {
        securityDefinitionJsonObject.put(APIConstants.SWAGGER_SCOPES, xScopesArray);//++++++++
    }
    securityDefinitionAttr.put(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY, securityDefinitionJsonObject);//++++

    scopesObject.put(APIConstants.SWAGGER_X_WSO2_SCOPES, xWso2ScopesArray);
    securityDefinitionObject.put(APIConstants.SWAGGER_OBJECT_NAME_APIM, scopesObject);

    swaggerObject.put(APIConstants.SWAGGER_X_WSO2_SECURITY, securityDefinitionObject);
    swaggerObject.put(APIConstants.SWAGGER_SECURITY_DEFINITIONS, securityDefinitionAttr);//++++++

    return swaggerObject.toJSONString();
}

From source file:org.wso2.carbon.apimgt.migration.util.ResourceUtil.java

/**
 * Modify the resource in registry location '1.2' to be compatible with the
 * AM 1.8. add the/*w w w.  j  a  va 2s  . c  om*/
 * parameters to operations element, add 'nickname' variable and the
 * 'basePath' variable
 * 
 * @param resource
 *            resource inside the 1.2 location
 * @param allParameters
 *            map containing all the parameters extracted from api-doc
 *            containing
 *            resources for swagger 1.1
 * @param allOperations 
 * @param basePath
 *            base path for the resource
 * @return modified resource for the api
 */
public static String getUpdatedSwagger12Resource(JSONObject resource, Map<String, JSONArray> allParameters,
        Map<String, JSONObject> allOperations, String basePath) {

    JSONArray apis = (JSONArray) resource.get(Constants.API_DOC_12_APIS);
    for (int i = 0; i < apis.size(); i++) {
        JSONObject apiInfo = (JSONObject) apis.get(i);
        String path = (String) apiInfo.get(Constants.API_DOC_12_PATH);
        JSONArray operations = (JSONArray) apiInfo.get(Constants.API_DOC_12_OPERATIONS);

        for (int j = 0; j < operations.size(); j++) {
            JSONObject operation = (JSONObject) operations.get(j);
            String method = (String) operation.get(Constants.API_DOC_12_METHOD);

            // nickname is method name + "_" + path without starting "/"
            // symbol
            String nickname = method.toLowerCase() + "_" + path.substring(1);
            // add nickname variable
            operation.put(Constants.API_DOC_12_NICKNAME, nickname);
            String key = path + "_" + method.toLowerCase();

            JSONArray parameters = new JSONArray();
            if (allParameters.containsKey(key)) {
                parameters = allParameters.get(key);

                //setting the 'type' to 'string' if this variable is missing
                for (int m = 0; m < parameters.size(); m++) {
                    JSONObject para = (JSONObject) parameters.get(m);
                    if (!para.containsKey("type")) {
                        para.put("type", "string");
                    }
                }

            } else {
                parameters = getDefaultParameters();

            }
            //if there are parameters already in this 
            JSONArray existingParams = (JSONArray) operation.get(Constants.API_DOC_12_PARAMETERS);
            if (existingParams.isEmpty()) {
                JSONParser parser = new JSONParser();
                if (path.contains("{")) {
                    List<String> urlParams = ResourceUtil.getURLTemplateParams(path);
                    for (String p : urlParams) {
                        try {
                            JSONObject paramObj = (JSONObject) parser
                                    .parse(Constants.DEFAULT_PARAM_FOR_URL_TEMPLATE);
                            paramObj.put("name", p);
                            parameters.add(paramObj);
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                // add parameters array
                operation.put(Constants.API_DOC_12_PARAMETERS, parameters);
            } else {
                for (int k = 0; k < existingParams.size(); k++) {
                    parameters.add(existingParams.get(k));
                }
                operation.put(Constants.API_DOC_12_PARAMETERS, parameters);
            }

            //updating the resource description and nickname using values in the swagger 1.1 doc
            if (allOperations.containsKey(key)) {

                //update info related to object
                JSONObject operationObj11 = allOperations.get(key);
                //add summery
                if (operationObj11.containsKey("summary")) {
                    operation.put("summary", operationObj11.get("summery"));
                }

            }
        }
    }

    // add basePath variable
    resource.put(Constants.API_DOC_12_BASE_PATH, basePath);

    return resource.toJSONString();
}

From source file:org.wso2.carbon.apimgt.sciquest.keymanager.APIManagerOAuthClient.java

/**
 * This method validates the access token with external OAuth Server
 *
 * @param accessToken - the token which need to be validated
 * @return an {@code AccessTokenInfo} having token validation meta data
 * @throws APIManagementException//w  ww.j av  a  2s .  c  om
 */

public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();
    tokenInfo.setAccessToken(accessToken);

    KeyManagerConfiguration config = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(ClientConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(ClientConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(ClientConstants.INTROSPECTION_CS);
    String encodedSecret = Base64
            .encode(new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {
        URIBuilder uriBuilder = new URIBuilder(introspectionURL);
        uriBuilder.addParameter("access_token", accessToken);
        uriBuilder.build();

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        HttpClient client = new DefaultHttpClient();

        httpGet.setHeader("Authorization", "Basic " + encodedSecret);
        HttpResponse response = client.execute(httpGet);
        int responseCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("HTTP Response code for Token Validation from external OAuth Server: " + responseCode);
        }

        // Response Format from OAuth 2 Server

        /*{
        "audience":"MappedClient",
            "scopes":[
                "test"
            ],
            "principal":{
                "name":"mappedclient",
                "roles":[
                
                ],
                "groups":[
                
                ],
                "adminPrincipal":false,
                "attributes":{
                
                }
            },
            "expires_in":1433059160531
        }*/

        HttpEntity entity = response.getEntity();
        JSONObject parsedObject;
        reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

        if (HttpStatus.SC_OK == responseCode) {
            //pass bufferReader object  and get read it and retrieve  the parsedJson object
            parsedObject = getParsedObjectByReader(reader);
            if (parsedObject != null) {
                Object principal = parsedObject.get("principal");

                if (principal == null) {
                    tokenInfo.setTokenValid(false);
                    return tokenInfo;
                }
                Map principalMap = (Map) principal;
                String clientId = (String) principalMap.get("name");
                Long expiryTimeString = (Long) parsedObject.get("expires_in");

                // Returning false if mandatory attributes are missing.
                if (clientId == null || expiryTimeString == null) {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

                long currentTime = System.currentTimeMillis();
                long expiryTime = expiryTimeString;
                if (expiryTime > currentTime) {
                    tokenInfo.setTokenValid(true);
                    tokenInfo.setConsumerKey(clientId);
                    tokenInfo.setValidityPeriod(expiryTime - currentTime);
                    // Considering Current Time as the issued time.
                    tokenInfo.setIssuedTime(currentTime);
                    JSONArray scopesArray = (JSONArray) parsedObject.get("scopes");

                    if (log.isDebugEnabled()) {
                        StringBuilder tokens = new StringBuilder("[");
                        Iterator iterator = scopesArray.iterator();
                        while (iterator.hasNext()) {
                            tokens.append(iterator.next());
                            if (iterator.hasNext()) {
                                tokens.append(", ");
                            }
                        }
                        tokens.append("]");

                        log.debug("Tokens " + tokens);
                    }

                    if (scopesArray != null && !scopesArray.isEmpty()) {

                        String[] scopes = new String[scopesArray.size()];
                        for (int i = 0; i < scopes.length; i++) {
                            scopes[i] = (String) scopesArray.get(i);
                        }
                        tokenInfo.setScope(scopes);
                    }

                    JSONObject jso = new JSONObject();
                    jso.putAll(principalMap);
                    tokenInfo.setEndUserName(jso.toString());

                    if (log.isDebugEnabled()) {
                        log.debug("Token Response Principle : " + jso.toJSONString());
                    }
                } else {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

            } else {
                log.error("Invalid Token " + accessToken);
                tokenInfo.setTokenValid(false);
                tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                return tokenInfo;
            }
        } //for other HTTP error codes we just pass generic message.
        else {
            log.error("Invalid Token " + accessToken);
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
        }

    } catch (UnsupportedEncodingException e) {
        handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
        handleException(
                "HTTP request error has occurred while sending request  to OAuth Provider. " + e.getMessage(),
                e);
    } catch (IOException e) {
        handleException("Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
        handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return tokenInfo;
}

From source file:org.wso2.carbon.apimgt.swagger.migration.utils.ResourceUtil.java

/**
 * Modify the resource in registry location '1.2' to be compatible with the
 * AM 1.8. add the//from  w  ww  .j ava 2 s  .c  o m
 * parameters to operations element, add 'nickname' variable and the
 * 'basePath' variable
 * 
 * @param resource
 *            resource inside the 1.2 location
 * @param allParameters
 *            map containing all the parameters extracted from api-doc
 *            containing
 *            resources for swagger 1.1
 * @param allOperations 
 * @param basePath
 *            base path for the resource
 * @return modified resource for the api
 */
public static String getUpdatedSwagger12Resource(JSONObject resource, Map<String, JSONArray> allParameters,
        Map<String, JSONObject> allOperations, String basePath) {

    JSONArray apis = (JSONArray) resource.get(Constants.API_DOC_12_APIS);
    for (int i = 0; i < apis.size(); i++) {
        JSONObject apiInfo = (JSONObject) apis.get(i);
        String path = (String) apiInfo.get(Constants.API_DOC_12_PATH);
        JSONArray operations = (JSONArray) apiInfo.get(Constants.API_DOC_12_OPERATIONS);

        for (int j = 0; j < operations.size(); j++) {
            JSONObject operation = (JSONObject) operations.get(j);
            String method = (String) operation.get(Constants.API_DOC_12_METHOD);

            // nickname is method name + "_" + path without starting "/"
            // symbol
            String nickname = method.toLowerCase() + "_" + path.substring(1);
            // add nickname variable
            operation.put(Constants.API_DOC_12_NICKNAME, nickname);
            String key = path + "_" + method.toLowerCase();

            JSONArray parameters = new JSONArray();
            if (allParameters.containsKey(key)) {
                parameters = allParameters.get(key);

                //setting the 'type' to 'string' if this variable is missing
                for (int m = 0; m < parameters.size(); m++) {
                    JSONObject para = (JSONObject) parameters.get(m);
                    if (!para.containsKey("type")) {
                        para.put("type", "string");
                    }
                }

            } else {
                parameters = getDefaultParameters();

            }
            //if there are parameters already in this 
            JSONArray existingParams = (JSONArray) operation.get(Constants.API_DOC_12_PARAMETERS);
            if (existingParams.isEmpty()) {
                JSONParser parser = new JSONParser();
                if (path.contains("{")) {
                    List<String> urlParams = ResourceUtil.getURLTempateParams(path);
                    for (String p : urlParams) {
                        try {
                            JSONObject paramObj = (JSONObject) parser
                                    .parse(Constants.DEFAULT_PARAM_FOR_URL_TEMPLATE);
                            paramObj.put("name", p);
                            parameters.add(paramObj);
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                // add parameters array
                operation.put(Constants.API_DOC_12_PARAMETERS, parameters);
            } else {
                for (int k = 0; k < existingParams.size(); k++) {
                    parameters.add(existingParams.get(k));
                }
                operation.put(Constants.API_DOC_12_PARAMETERS, parameters);
            }

            //updating the resource description and nickname using values in the swagger 1.1 doc
            if (allOperations.containsKey(key)) {

                //update info related to object
                JSONObject operationObj11 = allOperations.get(key);
                //add summery
                if (operationObj11.containsKey("summary")) {
                    operation.put("summary", (String) operationObj11.get("summery"));
                }

            }
        }
    }

    // add basePath variable
    resource.put(Constants.API_DOC_12_BASE_PATH, basePath);

    return resource.toJSONString();
}