Example usage for org.json.simple JSONObject remove

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

Introduction

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

Prototype

V remove(Object key);

Source Link

Document

Removes the mapping for a key from this map if it is present (optional operation).

Usage

From source file:org.openme.openme.java

public static JSONObject remote_access(JSONObject i) {
    /*//from   www .  j a v  a  2s.  c o m
    Input:  {
      cm_remote_url             - remote URL
      (cm_user_uoa)             -
      (cm_user_password)        -
      (cm_user_password1)       -
      (remote_repo_uoa)
            
      (remote_pre_auth)         - if 'yes', need standard http login/password pre-authentication
      (cm_remote_user_name)     - remote username
      (cm_remote_user_password) - remote password
            
      (cm_web_module_uoa)       - module to run
      (cm_web_action)           - action to perform
                                  if =='download', prepare entry/file download through Internet
            
      (cm_save_to_file)         - if cm_web_action==download,
                                  save output to this file
            
      (cm_console)              - if 'json', treat output as json
                                  if 'json_after_text', strip everything before json
                                  if 'txt', output to cm_stdout
            
      ...                       - all other request parameters
            
      //FGG TBD - should add support for proxy
    }
            
    Output: {
      cm_return   - return code = 0 if successful
                                > 0 if error
                                < 0 if warning (rarely used at this moment)
      (cm_error)  - error text, if cm_return > 0
      (cm_stdout) - if cm_console='txt', output there
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    URL u;
    HttpURLConnection c = null;

    // Prepare request
    String x = "";
    String post = "";

    String con = "";
    x = (String) i.get("cm_console");
    if (x != null && x != "")
        con = x;

    String url = (String) i.get("cm_remote_url");
    if (url == null || url == "") {
        r.put("cm_return", new Long(1));
        r.put("cm_error", "'cm_remote_url is not defined");
        return r;
    }
    i.remove("cm_remote_url");

    x = (String) i.get("cm_user_uoa");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_uoa=" + x;
        i.remove("cm_user_uoa");
    }

    String save_to_file = (String) i.get("cm_save_to_file");
    if (save_to_file != null)
        i.remove("cm_save_to_file");

    x = (String) i.get("cm_user_password");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_password=" + x;
        i.remove("cm_user_password");
    }

    x = (String) i.get("cm_user_password1");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_user_password1=" + x;
        i.remove("cm_user_password1");
    }

    x = (String) i.get("remote_repo_uoa");
    if (x != null && x != "") {
        if (post != "")
            post += "&";
        post += "cm_repo_uoa=" + x;
        i.remove("remote_repo_uoa");
    }

    // Check if needed remote pre-authentication
    String base64string = "";
    x = (String) i.get("remote_pre_auth");
    if (x == "yes") {
        i.remove("remote_pre_auth");

        String username = "";
        String password = "";

        x = (String) i.get("cm_remote_user_name");
        if (x != null && x != "") {
            username = x;
            i.remove("cm_remote_user_name");
        }

        x = (String) i.get("cm_remote_user_password");
        if (x != null && x != "") {
            password = x;
            i.remove("cm_remote_user_password");
        }

        x = username + ":" + password;
        base64string = new String(Base64.encodeBase64(x.replace("\n", "").getBytes()));
    }

    // Check if data download, not json and convert it to download request
    boolean download = false;

    x = (String) i.get("cm_web_action");
    if (x == "download" || x == "show") {
        download = true;
        if (post != "")
            post += "&";
        post += "cm_web_module_uoa=web&cm_web_action=" + x;
        i.remove("cm_web_action");

        if (((String) i.get("cm_web_module_uoa")) != null)
            i.remove("cm_web_module_uoa");
        if (((String) i.get("cm_console")) != null)
            i.remove("cm_console");
    }

    // Prepare array to transfer through Internet
    JSONObject ii = new JSONObject();
    ii.put("cm_array", i);
    JSONObject rx = convert_cm_array_to_uri(ii);
    if ((Long) rx.get("cm_return") > 0)
        return rx;

    if (post != "")
        post += "&";
    post += "cm_json=" + ((String) rx.get("cm_string1"));

    // Prepare URL request
    String s = "";
    try {
        //Connect
        u = new URL(url);
        c = (HttpURLConnection) u.openConnection();

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length));
        if (base64string != "")
            c.setRequestProperty("Authorization", "Basic " + base64string);
        c.setUseCaches(false);
        c.setDoInput(true);
        c.setDoOutput(true);

        //Send request
        DataOutputStream dos = new DataOutputStream(c.getOutputStream());
        dos.writeBytes(post);
        dos.flush();
        dos.close();
    } catch (Exception e) {
        if (c != null)
            c.disconnect();

        r.put("cm_return", new Long(1));
        r.put("cm_error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
        return r;
    }

    r.put("cm_return", new Long(0));

    // Check if download, not json!
    if (download) {
        String name = "default_download_name.dat";

        x = ((String) i.get("cm_web_filename"));
        if (x != null && x != "") {
            File xf = new File(x);
            name = xf.getName();
        }

        if (save_to_file != null && save_to_file != "")
            name = save_to_file;

        //Reading response in binary and at the same time saving to file
        try {
            //Read response
            DataInputStream dis = new DataInputStream(c.getInputStream());
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(name));

            byte[] buf = new byte[16384];

            int len;

            while ((len = dis.read(buf)) != -1)
                dos.write(buf, 0, len);

            dos.close();
            dis.close();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("cm_return", new Long(1));
            r.put("cm_error",
                    "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ...");
            return r;
        }
    } else {
        //Reading response in text
        try {
            //Read response
            InputStream is = c.getInputStream();
            BufferedReader f = new BufferedReader(new InputStreamReader(is));
            StringBuffer ss = new StringBuffer();

            while ((x = f.readLine()) != null) {
                ss.append(x);
                ss.append('\r');
            }

            f.close();
            s = ss.toString();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("cm_return", new Long(1));
            r.put("cm_error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
            return r;
        }

        if (con == "json_after_text") {
            String json_sep = "*** ### --- CM JSON SEPARATOR --- ### ***";
            int li = s.lastIndexOf(json_sep);
            if (li >= 0) {
                s = s.substring(li + json_sep.length());
                s = s.trim();
            }
        }

        if (con == "json_after_text" || con == "json") {
            //Parsing json
            try {
                JSONParser parser = new JSONParser();
                r = (JSONObject) parser.parse(s);
            } catch (ParseException ex) {
                r.put("cm_return", new Long(1));
                r.put("cm_error", "can't parse json output (" + ex + ") ...");
                return r;
            }
        } else
            r.put("cm_stdout", s);
    }

    if (c != null)
        c.disconnect();

    return r;
}

From source file:org.openme_ck.openme_ck.java

public static JSONObject remote_access(JSONObject i) {
    /*//from w  w w . j  a  v  a 2  s . co  m
    Input:  {
      remote_server_url      - remote server URL
      (module_uoa)           - module to run
      (action)               - action to perform
                                  if =='download', prepare entry/file download through Internet
            
      (save_to_file)         - if web_action==download,
                                  save output to this file
            
      (out)                  - if 'json', treat output as json
                                  if 'json_after_text', strip everything before json
                                  if 'txt', output to stdout
            
      ...                    - all other request parameters
            
      //FGG TBD - should add support for proxy
    }
            
    Output: {
      return   - return code = 0 if successful
                                > 0 if error
                                < 0 if warning (rarely used at this moment)
      (error)  - error text, if return > 0
      (stdout) - if out='txt', output there
    }
    */

    // Prepare return object
    JSONObject r = new JSONObject();

    URL u;
    HttpURLConnection c = null;

    // Prepare request
    String x = "";
    String post = "";

    String con = "";
    x = (String) i.get("out");
    if (x != null && x != "")
        con = x;

    String url = (String) i.get("remote_server_url");
    if (url == null || url == "") {
        r.put("return", new Long(1));
        r.put("error", "'remote_server_url is not defined");
        return r;
    }
    i.remove("remote_server_url");

    String save_to_file = (String) i.get("save_to_file");
    if (save_to_file != null)
        i.remove("save_to_file");

    // Check if data download, not json and convert it to download request
    boolean download = false;

    x = (String) i.get("action");
    if (x == "download" || x == "show") {
        download = true;
        if (post != "")
            post += "&";
        post += "module_uoa=web&action=" + x;
        i.remove("action");

        if (((String) i.get("module_uoa")) != null)
            i.remove("module_uoa");
        if (((String) i.get("out")) != null)
            i.remove("out");
    }

    // Prepare dict to transfer through Internet
    JSONObject ii = new JSONObject();
    ii.put("dict", i);
    JSONObject rx = convert_array_to_uri(ii);
    if ((Long) rx.get("return") > 0)
        return rx;

    if (post != "")
        post += "&";
    post += "ck_json=" + ((String) rx.get("string"));

    // Prepare URL request
    String s = "";
    try {
        //Connect
        u = new URL(url);
        c = (HttpURLConnection) u.openConnection();

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length));
        c.setUseCaches(false);
        c.setDoInput(true);
        c.setDoOutput(true);

        //Send request
        DataOutputStream dos = new DataOutputStream(c.getOutputStream());
        dos.writeBytes(post);
        dos.flush();
        dos.close();
    } catch (Exception e) {
        if (c != null)
            c.disconnect();

        r.put("return", new Long(1));
        r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
        return r;
    }

    r.put("return", new Long(0));

    // Check if download, not json!
    if (download) {
        String name = "default_download_name.dat";

        x = ((String) i.get("filename"));
        if (x != null && x != "") {
            File xf = new File(x);
            name = xf.getName();
        }

        if (save_to_file != null && save_to_file != "")
            name = save_to_file;

        //Reading response in binary and at the same time saving to file
        try {
            //Read response
            DataInputStream dis = new DataInputStream(c.getInputStream());
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(name));

            byte[] buf = new byte[16384];

            int len;

            while ((len = dis.read(buf)) != -1)
                dos.write(buf, 0, len);

            dos.close();
            dis.close();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Long(1));
            r.put("error",
                    "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ...");
            return r;
        }
    } else {
        //Reading response in text
        try {
            //Read response
            InputStream is = c.getInputStream();
            BufferedReader f = new BufferedReader(new InputStreamReader(is));
            StringBuffer ss = new StringBuffer();

            while ((x = f.readLine()) != null) {
                ss.append(x);
                ss.append('\r');
            }

            f.close();
            s = ss.toString();
        } catch (Exception e) {
            if (c != null)
                c.disconnect();

            r.put("return", new Long(1));
            r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ...");
            return r;
        }

        if (con == "json_after_text") {
            int li = s.lastIndexOf(json_sep);
            if (li >= 0) {
                s = s.substring(li + json_sep.length());

                li = s.lastIndexOf(json_sep2);
                if (li > 0) {
                    s = s.substring(0, li);
                }

                s = s.trim();
            }
        }

        if (con == "json_after_text" || con == "json") {
            //Parsing json
            try {
                JSONParser parser = new JSONParser();
                r = (JSONObject) parser.parse(s);
            } catch (ParseException ex) {
                r.put("return", new Long(1));
                r.put("error", "can't parse json output (" + ex + ") ...");
                return r;
            }
        } else
            r.put("stdout", s);
    }

    if (c != null)
        c.disconnect();

    return r;
}

