Example usage for org.json.simple JSONObject isEmpty

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:org.jolokia.converter.json.TabularDataExtractorTest.java

@Test
void extractGenericTabularDataWithJsonEmpty() throws OpenDataException, AttributeNotFoundException {
    CompositeTypeAndJson ctj = new CompositeTypeAndJson(STRING, "name", null, STRING, "firstname", null,
            INTEGER, "age", null, BOOLEAN, "male", null);
    TabularTypeAndJson taj = new TabularTypeAndJson(new String[] { "name", "firstname" }, ctj);
    TabularData data = new TabularDataSupport(taj.getType());

    JSONObject result = (JSONObject) extract(true, data);

    assertTrue(result.isEmpty());
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

private Person parsePerson(final JSONObject jsonData) {
    Person person = null;//from   w w  w  .j a v  a2s. co m

    person = (Person) getApplicationContext().getBean("directoryPerson");

    if (jsonData.isEmpty() || "".equalsIgnoreCase(jsonData.toString())) {
        person.setDisplayName("Error");
        List<String> tDesc = new ArrayList<String>();
        tDesc.add("To many search results found. Please try again.");
        person.setAffiliations(tDesc);
    } else if (null != jsonData.get("errors") && (jsonData.get("errors")) instanceof JSONObject) {
        JSONObject error = (JSONObject) jsonData.get("errors");
        if (null != error.get("global")) {
            JSONObject globalError = (JSONObject) error.get("global");
            person.setDisplayName("Error");
            List<String> tDesc = new ArrayList<String>();
            tDesc.add((String) globalError.get("description"));
            person.setAffiliations(tDesc);
        }
    } else {
        person.setDisplayName((String) jsonData.get("displayName"));
        if (null != jsonData.get("name") && !"".equalsIgnoreCase((String) jsonData.get("name"))) {
            person.setDisplayName((String) jsonData.get("name"));
        }
        person.setEmail((String) jsonData.get("email"));
        person.setUserName((String) jsonData.get("uniqname"));

        if (null != jsonData.get("affiliation")) {
            if (jsonData.get("affiliation") instanceof String) {
                List<String> tList = new ArrayList<String>();
                tList.add((String) jsonData.get("affiliation"));
                person.setAffiliations(tList);
            } else {
                person.setAffiliations((List) jsonData.get("affiliation"));
            }
        }

        if (null != jsonData.get("aff")) {
            if (jsonData.get("aff") instanceof String) {
                List<String> tList = new ArrayList<String>();
                tList.add((String) jsonData.get("aff"));
                person.setAffiliations(tList);
            } else {
                person.setAffiliations((List) jsonData.get("aff"));
            }
        }

        if (null != jsonData.get("title")) {
            if (jsonData.get("title") instanceof String) {
                List<String> tList = new ArrayList<String>();
                tList.add((String) jsonData.get("title"));
                person.setDepartments(tList);
            } else {
                person.setDepartments((List) jsonData.get("title"));
            }
        }

        if (null != jsonData.get("workAddress")) {
            if (jsonData.get("workAddress") instanceof String) {
                person.setAddress(((String) jsonData.get("workAddress")).replace(" $ ", "\n"));
            } else {
                JSONArray addresses = (JSONArray) jsonData.get("workAddress");
                person.setAddress(((String) addresses.get(0)).replace(" $ ", "\n"));
            }
        }

        if (null != jsonData.get("workPhone")) {
            if (jsonData.get("workPhone") instanceof String) {
                person.setPhone(((String) jsonData.get("workPhone")).replace(" $ ", "\n"));
            } else {
                JSONArray phones = (JSONArray) jsonData.get("workPhone");
                person.setPhone(((String) phones.get(0)).replace(" $ ", "\n"));
            }
        }
    }
    return person;
}

From source file:org.sead.sda.LandingPage.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("tag") != null || request.getRequestURI().contains("/sda/list")) {
        String tag = "";

        if (request.getParameter("tag") != null) {
            tag = request.getParameter("tag");
        } else {// ww w  .  j a  v  a  2s  . co m
            tag = request.getRequestURI().split("/sda/list=")[1];
        }

        // here we check whether the BagIt zip file for this RO exists in SDA
        SFTP sftp = new SFTP();
        String bagName = getBagNameFromId(tag);
        if (sftp.doesFileExist(Constants.sdaPath + bagName + "/" + bagName + ".zip")) {
            System.out.println("Bag Exists in SDA...");
            request.setAttribute("bagExists", "true");
        }
        sftp.disConnectSessionAndChannel();

        request.setAttribute("obTag", tag);
        request.setAttribute("landingPageUrl", Constants.landingPage);

        String keyList_cp = "@id|status|message|preferences";

        String keyList_ore = "keyword|contact|creator|publication date|title|abstract|license|is version of|similarto|title|describes|@context|aggregates|has part|identifier|label|size";
        //

        keyMapList = new HashMap<String, String>();

        Shimcalls shim = new Shimcalls();
        // Fix: accessing RO from c3pr here is wrong. we have to access the ore map in the
        // published package and read properties from that.
        JSONObject cp = shim.getResearchObject(tag);

        if (cp.isEmpty()) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/ro.jsp");
            request.setAttribute("roExists", "false");
            dispatcher.forward(request, response);
            return;
        }

        request.setAttribute("roExists", "true");
        SeadMon.addLog(MonConstants.Components.LANDING_PAGE, tag, MonConstants.EventType.ACCESS);

        keyMap(cp, keyList_cp);

        shim.getObjectID(cp, "@id");
        String oreUrl = shim.getID();
        JSONObject oreFile = shim.getResearchObjectORE(oreUrl);
        keyMap(oreFile, keyList_ore);

        JSONObject describes = (JSONObject) oreFile.get(keyMapList.get("describes"));
        Map<String, List<String>> roProperties = new HashMap<String, List<String>>();
        Map<String, String> downloadList = new HashMap<String, String>();
        Map<String, String> linkedHashMap = new LinkedHashMap<String, String>();
        Map<String, String> linkedHashMapTemp = new LinkedHashMap<String, String>();
        Map<String, String> newDownloadList = new LinkedHashMap<String, String>();

        // extract properties from ORE
        JSONArray status = (JSONArray) cp.get(keyMapList.get("Status".toLowerCase()));
        String doi = "No DOI Found"; // handle this as an exception
        String pubDate = null;
        for (Object st : status) {
            JSONObject jsonStatus = (JSONObject) st;
            String stage = (String) jsonStatus.get("stage");
            if ("Success".equals(stage)) {
                doi = (String) jsonStatus.get("message");
                pubDate = (String) jsonStatus.get("date");
            }
        }
        roProperties.put("DOI", Arrays.asList(doi));
        roProperties.put("Publication Date", Arrays.asList(pubDate));
        roProperties.put("Full Metadata",
                Arrays.asList(Constants.landingPage + "/metadata/" + tag + "/oremap"));
        addROProperty("Creator", describes, roProperties);
        //            addROProperty("Publication Date", describes, roProperties);
        addROProperty("Title", describes, roProperties);
        addROProperty("Abstract", describes, roProperties);
        addROProperty("Contact", describes, roProperties);
        addROProperty("Keyword", describes, roProperties);

        JSONObject preferences = (JSONObject) cp.get(keyMapList.get("Preferences".toLowerCase()));

        //addROProperty_License("License", preferences, cp, roProperties);
        addROProperty("License", preferences, roProperties);

        // check access rights
        if (isRORestricted(preferences)) {
            request.setAttribute("accessRestricted", "true");
            List<String> rights = new ArrayList<String>();
            rights.add("Restricted");
            roProperties.put("Access Rights", rights);
        }

        //Map<String, String> properties = new HashMap<String, String>();
        //String Label = properties.get("Label");

        // extract Live Data Links from ORE
        String liveCopy = null;
        if (describes.get(keyMapList.get("Is Version Of".toLowerCase())) != null) {
            String versionOf = describes.get(keyMapList.get("Is Version Of".toLowerCase())).toString();
            if (versionOf.startsWith("http")) {
                liveCopy = versionOf;
            } else if (describes.get(keyMapList.get("similarTo".toLowerCase())) != null) {
                String similar = describes.get(keyMapList.get("similarTo".toLowerCase())).toString();
                similar = similar.substring(0, similar.indexOf("/resteasy") + 1);
                liveCopy = similar + "#collection?uri=" + versionOf;
            }
        }
        if (liveCopy != null) {
            List<String> liveCopyList = new ArrayList<String>();
            if (shim.validUrl(liveCopy)) {
                liveCopyList.add(liveCopy);
            } else {
                liveCopyList.add("Not Available");
            }
            roProperties.put("Live Data Links", liveCopyList);
        }

        // set properties as an attribute
        request.setAttribute("roProperties", roProperties);

        // String title = describes.get(keyMapList.get("Title".toLowerCase())).toString();

        // extract file names from tar archive in SDA
        String requestURI = request.getRequestURI();

        if (requestURI.contains("/sda/list")) {
            int c = 0;
            String[] requestURIsda = requestURI.split("/");
            for (String item : requestURIsda) {
                if (item.equals("sda")) {
                    c++;
                }
            }
            if (c % 2 != 0) {

                //extract RO hierarchy
                try {
                    NewOREmap oreMap = new NewOREmap(oreFile, keyMapList);
                    downloadList = oreMap.getHierarchy();

                    Set<String> nameList = downloadList.keySet();

                    for (String name : nameList) {
                        String[] name_split = name.split("/");
                        String size = null;
                        if (downloadList.get(name) != null) {
                            int bytes = Integer.parseInt(downloadList.get(name));

                            int kb = bytes / 1024;
                            int mb = kb / 1024;
                            int gb = mb / 1024;
                            if (bytes <= 1024) {
                                size = bytes + " Bytes";
                            } else if (kb <= 1024) {
                                size = kb + " KB";
                            } else if (mb <= 1024) {
                                size = mb + " MB";
                            } else {
                                size = gb + " GB";
                            }
                        }

                        String temp = null;
                        if (name_split.length <= 2 && size != null) {

                            temp = "<span style='padding-left:" + 30 * (name_split.length - 2) + "px'>"
                                    + name_split[name_split.length - 1] + "</span>";
                            linkedHashMap.put(name, temp);
                        } else {

                            temp = "<span style='padding-left:" + 30 * (name_split.length - 2) + "px'>" + "|__"
                                    + name_split[name_split.length - 1] + "</span>";
                            linkedHashMapTemp.put(name, temp);
                        }

                        newDownloadList.put(name, size);

                    }

                    for (String key : linkedHashMapTemp.keySet()) {
                        linkedHashMap.put(key, linkedHashMapTemp.get(key));
                    }
                } catch (Exception e) {
                    System.err.println("Landing Page OREmap error: inaccurate keys");
                }

            }

            // set download list as an attribute
            // set linkedHashMap as an attribute
        }
        request.setAttribute("downloadList", newDownloadList);
        request.setAttribute("linkedHashMap", linkedHashMap);

        // forward the user to get_id UI
        RequestDispatcher dispatcher = request.getRequestDispatcher("/ro.jsp");
        dispatcher.forward(request, response);

    } else if (!request.getRequestURI().contains("bootstrap")) {

        // collection title is the last part of the request URI
        String requestURI = request.getRequestURI();
        String newURL = requestURI.substring(requestURI.lastIndexOf("sda/") + 4);
        String title = null;
        String filename = null;

        if (!newURL.contains("/")) {
            title = newURL;
        } else {
            title = newURL.split("/")[0];
            filename = newURL.substring(newURL.indexOf("/") + 1);
        }
        title = URLDecoder.decode(title, "UTF-8");
        newURL = URLDecoder.decode(newURL, "UTF-8");

        // don't allow downloads for restricted ROs
        // Fix: use ORE from package
        Shimcalls shim = new Shimcalls();
        JSONObject ro = shim.getResearchObject(title);

        String keyList_cp = "@id|status|message|preferences";
        keyMapList = new HashMap<String, String>();
        keyMap(ro, keyList_cp);

        if (isRORestricted((JSONObject) ro.get(keyMapList.get("Preferences".toLowerCase())))) {
            return;
        }

        SFTP sftp = new SFTP();
        String bgName = getBagNameFromId(title);
        String target = Constants.sdaPath + bgName + "/" + bgName + ".zip";
        if (!sftp.doesFileExist(target)) {
            target = Constants.sdaPath + title + "/" + title + ".tar";
        }

        System.out.println("title " + title);
        System.out.println("filename " + filename);

        if (!title.equals("*")) {
            InputStream inStream = sftp.downloadFile(target);

            String mimeType = "application/octet-stream";
            response.setContentType(mimeType);

            String headerKey = "Content-Disposition";

            String headerValue = null;
            if (filename != null) {
                if (filename.contains("/")) {
                    filename = filename.substring(filename.lastIndexOf("/") + 1);
                }
                headerValue = String.format("attachment; filename=\"%s\"", filename);
            } else {
                headerValue = String.format("attachment; filename=\"%s\"",
                        target.substring(target.lastIndexOf("/") + 1));
            }
            response.setHeader(headerKey, headerValue);

            OutputStream outStream = response.getOutputStream();
            if (newURL.equals(title)) {
                //download tar file
                SeadMon.addLog(MonConstants.Components.LANDING_PAGE, title, MonConstants.EventType.DOWNLOAD);
                System.out.println("SDA download path: " + target);
                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
            } else {
                //download individual files
                if (target.contains(".tar")) {
                    System.out.println("SDA download path: " + Constants.sdaPath + newURL);
                    TarArchiveInputStream myTarFile = new TarArchiveInputStream(inStream);

                    TarArchiveEntry entry = null;
                    String individualFiles;
                    int offset;

                    while ((entry = myTarFile.getNextTarEntry()) != null) {
                        individualFiles = entry.getName();

                        if (individualFiles.equals(newURL)) {
                            byte[] content = new byte[(int) entry.getSize()];
                            offset = 0;
                            myTarFile.read(content, offset, content.length - offset);
                            outStream.write(content);
                        }
                    }
                    myTarFile.close();
                } else {
                    System.out.println("SDA download path: " + Constants.sdaPath + bgName + "/" + bgName
                            + ".zip/" + bgName + "/" + newURL.substring(newURL.indexOf("/") + 1));
                    BufferedInputStream bin = new BufferedInputStream(inStream);
                    ZipInputStream myZipFile = new ZipInputStream(bin);

                    ZipEntry ze = null;
                    while ((ze = myZipFile.getNextEntry()) != null) {
                        if (ze.getName().equals(bgName + "/" + newURL.substring(newURL.indexOf("/") + 1))) {
                            byte[] buffer = new byte[4096];
                            int len;
                            while ((len = myZipFile.read(buffer)) != -1) {
                                outStream.write(buffer, 0, len);
                            }
                            break;
                        }
                    }
                }
            }
            inStream.close();
            outStream.close();
        }

        sftp.disConnectSessionAndChannel();
    }

}

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

