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:at.ac.tuwien.dsg.quelle.elasticityQuantification.dtos.CloudServiceConfigurationRecommendation.java

public JSONObject toJSON() {
    JSONObject jsonDescription = new JSONObject();
    jsonDescription.put("serviceUnit", serviceUnit.getName());

    //quality options
    {/*  ww  w. jav a2 s  .c  o m*/
        JSONArray array = new JSONArray();
        for (Quality quality : chosenQualityOptions) {

            JSONObject qualityDescription = new JSONObject();
            jsonDescription.put("quality", quality.getName());
            JSONArray qualityProperties = new JSONArray();

            for (Map.Entry<Metric, MetricValue> property : quality.getProperties().entrySet()) {
                JSONObject jsonPropertyDescription = new JSONObject();
                jsonPropertyDescription.put("property",
                        property.getKey().getName() + " [" + property.getKey().getMeasurementUnit() + "]");
                jsonPropertyDescription.put("value", property.getValue().getValueRepresentation());
                qualityProperties.add(jsonPropertyDescription);
            }
            qualityDescription.put("properties", qualityProperties);
            array.add(qualityDescription);
        }

        if (!array.isEmpty()) {
            jsonDescription.put("optionalQualitiesRecommended", array);
        }
    }

    //resource options
    {
        JSONArray array = new JSONArray();
        for (Resource resource : chosenResourceOptions) {

            JSONObject qualityDescription = new JSONObject();
            jsonDescription.put("resource", resource.getName());
            JSONArray qualityProperties = new JSONArray();

            for (Map.Entry<Metric, MetricValue> property : resource.getProperties().entrySet()) {
                JSONObject jsonPropertyDescription = new JSONObject();
                jsonPropertyDescription.put("property",
                        property.getKey().getName() + " [" + property.getKey().getMeasurementUnit() + "]");
                jsonPropertyDescription.put("value", property.getValue().getValueRepresentation());
                qualityProperties.add(jsonPropertyDescription);
            }
            qualityDescription.put("resources", qualityProperties);
            array.add(qualityDescription);
        }

        if (!array.isEmpty()) {
            jsonDescription.put("optionalResourcesRecommended", array);
        }
    }

    //mandatory service units
    {
        JSONArray array = new JSONArray();
        for (ServiceUnitConfigurationSolution configurationSolution : mandatoryAssociatedServiceUnits) {
            array.add(configurationSolution.toJSON());
        }
        if (!array.isEmpty()) {
            jsonDescription.put("mandatoryAssociatedServiceUnitsRecommendedConfigurations", array);
        }
    }

    //optional service units
    {
        JSONArray array = new JSONArray();
        for (ServiceUnitConfigurationSolution configurationSolution : optionallyAssociatedServiceUnits) {
            array.add(configurationSolution.toJSON());
        }
        if (!array.isEmpty()) {
            jsonDescription.put("optionalAssociatedServiceUnitsRecommendedConfigurations", array);
        }
    }

    return jsonDescription;
}

From source file:at.ac.tuwien.dsg.quelle.elasticityQuantification.requirements.ServiceUnitConfigurationSolution.java