From source file:org.talend.components.splunk.objects.SplunkJSONEventTest.java

@Test
public void testSplunkJSONEventFieldsSetting() {
    SplunkJSONEvent splunkEvent = new SplunkJSONEvent();

    // Test setting some metadata fields
    splunkEvent.put(SplunkJSONEventField.INDEX, "index");
    splunkEvent.put(SplunkJSONEventField.SOURCE, "localhost");

    // Assert set fields
    assertTrue("Index should be equal to index",
            "index".equals(splunkEvent.get(SplunkJSONEventField.INDEX.getName())));
    assertTrue("Source should be equal to localhost",
            "localhost".equals(splunkEvent.get(SplunkJSONEventField.SOURCE.getName())));

    // Try to set null values. It shouldn't be set.
    splunkEvent.put(SplunkJSONEventField.HOST, null);
    assertFalse("Host value was set to null. It shouldn't be set.",
            splunkEvent.containsKey(SplunkJSONEventField.HOST.getName()));

    // Try to add event field
    splunkEvent.addEventObject("Field1", "Value1");
    splunkEvent.addEventObject("FieldInt", 123);

    // Check event fields
    JSONObject eventObject = (JSONObject) splunkEvent.get(SplunkJSONEventField.EVENT.getName());
    assertFalse("Event Field should not be null", eventObject == null);

    assertTrue("Field1 value should be equal to Value1", "Value1".equals(eventObject.remove("Field1")));
    assertTrue("FieldInt value should be int value and be equal to 123",
            (int) eventObject.remove("FieldInt") == 123);

    // Nothing else should be in the event object
    assertTrue("Nothing should be left in the event object", eventObject.size() == 0);
}

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