/**
 * Returns all the Gateway Endpoint URLs of a given API
 * /*from  w w w  .j a va 2 s.  com*/
 * @param cx
 * @param thisObj
 * @param args
 * @param funObj
 * @return List of Gateway Endpoint URLs of the API
 * @throws ScriptException
 * @throws APIManagementException
 */
public static NativeArray jsFunction_getAPIEndpointURLs(Context cx, Scriptable thisObj, Object[] args,
        Function funObj) throws ScriptException, APIManagementException {
    String providerName;
    String apiName;
    String version;
    String userName;

    NativeArray myn = new NativeArray(0);

    if (args != null && args.length > 3) {
        providerName = APIUtil.replaceEmailDomain((String) args[0]);
        apiName = (String) args[1];
        version = (String) args[2];
        userName = (String) args[3];

        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, version);
        APIConsumer apiConsumer = getAPIConsumer(thisObj);
        API api = apiConsumer.getAPI(apiIdentifier);

        Map<String, String> domains;

        domains = apiConsumer.getTenantDomainMappings(MultitenantUtils.getTenantDomain(userName),
                APIConstants.API_DOMAIN_MAPPINGS_GATEWAY);
        if (domains != null && domains.size() > 0) {
            int index = 0;
            for (Object o : domains.entrySet()) {
                Map.Entry pair = (Map.Entry) o;
                String domainValue = (String) pair.getValue();
                if (domainValue.endsWith("/")) {
                    domainValue = domainValue.substring(0, domainValue.length() - 1);
                }
                String contextWithoutTenant = api.getContext()
                        .replace("/t/" + MultitenantUtils.getTenantDomain(userName), "");
                myn.put(index, myn, domainValue + contextWithoutTenant);
                if (api.isDefaultVersion()) {
                    contextWithoutTenant = contextWithoutTenant.replace(version + "/", "");
                    myn.put(++index, myn, domainValue + contextWithoutTenant);
                }
                index++;
            }
        } else {
            JSONObject environmentsObject = getEnvironmentsOfAPI(api);
            JSONObject productionEnvironmentObjects = (JSONObject) environmentsObject.get("production");
            JSONObject sandboxEnvironmentObjects = (JSONObject) environmentsObject.get("sandbox");
            JSONObject hybridEnvironmentObjects = (JSONObject) environmentsObject.get("hybrid");
            int envCount = 0;
            if (productionEnvironmentObjects != null && !productionEnvironmentObjects.isEmpty()) {
                envCount = createAPIEndpointsPerType(productionEnvironmentObjects, api, version, myn, envCount,
                        "production");
            }
            if (sandboxEnvironmentObjects != null && !sandboxEnvironmentObjects.isEmpty()) {
                envCount = createAPIEndpointsPerType(sandboxEnvironmentObjects, api, version, myn, envCount,
                        "sandbox");
            }
            if (hybridEnvironmentObjects != null && !hybridEnvironmentObjects.isEmpty()) {
                envCount = createAPIEndpointsPerType(hybridEnvironmentObjects, api, version, myn, envCount,
                        "hybrid");
            }
        }

    }
    return myn;
}

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