public JSONObject toJSON() {
    JSONObject jsonDescription = new JSONObject();
    jsonDescription.put("serviceUnit", serviceUnit.getName());

    //quality options
    {/*from  w  w w.  j a  v a2s .c  om*/
        JSONArray array = new JSONArray();
        for (RequirementsMatchingEngine.RequirementsMatchingReport<Quality> qualityReport : chosenQualityOptions) {

            Quality quality = qualityReport.getConcreteConfiguration();
            JSONObject qualityDescription = new JSONObject();
            jsonDescription.put("quality", quality.getName());
            JSONArray qualityProperties = new JSONArray();

            for (Map.Entry<Metric, MetricValue> property : quality.getProperties().entrySet()) {
                JSONObject jsonPropertyDescription = new JSONObject();
                jsonPropertyDescription.put("property",
                        property.getKey().getName() + " [" + property.getKey().getMeasurementUnit() + "]");
                jsonPropertyDescription.put("value", property.getValue().getValueRepresentation());
                qualityProperties.add(jsonPropertyDescription);
            }
            qualityDescription.put("properties", qualityProperties);
            array.add(qualityDescription);
        }

        if (!array.isEmpty()) {
            jsonDescription.put("optionalQualitiesRecommended", array);
        }
    }

    //resource options
    {
        JSONArray array = new JSONArray();
        for (RequirementsMatchingEngine.RequirementsMatchingReport<Resource> qualityReport : chosenResourceOptions) {

            Resource quality = qualityReport.getConcreteConfiguration();
            JSONObject qualityDescription = new JSONObject();
            jsonDescription.put("resource", quality.getName());
            JSONArray qualityProperties = new JSONArray();

            for (Map.Entry<Metric, MetricValue> property : quality.getProperties().entrySet()) {
                JSONObject jsonPropertyDescription = new JSONObject();
                jsonPropertyDescription.put("property",
                        property.getKey().getName() + " [" + property.getKey().getMeasurementUnit() + "]");
                jsonPropertyDescription.put("value", property.getValue().getValueRepresentation());
                qualityProperties.add(jsonPropertyDescription);
            }
            qualityDescription.put("resources", qualityProperties);
            array.add(qualityDescription);
        }

        if (!array.isEmpty()) {
            jsonDescription.put("optionalResourcesRecommended", array);
        }
    }

    //mandatory service units
    {
        JSONArray array = new JSONArray();
        for (ServiceUnitConfigurationSolution configurationSolution : mandatoryAssociatedServiceUnits) {
            array.add(configurationSolution.toJSON());
        }
        if (!array.isEmpty()) {
            jsonDescription.put("mandatoryAssociatedServiceUnitsRecommendedConfigurations", array);
        }
    }

    //optional service units
    {
        JSONArray array = new JSONArray();
        for (ServiceUnitConfigurationSolution configurationSolution : optionallyAssociatedServiceUnits) {
            array.add(configurationSolution.toJSON());
        }
        if (!array.isEmpty()) {
            jsonDescription.put("optionalAssociatedServiceUnitsRecommendedConfigurations", array);
        }
    }

    return jsonDescription;
}

From source file:at.ac.tuwien.dsg.quelle.sesConfigurationsRecommendationService.control.RequirementsManagementController.java

