Example usage for org.apache.http.entity.mime.content FileBody getInputStream

List of usage examples for org.apache.http.entity.mime.content FileBody getInputStream

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content FileBody getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Usage

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

/**
 * This method is to functionality of add a new API in API-Provider
 *
 * @param cx      Rhino context/*w ww.  j  ava  2  s .c  o  m*/
 * @param thisObj Scriptable object
 * @param args    Passing arguments
 * @param funObj  Function object
 * @return true if the API was added successfully
 * @throws APIManagementException Wrapped exception by org.wso2.carbon.apimgt.api.APIManagementException
 * @throws FaultGatewaysException
 */
public static boolean jsFunction_addAPI(Context cx, Scriptable thisObj, Object[] args, Function funObj)
        throws APIManagementException, ScriptException, FaultGatewaysException {
    if (args == null || args.length == 0) {
        handleException("Invalid number of input parameters.");
    }

    boolean success;
    NativeObject apiData = (NativeObject) args[0];
    String provider = String.valueOf(apiData.get("provider", apiData));
    if (provider != null) {
        provider = APIUtil.replaceEmailDomain(provider);
    }

    String name = (String) apiData.get("apiName", apiData);
    String version = (String) apiData.get("version", apiData);
    String defaultVersion = (String) apiData.get("defaultVersion", apiData);
    String description = (String) apiData.get("description", apiData);
    String endpoint = (String) apiData.get("endpoint", apiData);
    String sandboxUrl = (String) apiData.get("sandbox", apiData);
    String visibility = (String) apiData.get("visibility", apiData);
    String thumbUrl = (String) apiData.get("thumbUrl", apiData);
    String environments = (String) apiData.get("environments", apiData);
    String visibleRoles = "";

    if (name != null) {
        name = name.trim();
        if (name.isEmpty()) {
            handleException("API name is not specified");
        }
    }

    if (version != null) {
        version = version.trim();
        if (version.isEmpty()) {
            handleException("Version not specified for API " + name);
        }
    }

    if (visibility != null && visibility.equals(APIConstants.API_RESTRICTED_VISIBILITY)) {
        visibleRoles = (String) apiData.get("visibleRoles", apiData);
    }

    if (sandboxUrl != null && sandboxUrl.trim().length() == 0) {
        sandboxUrl = null;
    }

    if (endpoint != null && endpoint.trim().length() == 0) {
        endpoint = null;
    }

    if (endpoint != null && !endpoint.startsWith("http") && !endpoint.startsWith("https")) {
        endpoint = "http://" + endpoint;
    }
    if (sandboxUrl != null && !sandboxUrl.startsWith("http") && !sandboxUrl.startsWith("https")) {
        sandboxUrl = "http://" + sandboxUrl;
    }

    String redirectURL = (String) apiData.get("redirectURL", apiData);
    boolean advertiseOnly = Boolean.parseBoolean((String) apiData.get("advertiseOnly", apiData));
    String apiOwner = (String) apiData.get("apiOwner", apiData);

    if (apiOwner == null || apiOwner.equals("")) {
        apiOwner = provider;
    }

    String wsdl = (String) apiData.get("wsdl", apiData);
    String wadl = (String) apiData.get("wadl", apiData);
    String tags = (String) apiData.get("tags", apiData);

    String subscriptionAvailability = (String) apiData.get("subscriptionAvailability", apiData);
    String subscriptionAvailableTenants = "";
    if (subscriptionAvailability != null
            && subscriptionAvailability.equals(APIConstants.SUBSCRIPTION_TO_SPECIFIC_TENANTS)) {
        subscriptionAvailableTenants = (String) apiData.get("subscriptionTenants", apiData);
    }

    Set<String> tag = new HashSet<String>();

    if (tags != null) {
        if (tags.contains(",")) {
            String[] userTag = tags.split(",");
            tag.addAll(Arrays.asList(userTag).subList(0, tags.split(",").length));
        } else {
            tag.add(tags);
        }
    }

    String transport = getTransports(apiData);

    String tier = (String) apiData.get("tier", apiData);
    if (StringUtils.isBlank(tier)) {
        handleException("No tier defined for the API");
    }
    FileHostObject fileHostObject = (FileHostObject) apiData.get("imageUrl", apiData);
    String contextVal = (String) apiData.get("context", apiData);

    if (contextVal.isEmpty()) {
        handleException("Context not defined for API");
    }

    if (contextVal.endsWith("/")) {
        handleException("Context cannot end with '/' character");
    }

    APIProvider apiProvider = getAPIProvider(thisObj);
    //check for context exists
    if (apiProvider.isDuplicateContextTemplate(contextVal)) {
        handleException("Error occurred while adding the API. A duplicate API context already exists for "
                + contextVal);
    }
    String context = contextVal.startsWith("/") ? contextVal : ("/" + contextVal);
    String providerDomain = MultitenantUtils.getTenantDomain(String.valueOf(apiData.get("provider", apiData)));
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain)) {
        //Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }

    // This is to support the new Pluggable version strategy
    // if the context does not contain any {version} segment, we use the default version strategy.
    context = checkAndSetVersionParam(context);

    String contextTemplate = context;
    context = updateContextWithVersion(version, contextVal, context);

    NativeArray uriTemplateArr = (NativeArray) apiData.get("uriTemplateArr", apiData);

    String techOwner = (String) apiData.get("techOwner", apiData);
    String techOwnerEmail = (String) apiData.get("techOwnerEmail", apiData);
    String bizOwner = (String) apiData.get("bizOwner", apiData);
    String bizOwnerEmail = (String) apiData.get("bizOwnerEmail", apiData);

    String endpointSecured = (String) apiData.get("endpointSecured", apiData);
    String endpointAuthDigest = (String) apiData.get("endpointAuthDigest", apiData);
    String endpointUTUsername = (String) apiData.get("endpointUTUsername", apiData);
    String endpointUTPassword = (String) apiData.get("endpointUTPassword", apiData);

    String inSequence = (String) apiData.get("inSequence", apiData);
    String outSequence = (String) apiData.get("outSequence", apiData);
    String faultSequence = (String) apiData.get("faultSequence", apiData);

    String responseCache = (String) apiData.get("responseCache", apiData);
    String corsConfiguraion = (String) apiData.get("corsConfiguration", apiData);

    int cacheTimeOut = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
    if (APIConstants.ENABLED.equalsIgnoreCase(responseCache)) {
        responseCache = APIConstants.ENABLED;
        try {
            cacheTimeOut = Integer.parseInt((String) apiData.get("cacheTimeout", apiData));
        } catch (NumberFormatException e) {
            //ignore
        }
    } else {
        responseCache = APIConstants.DISABLED;
    }

    provider = (provider != null ? provider.trim() : null);
    name = (name != null ? name.trim() : null);
    version = (version != null ? version.trim() : null);
    APIIdentifier apiId = new APIIdentifier(provider, name, version);

    if (apiProvider.isAPIAvailable(apiId)) {
        handleException("Error occurred while adding the API. A duplicate API already exists for " + name + "-"
                + version);
    }

    API api = new API(apiId);

    // to keep the backword compatibility if swagger not set process from
    // resource_config or old way.
    if (apiData.get("swagger", apiData) == null) {
        if (apiData.get("resource_config", apiData) != null) {
            Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
            JSONParser parser = new JSONParser();
            JSONObject resourceConfig = null;

            try {
                resourceConfig = (JSONObject) parser.parse((String) apiData.get("resource_config", apiData));
            } catch (ParseException e) {
                handleException("Invalid resource config", e);
            } catch (ClassCastException e) {
                handleException("Unable to create JSON object from resource config", e);
            }

            // process scopes
            JSONArray scopes = (JSONArray) resourceConfig.get("scopes");
            Set<Scope> scopeList = new LinkedHashSet<Scope>();
            for (int i = 0; i < scopes.size(); i++) {
                Map scope = (Map) scopes.get(i); // access with get() method
                Scope scopeObj = new Scope();
                scopeObj.setKey((String) scope.get("key"));
                scopeObj.setName((String) scope.get("name"));
                scopeObj.setRoles((String) scope.get("roles"));
                scopeObj.setDescription((String) scope.get("description"));
                scopeList.add(scopeObj);
            }
            api.setScopes(scopeList);

            JSONArray resources = (JSONArray) resourceConfig.get("resources");
            for (int k = 0; k < resources.size(); k++) {
                JSONObject resource = (JSONObject) resources.get(k);

                Map http_verbs = (Map) resource.get("http_verbs");
                Iterator iterator = http_verbs.entrySet().iterator();

                while (iterator.hasNext()) {
                    Map.Entry mapEntry = (Map.Entry) iterator.next();
                    Map mapEntryValue = (Map) mapEntry.getValue();

                    URITemplate template = new URITemplate();
                    String uriTempVal = (String) resource.get("url_pattern");
                    uriTempVal = uriTempVal.startsWith("/") ? uriTempVal : ("/" + uriTempVal);
                    template.setUriTemplate(uriTempVal);
                    String verb = (String) mapEntry.getKey();
                    if (isHTTPMethodValid(verb)) {
                        template.setHTTPVerb(verb);
                    } else {
                        handleException("Specified HTTP verb " + verb + " is invalid");
                    }

                    String authType = (String) mapEntryValue.get("auth_type");
                    if (authType.equals("Application & Application User")) {
                        authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                    }
                    if (authType.equals("Application User")) {
                        authType = "Application_User";
                    }
                    if (authType.equals("Application")) {
                        authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN;
                    }
                    template.setThrottlingTier((String) mapEntryValue.get("throttling_tier"));
                    template.setAuthType(authType);
                    template.setResourceURI(endpoint);
                    template.setResourceSandboxURI(sandboxUrl);
                    Scope scope = APIUtil.findScopeByKey(scopeList, (String) mapEntryValue.get("scope"));
                    template.setScope(scope);
                    uriTemplates.add(template);
                }
            }
            // todo handle casting exceptions
            api.setUriTemplates(uriTemplates);
            // todo clean out the code.
        } else {
            // following is the old fashioned way of processing resources
            NativeArray uriMethodArr = (NativeArray) apiData.get("uriMethodArr", apiData);
            NativeArray authTypeArr = (NativeArray) apiData.get("uriAuthMethodArr", apiData);
            NativeArray throttlingTierArr = (NativeArray) apiData.get("throttlingTierArr", apiData);
            if (uriTemplateArr != null && uriMethodArr != null && authTypeArr != null) {
                if (uriTemplateArr.getLength() == uriMethodArr.getLength()) {
                    Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
                    for (int i = 0; i < uriTemplateArr.getLength(); i++) {
                        String uriMethods = (String) uriMethodArr.get(i, uriMethodArr);
                        String uriMethodsAuthTypes = (String) authTypeArr.get(i, authTypeArr);
                        String[] uriMethodArray = uriMethods.split(",");
                        String[] authTypeArray = uriMethodsAuthTypes.split(",");
                        String uriMethodsThrottlingTiers = (String) throttlingTierArr.get(i, throttlingTierArr);
                        String[] throttlingTierArray = uriMethodsThrottlingTiers.split(",");
                        for (int k = 0; k < uriMethodArray.length; k++) {
                            for (int j = 0; j < authTypeArray.length; j++) {
                                if (j == k) {
                                    URITemplate template = new URITemplate();
                                    String uriTemp = (String) uriTemplateArr.get(i, uriTemplateArr);
                                    String uriTempVal = uriTemp.startsWith("/") ? uriTemp : ("/" + uriTemp);
                                    template.setUriTemplate(uriTempVal);
                                    String throttlingTier = throttlingTierArray[j];

                                    if (isHTTPMethodValid(uriMethodArray[k])) {
                                        template.setHTTPVerb(uriMethodArray[k]);
                                    } else {
                                        handleException(
                                                "Specified HTTP verb " + uriMethodArray[k] + " is invalid");
                                    }

                                    String authType = authTypeArray[j];
                                    if (authType.equals("Application & Application User")) {
                                        authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                                    }
                                    if (authType.equals("Application User")) {
                                        authType = "Application_User";
                                    }
                                    if (authType.equals("Application")) {
                                        authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN;
                                    }

                                    template.setThrottlingTier(throttlingTier);
                                    template.setAuthType(authType);
                                    template.setResourceURI(endpoint);
                                    template.setResourceSandboxURI(sandboxUrl);

                                    uriTemplates.add(template);
                                    break;
                                }

                            }
                        }

                    }
                    api.setUriTemplates(uriTemplates);
                }
            }
        }
    }

    api.setDescription(StringEscapeUtils.escapeHtml(description));
    api.setWsdlUrl(wsdl);
    api.setWadlUrl(wadl);
    api.setLastUpdated(new Date());
    api.setUrl(endpoint);
    api.setSandboxUrl(sandboxUrl);
    api.addTags(tag);
    api.setTransports(transport);
    api.setApiOwner(apiOwner);
    api.setAdvertiseOnly(advertiseOnly);
    api.setRedirectURL(redirectURL);
    api.setSubscriptionAvailability(subscriptionAvailability);
    api.setSubscriptionAvailableTenants(subscriptionAvailableTenants);
    api.setResponseCache(responseCache);
    api.setCacheTimeout(cacheTimeOut);
    api.setAsDefaultVersion("default_version".equals(defaultVersion));

    api.setProductionMaxTps((String) apiData.get("productionTps", apiData));
    api.setSandboxMaxTps((String) apiData.get("sandboxTps", apiData));

    if (!"none".equals(inSequence)) {
        api.setInSequence(inSequence);
    }
    if (!"none".equals(outSequence)) {
        api.setOutSequence(outSequence);
    }

    List<String> sequenceList = apiProvider.getCustomFaultSequences(apiId);
    if (!"none".equals(faultSequence) && sequenceList.contains(faultSequence)) {
        api.setFaultSequence(faultSequence);
    }

    Set<Tier> availableTier = new HashSet<Tier>();
    String[] tierNames;
    if (tier != null) {
        tierNames = tier.split(",");
        if (!APIUtil.isAdvanceThrottlingEnabled()) {
            Set<Tier> definedTiers = apiProvider.getTiers();
            for (String tierName : tierNames) {
                boolean isTierValid = false;
                for (Tier definedTier : definedTiers) {
                    if (tierName.equals(definedTier.getName())) {
                        isTierValid = true;
                        break;
                    }
                }

                if (!isTierValid) {
                    handleException("Specified tier " + tierName + " does not exist");
                }
                availableTier.add(new Tier(tierName));
            }
        } else {
            Policy[] definedTiers = apiProvider.getPolicies(provider, PolicyConstants.POLICY_LEVEL_SUB);
            for (String tierName : tierNames) {
                boolean isTierValid = false;
                for (Policy definedTier : definedTiers) {
                    if (tierName.equals(definedTier.getPolicyName())) {
                        isTierValid = true;
                        break;
                    }
                }

                if (!isTierValid) {
                    handleException("Specified tier " + tierName + " does not exist");
                }
                availableTier.add(new Tier(tierName));
            }
        }

        api.addAvailableTiers(availableTier);
    }
    api.setStatus(APIStatus.CREATED);
    api.setContext(context);
    api.setContextTemplate(contextTemplate);
    api.setBusinessOwner(bizOwner);
    api.setBusinessOwnerEmail(bizOwnerEmail);
    api.setTechnicalOwner(techOwner);
    api.setTechnicalOwnerEmail(techOwnerEmail);
    api.setVisibility(visibility);
    api.setVisibleRoles(visibleRoles != null ? visibleRoles.trim() : null);
    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environments));
    CORSConfiguration corsConfiguration = APIUtil.getCorsConfigurationDtoFromJson(corsConfiguraion);
    if (corsConfiguration != null) {
        api.setCorsConfiguration(corsConfiguration);
    }
    String endpointConfig = (String) apiData.get("endpoint_config", apiData);
    if (StringUtils.isEmpty(endpointConfig)) {
        handleException("Endpoint Configuration is missing");
    } else {
        api.setEndpointConfig(endpointConfig);
        //Validate endpoint URI format
        validateEndpointURI(api.getEndpointConfig());
    }
    //set secured endpoint parameters
    if ("secured".equals(endpointSecured)) {
        api.setEndpointSecured(true);
        api.setEndpointUTUsername(endpointUTUsername);
        api.setEndpointUTPassword(endpointUTPassword);
        if ("digestAuth".equals(endpointAuthDigest)) {
            api.setEndpointAuthDigest(true);
        } else {
            api.setEndpointAuthDigest(false);
        }
    }

    checkFileSize(fileHostObject);
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }

        apiProvider.addAPI(api);

        if (fileHostObject != null && fileHostObject.getJavaScriptFile().getLength() != 0) {

            String thumbPath = addThumbIcon(fileHostObject.getInputStream(),
                    fileHostObject.getJavaScriptFile().getContentType(), apiProvider, api);
            apiProvider.updateAPI(api);
        }
        NativeArray externalAPIStores = (NativeArray) apiData.get("externalAPIStores", apiData);
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomain);
        if (externalAPIStores.getLength() != 0) {
            Set<APIStore> apiStores = new HashSet<APIStore>();
            for (int k = 0; k < externalAPIStores.getLength(); k++) {
                String apiStoreName = externalAPIStores.get(k, externalAPIStores).toString();
                apiStores.add(APIUtil.getExternalAPIStore(apiStoreName, tenantId));
            }
            apiProvider.publishToExternalAPIStores(api, apiStores, false);
        }
        success = true;

    } catch (Exception e) {
        handleException("Error while adding the API- " + name + "-" + version, e);
        return false;
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    if (thumbUrl != null && !thumbUrl.isEmpty()) {
        try {
            URL url = new URL(thumbUrl);
            String imageType = url.openConnection().getContentType();
            File fileToUploadFromUrl = new File(ICON_PATH);
            if (!fileToUploadFromUrl.exists()) {
                if (!fileToUploadFromUrl.createNewFile()) {
                    log.error("Unable to create new file under : " + ICON_PATH);
                }
            }
            FileUtils.copyURLToFile(url, fileToUploadFromUrl);
            FileBody fileBody = new FileBody(fileToUploadFromUrl, imageType);

            checkImageSize(fileToUploadFromUrl);

            String thumbPath = addThumbIcon(fileBody.getInputStream(), url.openConnection().getContentType(),
                    apiProvider, api);

        } catch (IOException e) {
            handleException("[Error] Cannot read data from the URL", e);
        }
        apiProvider.updateAPI(api);

    }

    if (apiData.get("swagger", apiData) != null) {
        // Read URI Templates from swagger resource and set to api object
        Set<URITemplate> uriTemplates = definitionFromSwagger20.getURITemplates(api,
                String.valueOf(apiData.get("swagger", apiData)));
        api.setUriTemplates(uriTemplates);

        // scopes
        Set<Scope> scopes = definitionFromSwagger20.getScopes(String.valueOf(apiData.get("swagger", apiData)));
        api.setScopes(scopes);

        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider));
        try {
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            for (URITemplate uriTemplate : uriTemplates) {
                Scope scope = uriTemplate.getScope();
                if (scope != null && !(APIUtil.isWhiteListedScope(scope.getKey()))) {
                    if (apiProvider.isScopeKeyAssigned(apiId, scope.getKey(), tenantId)) {
                        handleException("Scope " + scope.getKey() + " is already assigned by another API");
                    }
                }
            }
        } catch (UserStoreException e) {
            handleException("Error while reading tenant information ", e);
        }

        // Save swagger in the registry
        apiProvider.saveSwagger20Definition(api.getId(), (String) apiData.get("swagger", apiData));
        saveAPI(apiProvider, api, null, false);
    } else {
        String apiDefinitionJSON = definitionFromSwagger20.generateAPIDefinition(api);
        apiProvider.saveSwagger20Definition(api.getId(), apiDefinitionJSON);
    }
    return success;

}

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