/**
 * Create a new version of the <code>api</code>, with version <code>newVersion</code>
 *
 * @param api        The API to be copied
 * @param newVersion The version of the new API
 * @throws org.wso2.carbon.apimgt.api.model.DuplicateAPIException
 *          If the API trying to be created already exists
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 *          If an error occurs while trying to create
 *          the new version of the API/* w ww.  j av  a 2s. c  o m*/
 */
public void createNewAPIVersion(API api, String newVersion)
        throws DuplicateAPIException, APIManagementException {
    String apiSourcePath = APIUtil.getAPIPath(api.getId());

    String targetPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR
            + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName()
            + RegistryConstants.PATH_SEPARATOR + newVersion + APIConstants.API_RESOURCE_NAME;

    boolean transactionCommitted = false;
    try {
        if (registry.resourceExists(targetPath)) {
            throw new DuplicateAPIException("API already exists with version: " + newVersion);
        }
        registry.beginTransaction();
        Resource apiSourceArtifact = registry.get(apiSourcePath);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiSourceArtifact.getUUID());

        //Create new API version
        artifact.setId(UUID.randomUUID().toString());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, newVersion);

        //Check the status of the existing api,if its not in 'CREATED' status set
        //the new api status as "CREATED"
        String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        if (!APIConstants.CREATED.equals(status)) {
            artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, APIConstants.CREATED);
        }

        if (api.isDefaultVersion()) {
            artifact.setAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION, "true");
            //Check whether an existing API is set as default version.
            String defaultVersion = getDefaultVersion(api.getId());

            //if so, change its DefaultAPIVersion attribute to false

            if (defaultVersion != null) {
                APIIdentifier defaultAPIId = new APIIdentifier(api.getId().getProviderName(),
                        api.getId().getApiName(), defaultVersion);
                updateDefaultAPIInRegistry(defaultAPIId, false);
            }
        } else {
            artifact.setAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION, "false");
        }
        //Check whether the existing api has its own thumbnail resource and if yes,add that image
        //thumb to new API                                       thumbnail path as well.
        String thumbUrl = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR
                + api.getId().getProviderName() + RegistryConstants.PATH_SEPARATOR + api.getId().getApiName()
                + RegistryConstants.PATH_SEPARATOR + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR
                + APIConstants.API_ICON_IMAGE;
        if (registry.resourceExists(thumbUrl)) {
            Resource oldImage = registry.get(thumbUrl);
            apiSourceArtifact.getContentStream();
            APIIdentifier newApiId = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(),
                    newVersion);
            ResourceFile icon = new ResourceFile(oldImage.getContentStream(), oldImage.getMediaType());
            artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL,
                    addResourceFile(APIUtil.getIconPath(newApiId), icon));
        }
        // If the API has custom mediation policy, copy it to new version.

        String inSeqFilePath = APIUtil.getSequencePath(api.getId(), "in");

        if (registry.resourceExists(inSeqFilePath)) {

            APIIdentifier newApiId = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(),
                    newVersion);

            String inSeqNewFilePath = APIUtil.getSequencePath(newApiId, "in");
            org.wso2.carbon.registry.api.Collection inSeqCollection = (org.wso2.carbon.registry.api.Collection) registry
                    .get(inSeqFilePath);
            if (inSeqCollection != null) {
                String[] inSeqChildPaths = inSeqCollection.getChildren();
                for (String inSeqChildPath : inSeqChildPaths) {
                    Resource inSequence = registry.get(inSeqChildPath);

                    ResourceFile seqFile = new ResourceFile(inSequence.getContentStream(),
                            inSequence.getMediaType());
                    OMElement seqElment = APIUtil.buildOMElement(inSequence.getContentStream());
                    String seqFileName = seqElment.getAttributeValue(new QName("name"));
                    addResourceFile(inSeqNewFilePath + seqFileName, seqFile);
                }
            }
        }

        String outSeqFilePath = APIUtil.getSequencePath(api.getId(), "out");

        if (registry.resourceExists(outSeqFilePath)) {

            APIIdentifier newApiId = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(),
                    newVersion);

            String outSeqNewFilePath = APIUtil.getSequencePath(newApiId, "out");
            org.wso2.carbon.registry.api.Collection outSeqCollection = (org.wso2.carbon.registry.api.Collection) registry
                    .get(outSeqFilePath);
            if (outSeqCollection != null) {
                String[] outSeqChildPaths = outSeqCollection.getChildren();
                for (String outSeqChildPath : outSeqChildPaths) {
                    Resource outSequence = registry.get(outSeqChildPath);

                    ResourceFile seqFile = new ResourceFile(outSequence.getContentStream(),
                            outSequence.getMediaType());
                    OMElement seqElment = APIUtil.buildOMElement(outSequence.getContentStream());
                    String seqFileName = seqElment.getAttributeValue(new QName("name"));
                    addResourceFile(outSeqNewFilePath + seqFileName, seqFile);
                }
            }
        }

        // Here we keep the old context
        String oldContext = artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT);

        // We need to change the context by setting the new version
        // This is a change that is coming with the context version strategy
        String contextTemplate = artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE);
        artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT,
                contextTemplate.replace("{version}", newVersion));

        artifactManager.addGenericArtifact(artifact);
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        //Attach the API lifecycle
        artifact.attachLifecycle(APIConstants.API_LIFE_CYCLE);
        registry.addAssociation(APIUtil.getAPIProviderPath(api.getId()), targetPath,
                APIConstants.PROVIDER_ASSOCIATION);
        String roles = artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
        String[] rolesSet = new String[0];
        if (roles != null) {
            rolesSet = roles.split(",");
        }
        APIUtil.setResourcePermissions(api.getId().getProviderName(),
                artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY), rolesSet, artifactPath);
        //Here we have to set permission specifically to image icon we added
        String iconPath = artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL);
        if (iconPath != null && iconPath.lastIndexOf("/apimgt") != -1) {
            iconPath = iconPath.substring(iconPath.lastIndexOf("/apimgt"));
            APIUtil.copyResourcePermissions(api.getId().getProviderName(), thumbUrl, iconPath);
        }
        // Retain the tags
        org.wso2.carbon.registry.core.Tag[] tags = registry.getTags(apiSourcePath);
        if (tags != null) {
            for (org.wso2.carbon.registry.core.Tag tag : tags) {
                registry.applyTag(targetPath, tag.getTagName());
            }
        }

        // Retain the docs
        List<Documentation> docs = getAllDocumentation(api.getId());
        APIIdentifier newId = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(),
                newVersion);
        API newAPI = getAPI(newId, api.getId(), oldContext);

        if (api.isDefaultVersion()) {
            newAPI.setAsDefaultVersion(true);
        } else {
            newAPI.setAsDefaultVersion(false);
        }

        for (Documentation doc : docs) {
            /* copying the file in registry for new api */
            Documentation.DocumentSourceType sourceType = doc.getSourceType();
            if (sourceType == Documentation.DocumentSourceType.FILE) {
                String absoluteSourceFilePath = doc.getFilePath();
                // extract the prepend
                // ->/registry/resource/_system/governance/ and for
                // tenant
                // /t/my.com/registry/resource/_system/governance/
                int prependIndex = absoluteSourceFilePath.indexOf(APIConstants.API_LOCATION);
                String prependPath = absoluteSourceFilePath.substring(0, prependIndex);
                // get the file name from absolute file path
                int fileNameIndex = absoluteSourceFilePath.lastIndexOf(RegistryConstants.PATH_SEPARATOR);
                String fileName = absoluteSourceFilePath.substring(fileNameIndex + 1);
                // create relative file path of old location
                String sourceFilePath = absoluteSourceFilePath.substring(prependIndex);
                // create the relative file path where file should be
                // copied
                String targetFilePath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR
                        + newId.getProviderName() + RegistryConstants.PATH_SEPARATOR + newId.getApiName()
                        + RegistryConstants.PATH_SEPARATOR + newId.getVersion()
                        + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR
                        + RegistryConstants.PATH_SEPARATOR + APIConstants.DOCUMENT_FILE_DIR
                        + RegistryConstants.PATH_SEPARATOR + fileName;
                // copy the file from old location to new location(for
                // new api)
                registry.copy(sourceFilePath, targetFilePath);
                // update the filepath attribute in doc artifact to
                // create new doc artifact for new version of api
                doc.setFilePath(prependPath + targetFilePath);
            }
            createDocumentation(newAPI, doc);
            String content = getDocumentationContent(api.getId(), doc.getName());
            if (content != null) {
                addDocumentationContent(newAPI, doc.getName(), content);
            }
        }

        //Copy Swagger 2.0 resources for New version. 
        String resourcePath = APIUtil.getSwagger20DefinitionFilePath(api.getId().getApiName(),
                api.getId().getVersion(), api.getId().getProviderName());
        if (registry.resourceExists(resourcePath + APIConstants.API_DOC_2_0_RESOURCE_NAME)) {
            JSONObject swaggerObject = (JSONObject) new JSONParser()
                    .parse(definitionFromSwagger20.getAPIDefinition(api.getId(), registry));
            JSONObject infoObject = (JSONObject) swaggerObject.get("info");
            infoObject.remove("version");
            infoObject.put("version", newAPI.getId().getVersion());
            definitionFromSwagger20.saveAPIDefinition(newAPI, swaggerObject.toJSONString(), registry);
        }

        // Make sure to unset the isLatest flag on the old version
        GenericArtifact oldArtifact = artifactManager.getGenericArtifact(apiSourceArtifact.getUUID());
        oldArtifact.setAttribute(APIConstants.API_OVERVIEW_IS_LATEST, "false");
        artifactManager.updateGenericArtifact(oldArtifact);

        int tenantId;
        String tenantDomain = MultitenantUtils
                .getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        try {
            tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            throw new APIManagementException(
                    "Error in retrieving Tenant Information while adding api :" + api.getId().getApiName(), e);
        }

        apiMgtDAO.addAPI(newAPI, tenantId);
        registry.commitTransaction();
        transactionCommitted = true;

        if (log.isDebugEnabled()) {
            String logMessage = "Successfully created new version : " + newVersion + " of : "
                    + api.getId().getApiName();
            log.debug(logMessage);
        }

        //Sending Notifications to existing subscribers
        try {
            String isNotificationEnabled = "false";
            Registry configRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getConfigSystemRegistry(tenantId);
            if (configRegistry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) {
                Resource resource = configRegistry.get(APIConstants.API_TENANT_CONF_LOCATION);
                String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
                if (content != null) {
                    JSONObject tenantConfig = (JSONObject) new JSONParser().parse(content);
                    isNotificationEnabled = (String) tenantConfig.get(NotifierConstants.NOTIFICATIONS_ENABLED);
                }
            }

            if (JavaUtils.isTrueExplicitly(isNotificationEnabled)) {

                Properties prop = new Properties();
                prop.put(NotifierConstants.API_KEY, api.getId());
                prop.put(NotifierConstants.NEW_API_KEY, newAPI.getId());

                Set<Subscriber> subscribersOfAPI = apiMgtDAO.getSubscribersOfAPI(api.getId());
                prop.put(NotifierConstants.SUBSCRIBERS_PER_API, subscribersOfAPI);

                Set<Subscriber> subscribersOfProvider = apiMgtDAO
                        .getSubscribersOfProvider(api.getId().getProviderName());
                prop.put(NotifierConstants.SUBSCRIBERS_PER_API, subscribersOfProvider);

                NotificationDTO notificationDTO = new NotificationDTO(prop,
                        NotifierConstants.NOTIFICATION_TYPE_NEW_VERSION);
                notificationDTO.setTenantID(tenantId);
                notificationDTO.setTenantDomain(tenantDomain);
                new NotificationExecutor().sendAsyncNotifications(notificationDTO);

            }
        } catch (NotificationException e) {
            log.error(e.getMessage(), e);
        }

    } catch (DuplicateAPIException e) {
        throw e;
    } catch (ParseException e) {
        String msg = "Couldn't Create json Object from Swagger object for version" + newVersion + " of : "
                + api.getId().getApiName();
        handleException(msg, e);
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            handleException("Error while rolling back the transaction for API: " + api.getId(), re);
        }
        String msg = "Failed to create new version : " + newVersion + " of : " + api.getId().getApiName();
        handleException(msg, e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            handleException("Error while rolling back the transaction for API: " + api.getId(), ex);
        }
    }
}

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