/**
 * This method create the json object of the environments in the API
 * @param api API object of selected api .
 * @return json object of environments// w  w  w .  jav a 2  s  .  com
 */
private static JSONObject getEnvironmentsOfAPI(API api) {
    APIManagerConfiguration config = HostObjectComponent.getAPIManagerConfiguration();
    Map<String, Environment> environments = config.getApiGatewayEnvironments();
    JSONObject environmentObject = new JSONObject();
    JSONObject productionEnvironmentObject = new JSONObject();
    JSONObject sandboxEnvironmentObject = new JSONObject();
    JSONObject hybridEnvironmentObject = new JSONObject();
    Set<String> environmentsPublishedByAPI = new HashSet<String>(api.getEnvironments());
    environmentsPublishedByAPI.remove("none");
    for (String environmentName : environmentsPublishedByAPI) {
        Environment environment = environments.get(environmentName);
        if (environment != null) {
            JSONObject jsonObject = new JSONObject();
            List<String> environmenturls = new ArrayList<String>();
            environmenturls.addAll(Arrays.asList((environment.getApiGatewayEndpoint().split(","))));
            List<String> transports = new ArrayList<String>();
            transports.addAll(Arrays.asList((api.getTransports().split(","))));
            jsonObject.put("http", filterUrlsByTransport(environmenturls, transports, "http"));
            jsonObject.put("https", filterUrlsByTransport(environmenturls, transports, "https"));
            jsonObject.put("showInConsole", environment.isShowInConsole());
            if (APIConstants.GATEWAY_ENV_TYPE_PRODUCTION.equals(environment.getType())) {
                productionEnvironmentObject.put(environment.getName(), jsonObject);
            } else if (APIConstants.GATEWAY_ENV_TYPE_SANDBOX.equals(environment.getType())) {
                sandboxEnvironmentObject.put(environment.getName(), jsonObject);
            } else {
                hybridEnvironmentObject.put(environment.getName(), jsonObject);
            }
        }
    }
    if (productionEnvironmentObject != null && !productionEnvironmentObject.isEmpty()) {
        environmentObject.put(APIConstants.GATEWAY_ENV_TYPE_PRODUCTION, productionEnvironmentObject);
    }
    if (sandboxEnvironmentObject != null && !sandboxEnvironmentObject.isEmpty()) {
        environmentObject.put(APIConstants.GATEWAY_ENV_TYPE_SANDBOX, sandboxEnvironmentObject);
    }
    if (hybridEnvironmentObject != null && !hybridEnvironmentObject.isEmpty()) {
        environmentObject.put(APIConstants.GATEWAY_ENV_TYPE_HYBRID, hybridEnvironmentObject);
    }
    return environmentObject;
}