public static boolean jsFunction_updateAPI(Context cx, Scriptable thisObj, Object[] args, Function funObj)
        throws APIManagementException, FaultGatewaysException {

    if (args == null || args.length == 0) {
        handleException("Invalid number of input parameters.");
    }/*from  ww  w.j ava2s.  c  o m*/

    NativeObject apiData = (NativeObject) args[0];
    boolean success;
    String provider = String.valueOf(apiData.get("provider", apiData));
    if (provider != null) {
        provider = APIUtil.replaceEmailDomain(provider);
    }
    String name = (String) apiData.get("apiName", apiData);
    String version = (String) apiData.get("version", apiData);
    String defaultVersion = (String) apiData.get("defaultVersion", apiData);
    String description = (String) apiData.get("description", apiData);
    FileHostObject fileHostObject = (FileHostObject) apiData.get("imageUrl", apiData);
    String endpoint = (String) apiData.get("endpoint", apiData);
    String sandboxUrl = (String) apiData.get("sandbox", apiData);
    String techOwner = (String) apiData.get("techOwner", apiData);
    String techOwnerEmail = (String) apiData.get("techOwnerEmail", apiData);
    String bizOwner = (String) apiData.get("bizOwner", apiData);
    String bizOwnerEmail = (String) apiData.get("bizOwnerEmail", apiData);
    String visibility = (String) apiData.get("visibility", apiData);
    String thumbUrl = (String) apiData.get("thumbUrl", apiData);
    String environments = (String) apiData.get("environments", apiData);
    String corsConfiguraion = (String) apiData.get("corsConfiguration", apiData);
    String visibleRoles = "";
    if (visibility != null && visibility.equals(APIConstants.API_RESTRICTED_VISIBILITY)) {
        visibleRoles = (String) apiData.get("visibleRoles", apiData);
    }

    String visibleTenants = "";
    if (visibility != null && visibility.equals(APIConstants.API_CONTROLLED_VISIBILITY)) {
        visibleTenants = (String) apiData.get("visibleTenants", apiData);
    }
    String endpointSecured = (String) apiData.get("endpointSecured", apiData);
    String endpointAuthDigest = (String) apiData.get("endpointAuthDigest", apiData);
    String endpointUTUsername = (String) apiData.get("endpointUTUsername", apiData);
    String endpointUTPassword = (String) apiData.get("endpointUTPassword", apiData);

    String inSequence = (String) apiData.get("inSequence", apiData);
    String outSequence = (String) apiData.get("outSequence", apiData);
    String faultSequence = (String) apiData.get("faultSequence", apiData);

    String responseCache = (String) apiData.get("responseCache", apiData);
    int cacheTimeOut = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
    if (APIConstants.ENABLED.equalsIgnoreCase(responseCache)) {
        responseCache = APIConstants.ENABLED;
        try {
            cacheTimeOut = Integer.parseInt((String) apiData.get("cacheTimeout", apiData));
        } catch (NumberFormatException e) {
            //ignore
        }
    } else {
        responseCache = APIConstants.DISABLED;
    }

    if (sandboxUrl != null && sandboxUrl.trim().length() == 0) {
        sandboxUrl = null;
    }

    if (endpoint != null && endpoint.trim().length() == 0) {
        endpoint = null;
    }

    if (endpoint != null && !endpoint.startsWith("http") && !endpoint.startsWith("https")) {
        endpoint = "http://" + endpoint;
    }
    if (sandboxUrl != null && !sandboxUrl.startsWith("http") && !sandboxUrl.startsWith("https")) {
        sandboxUrl = "http://" + sandboxUrl;
    }

    String redirectURL = (String) apiData.get("redirectURL", apiData);
    boolean advertiseOnly = Boolean.parseBoolean((String) apiData.get("advertiseOnly", apiData));
    String apiOwner = (String) apiData.get("apiOwner", apiData);

    if (apiOwner == null || apiOwner.equals("")) {
        apiOwner = provider;
    }

    String wsdl = (String) apiData.get("wsdl", apiData);
    String wadl = (String) apiData.get("wadl", apiData);
    String subscriptionAvailability = (String) apiData.get("subscriptionAvailability", apiData);
    String subscriptionAvailableTenants = "";
    if (subscriptionAvailability != null
            && subscriptionAvailability.equals(APIConstants.SUBSCRIPTION_TO_SPECIFIC_TENANTS)) {
        subscriptionAvailableTenants = (String) apiData.get("subscriptionTenants", apiData);
    }

    String tags = (String) apiData.get("tags", apiData);
    Set<String> tag = new HashSet<String>();
    if (tags != null) {
        if (tags.contains(",")) {
            String[] userTag = tags.split(",");
            tag.addAll(Arrays.asList(userTag).subList(0, tags.split(",").length));
        } else {
            tag.add(tags);
        }
    }
    provider = (provider != null ? provider.trim() : null);
    name = (name != null ? name.trim() : null);
    version = (version != null ? version.trim() : null);
    APIIdentifier oldApiId = new APIIdentifier(provider, name, version);
    APIProvider apiProvider = getAPIProvider(thisObj);
    boolean isTenantFlowStarted = false;
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider));
    if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        isTenantFlowStarted = true;
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
    }

    API oldApi = apiProvider.getAPI(oldApiId);

    String transport = getTransports(apiData);

    String tier = (String) apiData.get("tier", apiData);
    String apiLevelPolicy = (String) apiData.get("apiPolicy", apiData);
    String contextVal = (String) apiData.get("context", apiData);
    String context = contextVal.startsWith("/") ? contextVal : ("/" + contextVal);
    String providerDomain = MultitenantUtils.getTenantDomain(String.valueOf(apiData.get("provider", apiData)));
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain)
            && !context.contains("/t/" + providerDomain)) {
        //Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }

    // This is to support the new Pluggable version strategy
    // if the context does not contain any {version} segment, we use the default version strategy.
    context = checkAndSetVersionParam(context);

    String contextTemplate = context;
    context = updateContextWithVersion(version, contextVal, context);

    APIIdentifier apiId = new APIIdentifier(provider, name, version);
    API api = new API(apiId);

    // to keep the backword compatibility if swagger not set process from
    // resource_config or old way.
    if (apiData.get("swagger", apiData) == null) {
        if (apiData.get("resource_config", apiData) != null) {
            Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
            JSONParser parser = new JSONParser();
            JSONObject resourceConfig = null;
            try {
                resourceConfig = (JSONObject) parser.parse((String) apiData.get("resource_config", apiData));
            } catch (ParseException e) {
                handleException("Invalid resource config", e);
            } catch (ClassCastException e) {
                handleException("Unable to create JSON object from resource config", e);
            }

            //process scopes
            JSONArray scopes = (JSONArray) resourceConfig.get("scopes");
            Set<Scope> scopeList = new LinkedHashSet<Scope>();
            for (int i = 0; i < scopes.size(); i++) {
                Map scope = (Map) scopes.get(i); //access with get() method
                Scope scopeObj = new Scope();
                scopeObj.setKey((String) scope.get("key"));
                scopeObj.setName((String) scope.get("name"));
                scopeObj.setRoles((String) scope.get("roles"));
                scopeObj.setDescription((String) scope.get("description"));
                scopeList.add(scopeObj);
            }
            api.setScopes(scopeList);

            JSONArray resources = (JSONArray) resourceConfig.get("resources");
            for (int k = 0; k < resources.size(); k++) {
                JSONObject resource = (JSONObject) resources.get(k);

                Map http_verbs = (Map) resource.get("http_verbs");
                Iterator iterator = http_verbs.entrySet().iterator();

                while (iterator.hasNext()) {
                    Map.Entry mapEntry = (Map.Entry) iterator.next();
                    Map mapEntryValue = (Map) mapEntry.getValue();

                    URITemplate template = new URITemplate();
                    String uriTempVal = (String) resource.get("url_pattern");
                    uriTempVal = uriTempVal.startsWith("/") ? uriTempVal : ("/" + uriTempVal);
                    template.setUriTemplate(uriTempVal);
                    template.setHTTPVerb((String) mapEntry.getKey());
                    String authType = (String) mapEntryValue.get("auth_type");
                    if (authType.equals("Application & Application User")) {
                        authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                    }
                    if (authType.equals("Application User")) {
                        authType = "Application_User";
                    }
                    if (authType.equals("Application")) {
                        authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN;
                    }
                    template.setThrottlingTier((String) mapEntryValue.get("throttling_tier"));
                    template.setAuthType(authType);
                    template.setResourceURI(endpoint);
                    template.setResourceSandboxURI(sandboxUrl);
                    Scope scope = APIUtil.findScopeByKey(scopeList, (String) mapEntryValue.get("scope"));
                    template.setScope(scope);
                    uriTemplates.add(template);
                }
            }
            //todo handle casting exceptions
            api.setUriTemplates(uriTemplates);
            //todo clean out the code.
        } else {
            //following is the old fashioned way of processing resources
            NativeArray uriMethodArr = (NativeArray) apiData.get("uriMethodArr", apiData);
            NativeArray authTypeArr = (NativeArray) apiData.get("uriAuthMethodArr", apiData);
            NativeArray throttlingTierArr = (NativeArray) apiData.get("throttlingTierArr", apiData);
            NativeArray uriTemplateArr = (NativeArray) apiData.get("uriTemplateArr", apiData);
            if (uriTemplateArr != null && uriMethodArr != null && authTypeArr != null) {
                if (uriTemplateArr.getLength() == uriMethodArr.getLength()) {
                    Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
                    for (int i = 0; i < uriTemplateArr.getLength(); i++) {
                        String uriMethods = (String) uriMethodArr.get(i, uriMethodArr);
                        String uriMethodsAuthTypes = (String) authTypeArr.get(i, authTypeArr);
                        String[] uriMethodArray = uriMethods.split(",");
                        String[] authTypeArray = uriMethodsAuthTypes.split(",");
                        String uriMethodsThrottlingTiers = (String) throttlingTierArr.get(i, throttlingTierArr);
                        String[] throttlingTierArray = uriMethodsThrottlingTiers.split(",");
                        for (int k = 0; k < uriMethodArray.length; k++) {
                            for (int j = 0; j < authTypeArray.length; j++) {
                                if (j == k) {
                                    URITemplate template = new URITemplate();
                                    String uriTemp = (String) uriTemplateArr.get(i, uriTemplateArr);
                                    String uriTempVal = uriTemp.startsWith("/") ? uriTemp : ("/" + uriTemp);
                                    template.setUriTemplate(uriTempVal);
                                    String throttlingTier = throttlingTierArray[j];
                                    template.setHTTPVerb(uriMethodArray[k]);
                                    String authType = authTypeArray[j];
                                    if (authType.equals("Application & Application User")) {
                                        authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                                    }
                                    if (authType.equals("Application User")) {
                                        authType = "Application_User";
                                    }
                                    if (authType.equals("Application")) {
                                        authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN;
                                    }
                                    template.setThrottlingTier(throttlingTier);
                                    template.setAuthType(authType);
                                    template.setResourceURI(endpoint);
                                    template.setResourceSandboxURI(sandboxUrl);

                                    uriTemplates.add(template);
                                    break;
                                }

                            }
                        }

                    }
                    api.setUriTemplates(uriTemplates);
                }
            }
        }
    }

    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environments));
    CORSConfiguration corsConfiguration = APIUtil.getCorsConfigurationDtoFromJson(corsConfiguraion);
    if (corsConfiguration != null) {
        api.setCorsConfiguration(corsConfiguration);
    }
    api.setDescription(StringEscapeUtils.escapeHtml(description));
    api.setLastUpdated(new Date());
    api.setUrl(endpoint);
    api.setSandboxUrl(sandboxUrl);
    api.addTags(tag);
    api.setContext(context);
    api.setContextTemplate(contextTemplate);
    api.setVisibility(visibility);
    api.setVisibleRoles(visibleRoles != null ? visibleRoles.trim() : null);
    api.setVisibleTenants(visibleTenants != null ? visibleTenants.trim() : null);
    Set<Tier> availableTier = new HashSet<Tier>();
    if (tier != null) {
        String[] tierNames = tier.split(",");
        for (String tierName : tierNames) {
            availableTier.add(new Tier(tierName));
        }
        api.addAvailableTiers(availableTier);
    }

    if (apiLevelPolicy != null) {
        if ("none".equals(apiLevelPolicy)) {
            api.setApiLevelPolicy(null);
        } else {
            api.setApiLevelPolicy(apiLevelPolicy);
        }
    }

    api.setStatus(oldApi.getStatus());
    api.setWsdlUrl(wsdl);
    api.setWadlUrl(wadl);
    api.setLastUpdated(new Date());
    api.setBusinessOwner(bizOwner);
    api.setBusinessOwnerEmail(bizOwnerEmail);
    api.setTechnicalOwner(techOwner);
    api.setTechnicalOwnerEmail(techOwnerEmail);
    api.setTransports(transport);
    if (!"none".equals(inSequence)) {
        api.setInSequence(inSequence);
    }
    if (!"none".equals(outSequence)) {
        api.setOutSequence(outSequence);
    }

    List<String> sequenceList = apiProvider.getCustomFaultSequences(apiId);
    if (!"none".equals(faultSequence) && sequenceList.contains(faultSequence)) {
        api.setFaultSequence(faultSequence);
    }
    api.setOldInSequence(oldApi.getInSequence());
    api.setOldOutSequence(oldApi.getOutSequence());
    api.setOldFaultSequence(oldApi.getFaultSequence());
    api.setRedirectURL(redirectURL);
    api.setApiOwner(apiOwner);
    api.setAdvertiseOnly(advertiseOnly);

    // @todo needs to be validated
    api.setEndpointConfig((String) apiData.get("endpoint_config", apiData));
    //Validate endpoint URI format
    validateEndpointURI(api.getEndpointConfig());

    api.setProductionMaxTps((String) apiData.get("productionTps", apiData));
    api.setSandboxMaxTps((String) apiData.get("sandboxTps", apiData));

    api.setSubscriptionAvailability(subscriptionAvailability);
    api.setSubscriptionAvailableTenants(subscriptionAvailableTenants);
    api.setResponseCache(responseCache);
    api.setCacheTimeout(cacheTimeOut);
    api.setAsDefaultVersion("default_version".equals(defaultVersion));
    //set secured endpoint parameters
    if ("secured".equals(endpointSecured)) {
        api.setEndpointSecured(true);
        api.setEndpointUTUsername(endpointUTUsername);
        api.setEndpointUTPassword(endpointUTPassword);
        if ("digestAuth".equals(endpointAuthDigest)) {
            api.setEndpointAuthDigest(true);
        } else {
            api.setEndpointAuthDigest(false);
        }
    }

    try {
        checkFileSize(fileHostObject);

        if (fileHostObject != null && fileHostObject.getJavaScriptFile().getLength() != 0) {

            String thumbPath = addThumbIcon(fileHostObject.getInputStream(),
                    fileHostObject.getJavaScriptFile().getContentType(), apiProvider, api);

        } else if (oldApi.getThumbnailUrl() != null) {
            // retain the previously uploaded image
            api.setThumbnailUrl(oldApi.getThumbnailUrl());
        }

        if (thumbUrl != null && !thumbUrl.isEmpty()) {
            try {
                URL url = new URL(thumbUrl);
                String imageType = url.openConnection().getContentType();

                File fileToUploadFromUrl = new File("tmp/icon");
                if (!fileToUploadFromUrl.exists()) {
                    if (!fileToUploadFromUrl.createNewFile()) {
                        log.error("Unable to create new file under tmp/icon");
                    }
                }
                FileUtils.copyURLToFile(url, fileToUploadFromUrl);
                FileBody fileBody = new FileBody(fileToUploadFromUrl, imageType);

                checkImageSize(fileToUploadFromUrl);

                String thumbPath = addThumbIcon(fileBody.getInputStream(),
                        url.openConnection().getContentType(), apiProvider, api);

            } catch (IOException e) {
                handleException("[Error] Cannot read data from the URL", e);
            }
        }

        if (apiData.get("swagger", apiData) != null) {
            // Read URI Templates from swagger resource and set to api object
            Set<URITemplate> uriTemplates = definitionFromSwagger20.getURITemplates(api,
                    String.valueOf(apiData.get("swagger", apiData)));
            api.setUriTemplates(uriTemplates);

            // scopes
            Set<Scope> scopes = definitionFromSwagger20
                    .getScopes(String.valueOf(apiData.get("swagger", apiData)));
            api.setScopes(scopes);

            try {
                int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                        .getTenantId(tenantDomain);
                for (URITemplate uriTemplate : uriTemplates) {
                    Scope scope = uriTemplate.getScope();
                    if (scope != null && !(APIUtil.isWhiteListedScope(scope.getKey()))) {
                        if (apiProvider.isScopeKeyAssigned(apiId, scope.getKey(), tenantId)) {
                            handleException("Scope " + scope.getKey() + " is already assigned by another API");
                        }
                    }
                }
            } catch (UserStoreException e) {
                handleException("Error while reading tenant information ", e);
            }

            // Save swagger in the registry
            apiProvider.saveSwagger20Definition(api.getId(), (String) apiData.get("swagger", apiData));
            saveAPI(apiProvider, api, null, false);
        } else {
            String apiDefinitionJSON = definitionFromSwagger20.generateAPIDefinition(api);
            apiProvider.saveSwagger20Definition(api.getId(), apiDefinitionJSON);
            apiProvider.updateAPI(api);
        }

        success = true;
    } catch (Exception e) {
        handleException("Error while updating the API- " + name + "-" + version, e);
        return false;
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    return success;
}