/**
 * @param resource        api-doc related to 1.1 definition
 * @param allParameters12 map containing all the parameters extracted
 *                        from each resource of swagger 1.2
 * @return JSON string of the updated Swagger 1.1 definition
 *//*  www.jav  a  2  s . com*/
public static String getUpdatedSwagger11Resource(JSONObject resource, Map<String, JSONArray> allParameters12) {

    log.info("===================== getUpdatedSwagger11Resource =========================");

    String resourcePath = (String) resource.get(Constants.API_DOC_11_RESOURCE_PATH);
    String apiVersion = (String) resource.get(Constants.API_DOC_11_API_VERSION);
    String resourcePathPrefix = resourcePath + "/" + apiVersion;

    log.info("resourcePath for 1.1 : " + resourcePath);
    log.info("apiVersion : " + apiVersion);
    log.info("resourcePathPrefix : " + resourcePathPrefix);

    JSONArray apis = (JSONArray) resource.get(Constants.API_DOC_11_APIS);
    for (Object api : apis) {
        JSONObject apiInfo = (JSONObject) api;
        log.info("\n\napiInfo : " + apiInfo.toJSONString());

        String path = (String) apiInfo.get(Constants.API_DOC_11_PATH);
        path = path.substring(resourcePathPrefix.length());
        JSONArray operations = (JSONArray) apiInfo.get(Constants.API_DOC_11_OPERATIONS);

        log.info("\n\noperations : " + operations.toJSONString());

        for (Object operation1 : operations) {
            JSONObject operation = (JSONObject) operation1;
            log.info("\n\noperation : " + operation);
            String method = (String) operation.get(Constants.API_DOC_11_METHOD);

            String key = path + "_" + method.toLowerCase();

            log.info("\nkey : " + key);

            //if there are parameters already in this
            JSONArray existingParams = (JSONArray) operation.get(Constants.API_DOC_11_PARAMETERS);

            log.info("\nexistingParams : " + existingParams);
            //maintain the list of original parameters to avoid duplicates
            JSONArray originalParams = existingParams;

            JSONArray parameters;
            if (allParameters12.containsKey(key)) {
                log.info("\nallParameters12.containsKey(key) : " + key);
                parameters = allParameters12.get(key);
                log.info("\nparameters : " + parameters.toJSONString());

                //setting the 'type' to 'string' if this variable is missing
                for (int m = 0; m < parameters.size(); m++) {
                    JSONObject para = (JSONObject) parameters.get(m);
                    log.info("\n\npara : " + para.toJSONString());
                    if (noSuchParameter(originalParams, (String) para.get(Constants.API_DOC_11_PARAM_NAME),
                            (String) para.get(Constants.API_DOC_11_PARAM_TYPE))) {
                        log.info("\nnoSuchParameter");
                        String dataType = "";
                        if (para.containsKey(Constants.API_DOC_12_DATA_TYPE)) {
                            log.info("\npara.containsKey(Constants.API_DOC_12_DATA_TYPE)");
                            dataType = (String) para.get(Constants.API_DOC_12_DATA_TYPE);
                        }

                        log.info("\ndataType : " + dataType);
                        para.put(Constants.API_DOC_11_DATA_TYPE, dataType);
                        para.remove(Constants.API_DOC_12_DATA_TYPE);
                        existingParams.add(existingParams.size(), para);
                    }
                }
            }

            log.info("\nexistingParams after loop : " + existingParams);
            operation.put(Constants.API_DOC_12_PARAMETERS, existingParams);
        }
    }

    return resource.toJSONString();
}