From source file:org.wso2.carbon.apimgt.impl.AbstractKeyManager.java

public AccessTokenRequest buildAccessTokenRequestFromJSON(String jsonInput, AccessTokenRequest tokenRequest)
        throws APIManagementException {

    if (jsonInput == null || jsonInput.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("JsonInput is null or Empty.");
        }/*from  w w w .j  a  v  a 2  s.c  o  m*/
        return tokenRequest;
    }

    JSONParser parser = new JSONParser();
    JSONObject jsonObject;

    if (tokenRequest == null) {
        if (log.isDebugEnabled()) {
            log.debug("Input request is null. Creating a new Request Object.");
        }
        tokenRequest = new AccessTokenRequest();
    }

    try {
        jsonObject = (JSONObject) parser.parse(jsonInput);
        // Getting parameters from input string and setting in TokenRequest.
        if (jsonObject != null && !jsonObject.isEmpty()) {
            Map<String, Object> params = (Map<String, Object>) jsonObject;

            if (null != params.get(ApplicationConstants.OAUTH_CLIENT_ID)) {
                tokenRequest.setClientId((String) params.get(ApplicationConstants.OAUTH_CLIENT_ID));
            }

            if (null != params.get(ApplicationConstants.OAUTH_CLIENT_SECRET)) {
                tokenRequest.setClientSecret((String) params.get(ApplicationConstants.OAUTH_CLIENT_SECRET));
            }

            if (null != params.get(ApplicationConstants.VALIDITY_PERIOD)) {
                tokenRequest.setValidityPeriod(
                        Long.parseLong((String) params.get(ApplicationConstants.VALIDITY_PERIOD)));
            }

            return tokenRequest;
        }
    } catch (ParseException e) {
        handleException("Error occurred while parsing JSON String", e);
    }
    return null;
}