private void processAddToRequirementsJSONCommand(String json) {

    //TODO: To actually  get the names from somwehere and conditions and etc. I need to do a bit more management
    //JSON looks like { "command" : "add", "type": "' + type+ '" "trace" : [{"name" : "ServiceReqs_overall_elasticity_multi", "type" : "SERVICE"}]};
    Object command = JSONValue.parse(json);
    JSONObject jSONcommandObject = (JSONObject) command;
    JSONObject metaInfo = (JSONObject) jSONcommandObject.get("meta");

    String whatToAdd = jSONcommandObject.get("type").toString();
    JSONArray trace = (JSONArray) jSONcommandObject.get("trace");

    JSONObject jSONRootObject = (JSONObject) trace.remove(0);
    String namejSONRootObject = jSONRootObject.get("name").toString();
    String typejSONRootObject = jSONRootObject.get("type").toString();

    //in order we traverse from root
    if (!requirements.getName().equals(namejSONRootObject)
            || !requirements.getLevel().toString().equals(typejSONRootObject)) {
        throw new RuntimeException("Something bad, as The requirements root does not match");
    }/*w  w w . j a  v  a 2 s .  co  m*/

    //we go one by one with JSON and get corect requirements children
    //first we get through the multi level requirements
    MultiLevelRequirements currentReqs = requirements;

    while (!currentReqs.getContainedElements().isEmpty() && !trace.isEmpty()) {
        {
            Object obj = trace.get(0);
            boolean discovered = false;
            JSONObject jSONObject = (JSONObject) obj;
            String name = jSONObject.get("name").toString();
            String type = jSONObject.get("type").toString();
            for (MultiLevelRequirements r : currentReqs.getContainedElements()) {
                if (r.getName().equals(name) && r.getLevel().toString().equals(type)) {
                    currentReqs = r;
                    discovered = true;
                    break;
                }
            }
            //so If for example I want to add Requirement on Requirements from Service, it will not be found in the MultiLevelRequirements (topology)
            //so, i need to keep it
            if (discovered) {
                trace.remove(0);
            } else {
                //if not discovered after a run, break while loop
                break;
            }
        }
    }
    //here we are at a point in which we need to start looking in individual requirements blocks, then individual requirements, then conditions
    //only if we add Requirements or Conditions. Otherwise all work on multi level reqs
    switch (whatToAdd) {
    case "Strategy": {

        String strategyType = metaInfo.get("strategy").toString();
        Strategy s = new Strategy().withCategoryString(strategyType);

        if (!currentReqs.getOptimizationStrategies().contains(s)) {
            currentReqs.addStrategy(s);
        }
        break;
    }
    case "Topology": {
        MultiLevelRequirements levelRequirements = new MultiLevelRequirements(
                MonitoredElement.MonitoredElementLevel.SERVICE_TOPOLOGY);
        String topologyName = metaInfo.get("name").toString();
        levelRequirements.setName(topologyName);
        if (!currentReqs.getContainedElements().contains(levelRequirements)) {
            currentReqs.addMultiLevelRequirements(levelRequirements);
        }
    }
        break;
    case "Unit": {
        MultiLevelRequirements levelRequirements = new MultiLevelRequirements(
                MonitoredElement.MonitoredElementLevel.SERVICE_UNIT);
        String unitName = metaInfo.get("name").toString();
        levelRequirements.setName(unitName);
        if (!currentReqs.getContainedElements().contains(levelRequirements)) {
            currentReqs.addMultiLevelRequirements(levelRequirements);
        }
    }
        break;
    case "Requirements": {

        Requirements requirements = new Requirements();
        String name = metaInfo.get("name").toString();

        requirements.setName(name);
        if (!currentReqs.getUnitRequirements().contains(requirements)) {
            currentReqs.addRequirements(requirements);
        }
    }
        break;
    case "Requirement": //here we need to continue to get the targeted Requirements block
    {

        Object obj = trace.remove(0);
        JSONObject jSONObject = (JSONObject) obj;
        String name = jSONObject.get("name").toString();
        String type = jSONObject.get("type").toString();
        for (Requirements r : currentReqs.getUnitRequirements()) {
            if (r.getName().equals(name)) {
                Requirement requirement = new Requirement();
                JSONObject metricInfo = (JSONObject) metaInfo.get("metric");
                Metric metric = new Metric(metricInfo.get("name").toString(),
                        metricInfo.get("unit").toString());
                switch (metricInfo.get("type").toString()) {
                case "COST":
                    metric.setType(Metric.MetricType.COST);
                    break;
                case "RESOURCE":
                    metric.setType(Metric.MetricType.RESOURCE);
                    break;
                case "QUALITY":
                    metric.setType(Metric.MetricType.QUALITY);
                    break;

                }

                //                                                + ', "unit": "' + selectedMetric.unit + '", "type":"' + selectedMetric.type + '"}';
                requirement.setName(metricInfo.get("name").toString());
                requirement.setMetric(metric);

                r.addRequirement(requirement);
                break;
            }
        }
    }
        break;
    case "Condition": //here we also need to get the requirement
    {
        Object obj = trace.remove(0);
        JSONObject jSONObject = (JSONObject) obj;
        String name = jSONObject.get("name").toString();
        String type = jSONObject.get("type").toString();
        for (Requirements r : currentReqs.getUnitRequirements()) {
            if (r.getName().equals(name)) {
                Object reqObj = trace.remove(0);
                JSONObject reqjSONObject = (JSONObject) reqObj;
                String reqname = reqjSONObject.get("name").toString();
                String reqtype = reqjSONObject.get("type").toString();

                for (Requirement req : r.getRequirements()) {
                    if (req.getName().equals(reqname)) {

                        Condition condition = new Condition();

                        //                                var selectedConditionType = conditionTypeSelect.options[conditionTypeSelect.selectedIndex];
                        //                                        var conditionData = '{ "type":"' + selectedConditionType.text + '"'
                        //                                                + ', "value": "' + f.conditionValue.text + '"}';
                        //                                        data = '{' + data + ', "meta" : { "condition":' + conditionData + ' } ' + '}';
                        JSONObject conditionJSON = (JSONObject) metaInfo.get("condition");

                        switch (conditionJSON.get("type").toString()) {
                        case "LESS_THAN":
                            condition.setType(Condition.Type.LESS_THAN);
                            break;
                        case "LESS_EQUAL":
                            condition.setType(Condition.Type.LESS_EQUAL);
                            break;
                        case "GREATER_THAN":
                            condition.setType(Condition.Type.GREATER_THAN);
                            break;
                        case "GREATER_EQUAL":
                            condition.setType(Condition.Type.GREATER_EQUAL);
                            break;
                        case "EQUAL":
                            condition.setType(Condition.Type.EQUAL);
                            break;
                        case "RANGE":
                            condition.setType(Condition.Type.RANGE);
                            break;
                        case "ENUMERATION":
                            condition.setType(Condition.Type.ENUMERATION);
                            break;
                        }

                        List<MetricValue> metricValues = new ArrayList<>();
                        metricValues.add(new MetricValue(conditionJSON.get("value").toString()));
                        condition.setValue(metricValues);

                        req.addCondition(condition);

                        break;
                    }
                }
                break;
            }
        }

    }

    }
}