From source file:org.wso2.carbon.dashboard.migratetool.DSMigrationTool.java

/**
 * Update the gadgetJSON in the gadgets folders.iterate through all the gadgets and update the gadget jsons
 *
 * @param artifactPath artifact path which consists the gadgets folders
 *//*w ww .ja va2 s  .  co m*/
protected void gadgetJSONUpdater(File artifactPath) {
    File[] listOfFiles = artifactPath.listFiles();
    String modifiedGadgetID;
    JSONObject gadgetJSONObject, gadgetDataObj;
    String thumbnail;
    String url;
    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isDirectory()) {
            try {
                JSONParser jsonParser = new JSONParser();
                Object obj = jsonParser.parse(new FileReader(artifactPath + File.separator
                        + listOfFiles[i].getName() + File.separator + GADGET_JSON));
                gadgetJSONObject = (JSONObject) obj;
                modifiedGadgetID = listOfFiles[i].getName().toLowerCase();
                gadgetJSONObject.put("id", modifiedGadgetID);
                thumbnail = (String) gadgetJSONObject.get("thumbnail");
                gadgetDataObj = (JSONObject) gadgetJSONObject.get("data");
                url = (String) (gadgetDataObj).get("url");
                if ((thumbnail).contains(modifiedGadgetID)) {
                    gadgetJSONObject.remove("thumbnail");
                    gadgetJSONObject.put("thumbnail", replace(thumbnail, modifiedGadgetID, modifiedGadgetID));
                }
                gadgetDataObj.remove("url");
                if (url.toLowerCase().contains("local")) {
                    url = replace(url, "gadget", "fs/gadget");
                }
                gadgetDataObj.put("url", replace(url, modifiedGadgetID, modifiedGadgetID));
                FileWriter file = new FileWriter(artifactPath + File.separator + listOfFiles[i].getName()
                        + File.separator + GADGET_JSON);
                file.write(gadgetJSONObject.toJSONString());
                file.flush();
                file.close();
                listOfFiles[i].renameTo(new File(artifactPath + File.separator + modifiedGadgetID));
            } catch (IOException e) {
            } catch (ParseException e) {
            }
        }
    }
}

