Example usage for org.json.simple JSONObject keySet

List of usage examples for org.json.simple JSONObject keySet

Introduction

In this page you can find the example usage for org.json.simple JSONObject keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:org.wso2.carbon.apimgt.rest.api.store.v1.mappings.APIMappingUtil.java

public static APIDTO fromAPItoDTO(API model, String tenantDomain) throws APIManagementException {

    APIDTO dto = new APIDTO();
    dto.setName(model.getId().getApiName());
    dto.setVersion(model.getId().getVersion());
    String providerName = model.getId().getProviderName();
    dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    dto.setId(model.getUUID());/*from ww  w.  ja  v  a2  s  . com*/
    dto.setContext(model.getContext());
    dto.setDescription(model.getDescription());
    dto.setIsDefaultVersion(model.isDefaultVersion());
    dto.setLifeCycleStatus(model.getStatus());

    /* todo: created and last updated times
    if (null != model.getLastUpdated()) {
    Date lastUpdateDate = model.getLastUpdated();
    Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
    dto.setLastUpdatedTime(String.valueOf(timeStamp));
    }
            
    String createdTimeStamp = model.getCreatedTime();
    if (null != createdTimeStamp) {
    Date date = new Date(Long.valueOf(createdTimeStamp));
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    String dateFormatted = formatter.format(date);
    dto.setCreatedTime(dateFormatted);
    } */

    Set<String> apiTags = model.getTags();
    List<String> tagsToReturn = new ArrayList<>();
    tagsToReturn.addAll(apiTags);
    dto.setTags(tagsToReturn);

    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
    List<String> tiersToReturn = new ArrayList<>();
    for (org.wso2.carbon.apimgt.api.model.Tier tier : apiTiers) {
        tiersToReturn.add(tier.getName());
    }
    dto.setTiers(tiersToReturn);

    dto.setTransport(Arrays.asList(model.getTransports().split(",")));

    dto.setEndpointURLs(extractEnpointURLs(model, tenantDomain));

    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
    dto.setBusinessInformation(apiBusinessInformationDTO);

    if (!StringUtils.isBlank(model.getThumbnailUrl())) {
        dto.setHasThumbnail(true);
    }

    if (model.getAdditionalProperties() != null) {
        JSONObject additionalProperties = model.getAdditionalProperties();
        Map<String, String> additionalPropertiesMap = new HashMap<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            String key = (String) propertyKey;
            additionalPropertiesMap.put(key, (String) additionalProperties.get(key));
        }
        dto.setAdditionalProperties(additionalPropertiesMap);
    }

    dto.setWsdlUri(model.getWsdlUrl());

    if (model.getGatewayLabels() != null) {
        dto.setLabels(getLabelDetails(model.getGatewayLabels(), model.getContext()));
    }

    if (model.getEnvironmentList() != null) {
        List<String> environmentListToReturn = new ArrayList<>();
        environmentListToReturn.addAll(model.getEnvironmentList());
        dto.setEnvironmentList(environmentListToReturn);
    }

    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    if (model.getApiSecurity() != null) {
        dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
    }
    return dto;
}

From source file:org.wso2.carbon.appmgt.impl.APIProviderImpl.java

/**
 * This method dynamically returns the mandatory and selected java policy handlers list for given app
 *
 * @param api :WebApp class which contains details about web applications
 * @return :handlers list with properties to be applied
 * @throws AppManagementException on error
 *//*w  w  w. j  ava  2  s .  c  om*/