From source file:org.wso2.carbon.apimgt.migration.client.MigrateFrom18to19.java

/**
 * generate swagger v2 info object using swagger 1.2 doc.
 * See <a href="https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject">Swagger v2 info
 * object</a>// w  w w  . ja v  a 2s .co m
 *
 * @param swagger12doc Old Swagger Document
 * @return swagger v2 infoObject
 * @throws ParseException
 */
private static JSONObject generateInfoObject(JSONObject swagger12doc) throws ParseException {

    JSONObject infoObj = (JSONObject) swagger12doc.get("info");
    JSONParser parser = new JSONParser();
    JSONObject swagger2InfoObj = (JSONObject) parser.parse(Constants.DEFAULT_INFO);

    //set the required parameters first
    String title = (String) infoObj.get("title");
    String version = (String) swagger12doc.get("apiVersion");

    swagger2InfoObj.put(Constants.SWAGGER_TITLE, title);
    swagger2InfoObj.put(Constants.SWAGGER_VER, version);

    if (infoObj.containsKey(Constants.SWAGGER_DESCRIPTION)) {
        swagger2InfoObj.put(Constants.SWAGGER_DESCRIPTION, infoObj.get("description"));
    }
    if (infoObj.containsKey(Constants.SWAGGER_TERMS_OF_SERVICE_URL)) {
        swagger2InfoObj.put(Constants.SWAGGER_TERMS_OF_SERVICE,
                infoObj.get(Constants.SWAGGER_TERMS_OF_SERVICE_URL));
    }

    //contact object
    if (infoObj.containsKey(Constants.SWAGGER_CONTACT)) {
        JSONObject contactsObj = new JSONObject();
        String contact = (String) infoObj.get(Constants.SWAGGER_CONTACT);
        if (contact.contains("http")) {
            contactsObj.put(Constants.SWAGGER_URL, contact);
        } else if (contact.contains("@")) {
            contactsObj.put(Constants.SWAGGER_EMAIL, contact);
        } else {
            contactsObj.put(Constants.SWAGGER_NAME, contact);
        }
        swagger2InfoObj.put(Constants.SWAGGER_CONTACT, contactsObj);
    }

    //licence object
    JSONObject licenseObj = new JSONObject();
    if (infoObj.containsKey(Constants.SWAGGER_LICENCE)) {
        licenseObj.put(Constants.SWAGGER_NAME, infoObj.get(Constants.SWAGGER_LICENCE));
    }
    if (infoObj.containsKey(Constants.SWAGGER_LICENCE_URL)) {
        licenseObj.put(Constants.SWAGGER_URL, infoObj.get(Constants.SWAGGER_LICENCE_URL));
    }
    if (!licenseObj.isEmpty()) {
        swagger2InfoObj.put(Constants.SWAGGER_LICENCE, licenseObj);
    }
    return swagger2InfoObj;
}