From source file:org.wso2.carbon.dashboard.migratetool.DSMigrationTool.java

/**
 * update the blocks section of dashboard json in order to compatible with carbon-dashboards version 1.0.15+
 *
 * @param blocksArray blocks array dashboard json
 *//*from w ww .  j  av a 2  s. co  m*/
protected void updateDashboardBlocks(JSONArray blocksArray) {
    JSONObject block = null;
    long col;
    long row;
    long size_y;
    long size_x;

    for (int i = 0; i < blocksArray.size(); i++) {
        block = (JSONObject) blocksArray.get(i);
        if (block.containsKey("col")) {
            col = (Long) block.get("col");
            block.put("x", col - 1);
            block.remove("col");
        }
        if (block.containsKey("row")) {
            row = (Long) block.get("row");
            block.put("y", row - 1);
            block.remove("row");
        }
        if (block.containsKey("size_x")) {
            size_x = (Long) block.get("size_x");
            block.put("width", size_x);
            block.remove("size_x");
        }
        if (block.containsKey("size_y")) {
            size_y = (Long) block.get("size_y");
            block.put("height", size_y);
            block.remove("size_y");
        }
    }
}

From source file:org.wso2.carbon.dashboard.migratetool.DSMigrationTool.java

/**
 * update the gadgetId of gadgets in the dashboard json with the modified gadgetID
 *
 * @param gadgetArr gadgets Array to update
 *///  w ww . ja va2s  .  c om