private APITemplateBuilder getAPITemplateBuilder(WebApp api) throws AppManagementException {
    APITemplateBuilderImpl velocityTemplateBuilder = new APITemplateBuilderImpl(api);

    //List of JavaPolicy class which contains policy related details
    List<JavaPolicy> policies = new ArrayList<JavaPolicy>();
    //contains properties related to relevant policy and will be used to generate the synapse api config file
    Map<String, String> properties;
    int counterPolicies; //counter :policies

    try {
        //fetch all the java policy handlers details which need to be included to synapse api config file
        policies = appMDAO.getMappedJavaPolicyList(api.getUUID(), true);
        //loop through each policy
        for (counterPolicies = 0; counterPolicies < policies.size(); counterPolicies++) {
            if (policies.get(counterPolicies).getProperties() == null) {
                //if policy doesn't contain any properties assign an empty map and add java policy as a handler
                velocityTemplateBuilder.addHandler(policies.get(counterPolicies).getFullQualifiName(),
                        Collections.EMPTY_MAP);
            } else {
                //contains properties related to all the policies
                JSONObject objPolicyProperties;
                properties = new HashMap<String, String>();

                //get property JSON object related to current policy in the loop
                objPolicyProperties = policies.get(counterPolicies).getProperties();

                //if policy contains any properties, run a loop and assign them
                Set<String> keys = objPolicyProperties.keySet();
                for (String key : keys) {
                    properties.put(key, objPolicyProperties.get(key).toString());
                }
                //add policy as a handler and also the relevant properties
                velocityTemplateBuilder.addHandler(policies.get(counterPolicies).getFullQualifiName(),
                        properties);
            }
        }

    } catch (AppManagementException e) {
        handleException(
                "Error occurred while adding java policy handlers to Application : " + api.getId().toString(),
                e);
    }
    return velocityTemplateBuilder;
}

From source file:org.wso2.das.javaagent.worker.AgentConnectionWorker.java

/**
 * Obtain the current schema and obtain the key set of schema using JSON parser.
 * /*from w ww  . j a v  a 2 s. c  om*/
 * @param currentSchema current schema of the persisted table
 * @throws InstrumentationAgentException
 */
@SuppressWarnings("unchecked")
public void filterCurrentSchemaFields(String currentSchema) throws InstrumentationAgentException {
    try {
        JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject) parser.parse(currentSchema);
        JSONObject keys = (JSONObject) json.get("columns");
        Set keySet = keys.keySet();
        Iterator i = keySet.iterator();
        while (i.hasNext()) {
            setCurrentSchemaFieldsSet(String.valueOf(i.next()));
        }
    } catch (ParseException e) {
        throw new InstrumentationAgentException("Failed to obtain fields in current schema : " + e.getMessage(),
                e);
    }
}

From source file:paxchecker.browser.ShowclixReader.java