From source file:at.ac.tuwien.dsg.quelle.sesConfigurationsRecommendationService.control.RequirementsManagementController.java

private void processRemoveRequirementsJSONCommand(String json) {

    //use META DATA FIELDs for rest of details for adding/removing shit
    //TODO: To actually  get the names from somwehere and conditions and etc. I need to do a bit more management
    //JSON looks like { "command" : "add", "type": "' + type+ '" "trace" : [{"name" : "ServiceReqs_overall_elasticity_multi", "type" : "SERVICE"}]};
    Object command = JSONValue.parse(json);
    JSONObject jSONcommandObject = (JSONObject) command;

    String whatToRemove = jSONcommandObject.get("type").toString();
    JSONArray trace = (JSONArray) jSONcommandObject.get("trace");

    JSONObject jSONRootObject = (JSONObject) trace.remove(0);
    String namejSONRootObject = jSONRootObject.get("name").toString();
    String typejSONRootObject = jSONRootObject.get("type").toString();

    //in order we traverse from root
    if (!requirements.getName().equals(namejSONRootObject)
            || !requirements.getLevel().toString().equals(typejSONRootObject)) {
        throw new RuntimeException("Something bad, as The requirements root does not match");
    }//w ww  .  ja  v a  2  s .c  o  m

    //we go one by one with JSON and get corect requirements children
    //first we get through the multi level requirements
    MultiLevelRequirements previousReqs = null;
    MultiLevelRequirements currentReqs = requirements;

    while (!currentReqs.getContainedElements().isEmpty() && !trace.isEmpty()) {
        {
            Object obj = trace.get(0);
            JSONObject jSONObject = (JSONObject) obj;
            String name = jSONObject.get("name").toString();
            String type = jSONObject.get("type").toString();
            boolean somethingMatched = false;
            for (MultiLevelRequirements r : currentReqs.getContainedElements()) {
                if (r.getName().equals(name) && r.getLevel().toString().equals(type)) {
                    previousReqs = currentReqs;
                    currentReqs = r;

                    //if we matched, remove it from trace, else leave it for future matching
                    trace.remove(0);
                    somethingMatched = true;
                    break;
                }
            }
            //need to break, as I might add strategies/requirements to any level (i.e. service)
            // so no need to traverse everything
            if (!somethingMatched) {
                break;
            }

        }
    }
    //here we are at a point in which we need to start looking in individual requirements blocks, then individual requirements, then conditions
    //only if we add Requirements or Conditions. Otherwise all work on multi level reqs
    switch (whatToRemove) {

    case "Strategy": {
        Object obj = trace.remove(0);
        JSONObject jSONObject = (JSONObject) obj;
        String name = jSONObject.get("name").toString();
        String type = jSONObject.get("type").toString();

        Strategy s = new Strategy().withCategoryString(name);

        for (Strategy strategy : currentReqs.getOptimizationStrategies()) {
            if (strategy.getStrategyCategory().equals(s.getStrategyCategory())) {
                currentReqs.removeStrategy(s);
                break;
            }

        }
    }
        break;

    case "Topology": {

        if (previousReqs.getContainedElements().contains(currentReqs)) {
            previousReqs.removeMultiLevelRequirements(currentReqs);
        }
    }
        break;
    case "Unit": {
        if (previousReqs.getContainedElements().contains(currentReqs)) {
            previousReqs.removeMultiLevelRequirements(currentReqs);
        }
    }
        break;
    case "Requirements": {
        Object obj = trace.remove(0);
        JSONObject jSONObject = (JSONObject) obj;
        String name = jSONObject.get("name").toString();

        Requirements requirements = new Requirements();
        requirements.setName(name);
        if (currentReqs.getUnitRequirements().contains(requirements)) {
            currentReqs.removeRequirements(requirements);
        }
    }
        break;
    case "Requirement": //here we need to continue to get the targeted Requirements block
    {
        Object obj = trace.remove(0);
        JSONObject jSONObject = (JSONObject) obj;
        String name = jSONObject.get("name").toString();
        String type = jSONObject.get("type").toString();
        for (Requirements r : currentReqs.getUnitRequirements()) {
            if (r.getName().equals(name)) {

                Object reqO = trace.remove(0);
                JSONObject jSONObjectReqo = (JSONObject) reqO;
                String nameReqo = jSONObjectReqo.get("name").toString();

                Requirement requirement = new Requirement();
                requirement.setName(nameReqo);

                for (Requirement req : r.getRequirements()) {
                    if (req.getName().equals(nameReqo)) {
                        r.getRequirements().remove(req);
                        break;
                    }
                }

                break;
            }
        }
    }
        break;

    case "Condition": //here we also need to get the requirement
    {
        Object obj = trace.remove(0);
        JSONObject jSONObject = (JSONObject) obj;
        String name = jSONObject.get("name").toString();
        String type = jSONObject.get("type").toString();
        for (Requirements r : currentReqs.getUnitRequirements()) {
            if (r.getName().equals(name)) {
                Object reqObj = trace.remove(0);
                JSONObject reqjSONObject = (JSONObject) reqObj;
                String reqname = reqjSONObject.get("name").toString();
                String reqtype = reqjSONObject.get("type").toString();

                for (Requirement req : r.getRequirements()) {
                    if (req.getName().equals(reqname)) {
                        Object rcondO = trace.remove(0);
                        JSONObject jSONObjectCondo = (JSONObject) rcondO;
                        String nameCondo = jSONObjectCondo.get("name").toString();

                        Condition condition = new Condition();
                        switch (nameCondo) {

                        case "ENUMERATION":
                            condition.setType(Condition.Type.ENUMERATION);
                            break;
                        case "EQUAL":
                            condition.setType(Condition.Type.EQUAL);
                            break;
                        case "GREATER_EQUAL":
                            condition.setType(Condition.Type.GREATER_EQUAL);
                            break;
                        case "LESS_EQUAL":
                            condition.setType(Condition.Type.LESS_EQUAL);
                            break;
                        case "LESS_THAN":
                            condition.setType(Condition.Type.LESS_THAN);
                            break;
                        case "RANGE":
                            condition.setType(Condition.Type.RANGE);
                            break;
                        }

                        for (Condition c : req.getConditions()) {
                            if (c.getType().equals(condition.getType())) {
                                req.getConditions().remove(c);
                                break;
                            }
                        }

                        break;
                    }
                }
                break;
            }
        }

    }

    }
}