protected void dashboardGadgetUpdater(JSONArray gadgetArr) {
    JSONObject gadgetContentObj;
    String thumbnail, url;
    String gadgetID;
    JSONObject gadgetDataObj;
    for (int i = 0; i < gadgetArr.size(); i++) {
        gadgetContentObj = (JSONObject) ((JSONObject) gadgetArr.get(i)).get("content");
        gadgetDataObj = (JSONObject) gadgetContentObj.get("data");
        url = (String) (gadgetDataObj).get("url");
        gadgetID = getGadgetID(url);
        gadgetContentObj.remove("id");
        gadgetContentObj.put("id", gadgetID);
        thumbnail = (String) gadgetContentObj.get("thumbnail");
        if ((thumbnail).contains(gadgetID)) {
            gadgetContentObj.remove("thumbnail");
            gadgetContentObj.put("thumbnail", replace(thumbnail, gadgetID, gadgetID));
        }
        gadgetDataObj.remove("url");
        if (url.toLowerCase().contains("local")) {
            url = replace(url, "gadget", "fs/gadget");
        }
        gadgetDataObj.put("url", replace(url, gadgetID, gadgetID));
    }
}

From source file:org.wso2.carbon.dssapi.util.APIUtil.java

/**
 * To Create apis Json Object in swagger12 Json
 *
 * @param api           api Object//from   www .  j a v  a  2s. co m
 * @param swagger12Json swagger12 json object
 * @throws ParseException
 */