From source file:org.wso2.carbon.apimgt.migration.Swagger19Migration.java

/**
 * generate swagger v2 info object using swagger 1.2 doc.
 * See <a href="https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject">Swagger v2 info object</a>
 *
 * @param swagger12doc Old Swagger Document
 * @return swagger v2 infoObject//from   w  w w .ja  va 2s  .  co m
 * @throws ParseException
 */
private static JSONObject generateInfoObject(JSONObject swagger12doc) throws ParseException {

    JSONObject infoObj = (JSONObject) swagger12doc.get("info");
    JSONParser parser = new JSONParser();
    JSONObject swagger2InfoObj = (JSONObject) parser.parse(Constants.DEFAULT_INFO);

    //set the required parameters first
    String title = (String) infoObj.get("title");
    String version = (String) swagger12doc.get("apiVersion");

    swagger2InfoObj.put("title", title);
    swagger2InfoObj.put("version", version);

    if (infoObj.containsKey("description")) {
        swagger2InfoObj.put("description", infoObj.get("description"));
    }
    if (infoObj.containsKey("termsOfServiceUrl")) {
        swagger2InfoObj.put("termsOfService", infoObj.get("termsOfServiceUrl"));
    }

    //contact object
    if (infoObj.containsKey("contact")) {
        JSONObject contactsObj = new JSONObject();
        String contact = (String) infoObj.get("contact");
        if (contact.contains("http")) {
            contactsObj.put("url", contact);
        } else if (contact.contains("@")) {
            contactsObj.put("email", contact);
        } else {
            contactsObj.put("name", contact);
        }
        swagger2InfoObj.put("contact", contactsObj);
    }

    //licence object
    JSONObject licenseObj = new JSONObject();
    if (infoObj.containsKey("license")) {
        licenseObj.put("name", infoObj.get("license"));
    }
    if (infoObj.containsKey("licenseUrl")) {
        licenseObj.put("url", infoObj.get("licenseUrl"));
    }
    if (!licenseObj.isEmpty()) {
        swagger2InfoObj.put("license", licenseObj);
    }
    return swagger2InfoObj;
}