From source file:com.fujitsu.dc.core.model.impl.es.DavCmpEsImpl.java

/**
 * ID?URL?. jsonObj?IDURL???/*from w ww  .  ja  v  a  2  s. c om*/
 * @param jsonObj ID??JSON
 * @param baseUrlStr xml:base
 */
@SuppressWarnings("unchecked")
private void roleIdToName(Object jsonObj, String baseUrlStr) {

    JSONArray array = new JSONArray();
    if (jsonObj instanceof JSONObject) {
        array.add(jsonObj);
    } else {
        array = (JSONArray) jsonObj;
    }
    if (array != null) {
        // xml:base
        for (int i = 0; i < array.size(); i++) {
            JSONObject aceJson = (JSONObject) array.get(i);
            JSONObject principal = (JSONObject) aceJson.get(KEY_ACL_PRINCIPAL);
            if (principal.get(KEY_ACL_HREF) != null) {
                // ID????????????????
                String roloResourceUrl = roleIdToRoleResourceUrl((String) principal.get(KEY_ACL_HREF));
                if (roloResourceUrl == null) {
                    // ID???????????????ACE???
                    array.remove(i);
                    --i;
                    // ????ID??????ACE??
                    if (array.isEmpty() && jsonObj instanceof JSONObject) {
                        JSONObject objJson = (JSONObject) jsonObj;
                        objJson.clear();
                    }
                    continue;
                }
                // base:xml?URL?
                roloResourceUrl = baseUrlToRoleResourceUrl(baseUrlStr, roloResourceUrl);
                principal.put(KEY_ACL_HREF, roloResourceUrl);
            } else if (principal.get(KEY_ACL_ALL) != null) {
                principal.put(KEY_ACL_ALL, null);
            }
        }
    }
}