private static void createApis(API api, JSONObject swagger12Json) throws ParseException {
    Set<String> resourceMap = new LinkedHashSet<String>();
    JSONArray jsonArray = new JSONArray();
    Set<URITemplate> uriTemplateSet = api.getUriTemplates();
    Set<URITemplate> tempUriTemplates = new HashSet<URITemplate>();
    for (URITemplate uriTemplate : uriTemplateSet) {
        String uriTemplateString = uriTemplate.getUriTemplate();
        if (Pattern.compile("[/][{]\\w+[}]").matcher(uriTemplateString).find()) {
            String tempUriTemplate = uriTemplateString.replaceAll("[/][{]\\w+[}]", "");
            resourceMap.add(tempUriTemplate);

            uriTemplate.setUriTemplate(uriTemplateString.replaceFirst("[/][{]\\w+[}]", "/*"));
            tempUriTemplates.add(uriTemplate);
        } else {
            resourceMap.add(uriTemplateString);
            tempUriTemplates.add(uriTemplate);
        }
    }
    api.setUriTemplates(tempUriTemplates);
    for (String resource : resourceMap) {
        jsonArray.add(new JSONParser().parse("{\n" + "            \"description\":\"\",\n"
                + "            \"path\":\"" + resource + "\"\n" + "         }"));
    }
    JSONObject api_doc = (JSONObject) swagger12Json.get("api_doc");
    api_doc.put("apis", jsonArray);
    swagger12Json.remove("api_doc");
    swagger12Json.put("api_doc", api_doc);
}

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  . j  a  v a 2 s .  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;
}