From source file:se.kodapan.geography.geocoding.Nominatim.java

private Result resultFactory(JSONObject jsonResult) {
    Result result = new ResultImpl();
    result.setSource(sourceFactory());/*from  w  w  w. ja  va2s .  c o m*/

    String licence = ((String) jsonResult.remove("licence"));
    result.getSource().setLicense(licence);
    // todo place_id can be a string error message, at least if reverse geocoding out of area
    Number placeIdentity = Long.valueOf(((String) jsonResult.remove("place_id")));
    String placeClass = ((String) jsonResult.remove("class"));
    String placeType = ((String) jsonResult.remove("type"));
    String osmIdentity = ((String) jsonResult.remove("osm_id"));

    String osmType = ((String) jsonResult.remove("osm_type"));

    String iconURL = ((String) jsonResult.remove("icon"));

    String displayName = ((String) jsonResult.remove("display_name"));
    result.getAddressComponents().setFormattedAddress(displayName);

    Number latitude = Double.valueOf((String) jsonResult.remove("lat"));
    Number longitude = Double.valueOf((String) jsonResult.remove("lon"));
    result.setLocation(new CoordinateImpl(latitude, longitude));

    JSONObject address = (JSONObject) jsonResult.remove("address");
    if (address != null) {
        for (Map.Entry<String, String> ae : ((Set<Map.Entry<String, String>>) address.entrySet())) {
            result.getAddressComponents().add(new AddressComponent(ae.getValue(), ae.getKey()));
        }
    }

    JSONArray boundingBox = (JSONArray) jsonResult.remove("boundingbox");
    if (boundingBox != null) {
        result.setBounds(new EnvelopeImpl(
                new CoordinateImpl(Double.valueOf(boundingBox.get(0).toString()),
                        Double.valueOf(boundingBox.get(2).toString())),
                new CoordinateImpl(Double.valueOf(boundingBox.get(1).toString()),
                        Double.valueOf(boundingBox.get(3).toString()))));
    }

    JSONArray polygonPoints = (JSONArray) jsonResult.remove("polygonpoints");
    if (polygonPoints != null) {
        if (result.getBounds() != null) {
            // according to the osm irc this means that the bounding box enclose the polygon
            log.info("Both boundingbox and polygon in response, using the latter");
        }
        List<Coordinate> polygonCoordinates = new ArrayList<Coordinate>(polygonPoints.size());
        for (int ppsi = 0; ppsi < polygonPoints.size(); ppsi++) {
            JSONArray polygonPoint = (JSONArray) polygonPoints.get(ppsi);
            polygonCoordinates.add(new CoordinateImpl(Double.valueOf(polygonPoint.get(1).toString()),
                    Double.valueOf(polygonPoint.get(0).toString())));
        }
        if (!polygonCoordinates.isEmpty()) {
            EnvelopeImpl envelope = new EnvelopeImpl();
            envelope.addBounds(polygonCoordinates);
            result.setBounds(envelope);
        }

    }

    if (!jsonResult.isEmpty()) {
        log.error("Unknown data left in result: " + jsonResult.toJSONString());
    }

    return result;
}