private static int getLatestID(URL url) {
    try {/*  w  w w  .ja  v a  2  s  .c  o m*/
        HttpURLConnection httpCon = Browser.setUpConnection(url);
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
        String jsonText = "";
        String line;
        while ((line = reader.readLine()) != null) {
            DataTracker.addDataUsed(line.length());
            jsonText += line;
        }
        reader.close();
        JSONParser mP = new JSONParser();
        JSONObject obj = (JSONObject) mP.parse(jsonText);
        int maxID = 0;
        for (String s : (Iterable<String>) obj.keySet()) {
            try {
                maxID = Math.max(maxID, Integer.parseInt((String) s));
            } catch (NumberFormatException nfe) {
                System.out.println("Error parsing ID number from String: " + s);
            }
        }
        return maxID;
    } catch (java.net.SocketTimeoutException ste) { // Return maxId for this?
        System.out.println("Unable to complete information download -- connection timed out");
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
    return -1;
}

From source file:piramide.multimodal.preprocessor.DirectoryPreprocessor.java

private Map<String, Object> loadVariables(File variablesFile) throws IOException {
    final String variablesText = FileUtils.readFileToString(variablesFile);
    final JSONObject variablesDictionary = (JSONObject) JSONValue.parse(variablesText);

    final Map<String, Object> returningMap = new HashMap<String, Object>();

    for (Object currentField : variablesDictionary.keySet()) {
        returningMap.put(currentField.toString(), variablesDictionary.get(currentField));
    }/*from  w  w  w  .  j  a  v a  2  s .  c  o  m*/

    return returningMap;
}

From source file:products.CommitedFeature.java

public boolean execute() {
    loggerObj.log(Level.INFO, "Inside CommitedFeature.execute method");
    JSONObject deptConfFileDetails = getDepartmentFileLocation();

    loggerObj.log(Level.INFO, "department file details is " + deptConfFileDetails.toJSONString());
    Set<String> deptKeys = deptConfFileDetails.keySet();
    //String departmentName = null;
    for (Iterator deptItr = deptKeys.iterator(); deptItr.hasNext();) {
        indiDepartmentWorkflow((String) deptItr.next(), deptConfFileDetails);
    }/* w  w  w. j ava  2 s .  c o m*/

    return false;
}

From source file:project.cs.netinfutilities.metadata.MetadataParser.java

/**
 * Returns a map that represents the meta-data key value pairs
 * contained in the specified meta-data.
 *
 * @param metadata          The JSON object corresponding to the meta-data.
 * @return                  The map with all meta-data values
 * @throws JSONException    Thrown, if no meta-data could be extracted at all
 *//* w w  w  . j  a v a  2  s  . c om*/
public static Map<String, Object> toMap(JSONObject metadata) throws ParseException {

    Map<String, Object> map = new LinkedHashMap<String, Object>();

    metadata = (JSONObject) metadata.get("meta");

    if (metadata == null) {
        throw new ParseException(ParseException.ERROR_UNEXPECTED_TOKEN,
                "\"meta\" tag not present in JSON Object");
    }

    // We iterate through the metadata by getting a set of keys from the metadata and
    // we walk through that set.
    @SuppressWarnings("unchecked")
    Set<String> keys = (Set<String>) metadata.keySet();

    Iterator<String> iterator = keys.iterator();

    while (iterator.hasNext()) {
        String key = iterator.next();
        Object value;

        value = metadata.get(key);

        if (value instanceof JSONArray) {
            List<String> list = extractList((JSONArray) value);
            map.put(key, list);
        } else {
            map.put(key, value);
        }
    }

    if (map.size() == 0) {
        throw new ParseException(ParseException.ERROR_UNEXPECTED_EXCEPTION, "No meta-data could be extracted.");
    }

    return map;
}

From source file:Publisher.CReport.java

public static String genReport(JSONArray pObjAry) throws IOException, COSVisitorException {

    List<List<String>> lstIncidentContents = new ArrayList<>();
    List<List<String>> lstHaze = new ArrayList<>();
    List<List<String>> lstDengue = new ArrayList<>();

    List<String> aryLst = new ArrayList<>();

    aryLst.add("Incident Type");
    aryLst.add("Percentage");

    lstIncidentContents.add(aryLst);/*from   ww w  .  j a  va  2s.  c om*/

    List<String> aryHazeHeader = new ArrayList<>();

    aryHazeHeader.add("Region");
    aryHazeHeader.add("PSI");

    lstHaze.add(aryHazeHeader);

    List<String> aryDengueHeader = new ArrayList<>();

    aryDengueHeader.add("Zones");
    aryDengueHeader.add("Count");

    lstDengue.add(aryDengueHeader);

    for (Object obj : pObjAry) {
        JSONObject objJson = (JSONObject) obj;

        Iterator<?> keys = objJson.keySet().iterator();

        while (keys.hasNext()) {
            String key = (String) keys.next();

            if (key.equalsIgnoreCase("type")) {
                continue;
            }

            String value = objJson.get(key) + "";

            List<String> aryValues = new ArrayList<>();

            switch (objJson.get("Type").toString().toUpperCase()) {
            case "STATS":
                aryValues.add(key);
                aryValues.add(value + "%");
                lstIncidentContents.add(aryValues);
                break;
            case "HAZE":
                aryValues.add(key + " Area");
                aryValues.add(value);
                lstHaze.add(aryValues);
                break;
            case "DENGUE":

                switch (key.toUpperCase()) {
                case "ALERT":
                    aryValues.add("Red Zone");
                    break;
                default:
                    aryValues.add("Yellow Zone");
                    break;
                }

                aryValues.add(value);
                lstDengue.add(aryValues);
                break;
            }
        }

    }

    try (// Create a document and add a page to it
            PDDocument document = new PDDocument()) {
        PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
        document.addPage(page);

        // Create a new font object selecting one of the PDF base fonts
        PDFont font = PDType1Font.HELVETICA_BOLD;

        // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
        try (// Start a new content stream which will "hold" the to be created content
                PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
            contentStream.beginText();
            contentStream.setFont(font, 20);
            contentStream.moveTextPositionByAmount(70, 720);
            contentStream.drawString("Incident Summary (" + new Date() + ")");
            contentStream.endText();

            contentStream.beginText();
            contentStream.setFont(font, 18);
            contentStream.moveTextPositionByAmount(100, 670);
            contentStream.drawString("Incident Statistics");
            contentStream.endText();

            contentStream.beginText();
            contentStream.setFont(font, 18);
            contentStream.moveTextPositionByAmount(100, 500);
            contentStream.drawString("Haze Statistics");
            contentStream.endText();

            contentStream.beginText();
            contentStream.setFont(font, 18);
            contentStream.moveTextPositionByAmount(100, 300);
            contentStream.drawString("Dengue Statistics");
            contentStream.endText();

            drawTable(page, contentStream, 650, 100, lstIncidentContents);

            drawTable(page, contentStream, 480, 100, lstHaze);

            drawTable(page, contentStream, 280, 100, lstDengue);

            // Make sure that the content stream is closed:
        }

        String strFileName = new Date().getTime() + ".pdf";

        // Save the results and ensure that the document is properly closed:
        document.save(strFileName);

        return Paths.get(strFileName).toAbsolutePath().toString();

    }

}

From source file:quickforms.controller.UpdateLookup.java

private HashMap<String, HashMap<String, String>> jsonToHashMap(String values) throws Exception {
    HashMap<String, HashMap<String, String>> lookups = new HashMap<String, HashMap<String, String>>();
    JSONParser parser = new JSONParser();
    JSONArray wrapper;//from   w ww  .  j  ava  2  s.  c o  m

    wrapper = (JSONArray) parser.parse(values);
    int curNewId = -1;
    for (int i = 0; i < wrapper.size(); i++) {
        JSONObject jObj = (JSONObject) wrapper.get(i);
        HashMap<String, String> thisRow = new HashMap<String, String>();
        String rowKey = "";
        for (Object key : jObj.keySet()) {

            if (((String) key).contains("Key")) {
                rowKey = (String) jObj.get(key);
                if (rowKey.isEmpty())
                    rowKey = Integer.toString(curNewId--); // identify this row as an insert
                thisRow.put((String) key, rowKey);
            } else {
                Object curCell = jObj.get(key);
                if (isNumber(curCell)) {

                    curCell = "" + ((Number) curCell).doubleValue();
                }
                thisRow.put((String) key, (String) curCell);
            }
        }
        lookups.put(rowKey, thisRow);
    }

    return lookups;
}

From source file:quickforms.sme.UseFulMethods.java

static public List<Map> createRSContext(String oldContextStr) throws Exception {
    JSONParser parser = new JSONParser();
    JSONArray lang = (JSONArray) parser.parse(oldContextStr);
    List<Map> oldContextList = new ArrayList<Map>();
    for (int i = 0; i < lang.size(); i++) {
        Map<String, String[]> oldContext = new HashMap<String, String[]>();
        JSONObject updateRow = (JSONObject) lang.get(i);
        Set<String> keyset1 = updateRow.keySet();
        for (String fieldName : keyset1) {
            String value = (String) updateRow.get((Object) fieldName);
            oldContext.put(fieldName, new String[] { value });
        }/*  ww  w.j  av  a2 s.  c o m*/
        oldContextList.add(oldContext);

    }
    return oldContextList;
}