From source file:niclients.main.getni.java

/**
 * Main of the GET NI./*from   www. j  a v a 2 s .c o m*/
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) throws UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    boolean done;
    String dst = null;
    JSONArray loc_array = new JSONArray();
    String c_type;
    HttpResponse response;
    int resp_code = 0;

    if (commandparser(args)) {

        dst = fqdn;
        done = false;

        try {
            while (!done) {
                if (createget(dst, niname)) {

                    response = client.execute(post);
                    resp_code = response.getStatusLine().getStatusCode();

                    if (200 == resp_code) {
                        // Get content type
                        c_type = response.getEntity().getContentType().getValue();

                        if ("application/json".equalsIgnoreCase(c_type)) {
                            // Response is location list
                            InputStream content = response.getEntity().getContent();
                            String resp = convertStreamToString(content);

                            // String to JSONArray
                            Object obj = JSONValue.parse(resp);
                            JSONArray array = (JSONArray) obj;

                            // add new locations to loc_array   
                            for (int i = 0; i < array.size(); i++) {
                                loc_array.add(array.get(i));
                            }
                            // Get next location from the loc_array and remove it from the loc_array
                            if (!loc_array.isEmpty()) {

                                // Check if new dst is type ni://
                                String tmp_dst = loc_array.get(0).toString();
                                tmp_dst = niUtils.mapNiToWKU(loc_array.get(0).toString());

                                if (tmp_dst == null) {
                                    //Check id new dst is type nihttp://
                                    tmp_dst = niUtils.mapNiHttpToWKU(loc_array.get(0).toString());
                                    if (tmp_dst != null)
                                        // is nihttp://
                                        dst = tmp_dst;
                                    else
                                        // is http://
                                        dst = loc_array.get(0).toString();
                                } else {
                                    // is ni://
                                    dst = tmp_dst;
                                }
                                loc_array.remove(0);
                            }
                        } else if ("application/octet-stream".equalsIgnoreCase(c_type)) {
                            // Response is content
                            InputStream content = response.getEntity().getContent();
                            if (output_filename == null)
                                writeCacheCopyToStdOut(content);
                            else {
                                writeCacheCopy(content, output_filename);
                                System.err.println("Content was stored to '" + output_filename + "'");
                            }
                            // so we can end the while
                            done = true;
                        } else {
                            // Response content type is not something we expected
                            System.err.println("Unsupported Content type = " + c_type);
                        }
                    } else {
                        // Response codetype is not success (we expected that)
                        System.err.println("RESP_CODE: " + Integer.toString(resp_code));
                    }
                } else {
                    System.err.println("Command parse failed!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:nl.surfnet.demo.SurfOAuthClient.java

@Override
public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();

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

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

    BufferedReader reader = null;

    try {//from   w  w  w .ja va  2 s  .  co  m
        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 : " + responseCode);
        }

        // {"audience":"MappedClient","scopes":["test"],"principal":{"name":"mappedclient","roles":[],"groups":[],"adminPrincipal":false,
        // "attributes":{}},"expires_in":1433059160531}
        HttpEntity entity = response.getEntity();
        JSONObject parsedObject;
        String errorMessage = null;
        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) {

                Map valueMap = parsedObject;
                Object principal = valueMap.get("principal");

                if (principal == null) {
                    tokenInfo.setTokenValid(false);
                    return tokenInfo;
                }
                Map principalMap = (Map) principal;
                String clientId = (String) principalMap.get("name");
                Long expiryTimeString = (Long) valueMap.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) valueMap.get("scopes");

                    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);
                    }
                } else {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                    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.codinjutsu.tools.jenkins.logic.JenkinsJsonParser.java

private List<JobParameter> getParameters(JSONArray parameterProperties) {
    List<JobParameter> jobParameters = new LinkedList<JobParameter>();
    if (parameterProperties == null || parameterProperties.isEmpty()) {
        return jobParameters;
    }//from  w ww.j a  v a2 s .  c om

    for (Object obj : parameterProperties) {
        JSONObject parameterProperty = (JSONObject) obj;
        if (parameterProperty == null || parameterProperty.isEmpty()) {
            continue;
        }

        JSONArray definitions = (JSONArray) parameterProperty.get(PARAMETER_DEFINITIONS);
        for (Object defObj : definitions) {
            JSONObject parameterObj = (JSONObject) defObj;
            JobParameter jobParameter = new JobParameter();
            JSONObject defaultParamObj = (JSONObject) parameterObj.get(PARAMETER_DEFAULT_PARAM);
            if (defaultParamObj != null && !defaultParamObj.isEmpty()) {
                Object defaultValue = defaultParamObj.get(PARAMETER_DEFAULT_PARAM_VALUE);
                if (defaultValue != null) {
                    jobParameter.setDefaultValue(defaultValue.toString());
                }
            }

            String name = (String) parameterObj.get(PARAMETER_NAME);
            jobParameter.setName(name);
            String type = (String) parameterObj.get(PARAMETER_TYPE);
            jobParameter.setType(type);
            JSONArray choices = (JSONArray) parameterObj.get(PARAMETER_CHOICE);
            jobParameter.setChoices(getChoices(choices));

            jobParameters.add(jobParameter);
        }
    }
    return jobParameters;
}

From source file:org.codinjutsu.tools.jenkins.logic.JenkinsJsonParser.java

private List<String> getChoices(JSONArray choiceObjs) {
    List<String> choices = new LinkedList<String>();
    if (choiceObjs == null || choiceObjs.isEmpty()) {
        return choices;
    }/*from   ww w. j a  v  a  2 s . c  om*/
    for (Object choiceObj : choiceObjs) {
        choices.add((String) choiceObj);
    }
    return choices;
}

From source file:org.codinjutsu.tools.jenkins.logic.JenkinsJsonParser.java

private Job.Health getHealth(JSONArray healths) {
    if (healths == null || healths.isEmpty()) {
        return null;
    }/*from  w ww .  ja v  a 2s .  c  o m*/

    Job.Health health = new Job.Health();
    JSONObject healthObject = (JSONObject) healths.get(0);
    String description = (String) healthObject.get(JOB_HEALTH_DESCRIPTION);
    health.setDescription(description);
    String healthLevel = (String) healthObject.get(JOB_HEALTH_ICON);
    if (StringUtils.isNotEmpty(healthLevel)) {
        if (healthLevel.endsWith(".png"))
            healthLevel = healthLevel.substring(0, healthLevel.lastIndexOf(".png"));
        else {
            healthLevel = healthLevel.substring(0, healthLevel.lastIndexOf(".gif"));
        }
    } else {
        healthLevel = null;
    }

    health.setLevel(healthLevel);

    if (!StringUtils.isEmpty(health.getLevel())) {
        return health;
    } else {
        return null;
    }
}