From source file:smops.dao.BusinessManager.java

public static void prepareReport(int offset, int limit) {
    JSONArray all_json = new JSONArray();
    final List<Business> bizs = getBusinesses(offset, limit);
    for (Business biz : bizs) {
        if (getValidFormsCount(biz) == 0) {
            continue;
        }//from w  w  w . j a  v a  2 s.  co  m
        //            System.out.println("");
        //            System.out.println("[" + biz.getName() + "] " + biz.getUrl());
        JSONObject biz_json = new JSONObject();
        biz_json.put("name", biz.getName());
        //            biz_json.put("url", biz.getUrl());
        JSONArray forms_json = new JSONArray();
        for (Object f : biz.getForms()) {
            Form form = (Form) f;
            if (form.getPurpose().equals("unknown")) {
                continue;
            }
            JSONObject f_json = new JSONObject();
            f_json.put("page_url", " " + form.getPageUrl() + " ");
            f_json.put("purpose", form.getPurpose());
            //                System.out.println("\t" + form.getPageUrl());
            //                System.out.print("\t[" + form.getPurpose() + "]: ");
            String fields_str = "";
            for (Object inp : form.getFields()) {
                Field field = (Field) inp;
                if (field.getInfoType().equals("unknown")) {
                    continue;
                }
                fields_str += field.getInfoType() + " ";
            }
            f_json.put("fields", fields_str);
            forms_json.add(f_json);
            //                System.out.println(fields_str);
        }
        if (!forms_json.isEmpty()) {
            biz_json.put("forms", forms_json);
        }
        if (!biz_json.isEmpty()) {
            all_json.add(biz_json);
        }
    }
    StringWriter out = new StringWriter();
    try {
        all_json.writeJSONString(out);
    } catch (IOException ex) {
        Logger.getLogger(BusinessManager.class.getName()).log(Level.SEVERE, null, ex);
    }
    String jsonText = out.toString();
    System.out.print(jsonText.replaceAll("/", ""));
}