Search in sources :

Example 61 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAPIResourcePolicies.

/**
 * Get the resource policies(inflow/outflow).
 *
 * @param apiId           API ID
 * @param sequenceType    sequence type('in' or 'out')
 * @param resourcePath    api resource path
 * @param verb            http verb
 * @param ifNoneMatch     If-None-Match header value
 * @return json response of the resource policies according to the resource path
 */
@Override
public Response getAPIResourcePolicies(String apiId, String sequenceType, String resourcePath, String verb, String ifNoneMatch, MessageContext messageContext) {
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider provider = RestApiCommonUtil.getLoggedInUserProvider();
        API api = provider.getLightweightAPIByUUID(apiId, organization);
        if (APIConstants.API_TYPE_SOAPTOREST.equals(api.getType())) {
            if (StringUtils.isEmpty(sequenceType) || !(RestApiConstants.IN_SEQUENCE.equals(sequenceType) || RestApiConstants.OUT_SEQUENCE.equals(sequenceType))) {
                String errorMessage = "Sequence type should be either of the values from 'in' or 'out'";
                RestApiUtil.handleBadRequest(errorMessage, log);
            }
            String resourcePolicy = SequenceUtils.getRestToSoapConvertedSequence(api, sequenceType);
            if (StringUtils.isEmpty(resourcePath) && StringUtils.isEmpty(verb)) {
                ResourcePolicyListDTO resourcePolicyListDTO = APIMappingUtil.fromResourcePolicyStrToDTO(resourcePolicy);
                return Response.ok().entity(resourcePolicyListDTO).build();
            }
            if (StringUtils.isNotEmpty(resourcePath) && StringUtils.isNotEmpty(verb)) {
                JSONObject sequenceObj = (JSONObject) new JSONParser().parse(resourcePolicy);
                JSONObject resultJson = new JSONObject();
                String key = resourcePath + "_" + verb;
                JSONObject sequenceContent = (JSONObject) sequenceObj.get(key);
                if (sequenceContent == null) {
                    String errorMessage = "Cannot find any resource policy for Resource path : " + resourcePath + " with type: " + verb;
                    RestApiUtil.handleResourceNotFoundError(errorMessage, log);
                }
                resultJson.put(key, sequenceObj.get(key));
                ResourcePolicyListDTO resourcePolicyListDTO = APIMappingUtil.fromResourcePolicyStrToDTO(resultJson.toJSONString());
                return Response.ok().entity(resourcePolicyListDTO).build();
            } else if (StringUtils.isEmpty(resourcePath)) {
                String errorMessage = "Resource path cannot be empty for the defined verb: " + verb;
                RestApiUtil.handleBadRequest(errorMessage, log);
            } else if (StringUtils.isEmpty(verb)) {
                String errorMessage = "HTTP verb cannot be empty for the defined resource path: " + resourcePath;
                RestApiUtil.handleBadRequest(errorMessage, log);
            }
        } else {
            String errorMessage = "The provided api with id: " + apiId + " is not a soap to rest converted api.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving the API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (ParseException e) {
        String errorMessage = "Error while retrieving the resource policies for the API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) ResourcePolicyListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ResourcePolicyListDTO)

Example 62 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class AbstractAPIManagerTestCase method testUpdateWsdl.

@Test
public void testUpdateWsdl() throws APIManagementException, RegistryException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Resource resource = new ResourceImpl();
    String resourcePath = "/test/wsdl";
    String wsdlContent = "sample wsdl";
    Mockito.when(registry.get(resourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
    try {
        abstractAPIManager.updateWsdl(resourcePath, wsdlContent);
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while updating the existing wsdl"));
    }
    try {
        abstractAPIManager.updateWsdl(resourcePath, wsdlContent);
    } catch (APIManagementException e) {
        Assert.fail("Error while updating wsdl");
    }
}
Also used : ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 63 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class AbstractAPIManagerTestCase method testDeleteApiSpecificMediationPolicy.

@Test
public void testDeleteApiSpecificMediationPolicy() throws RegistryException, APIManagementException {
    String resourcePath = "config/mediation/";
    Identifier identifier = Mockito.mock(Identifier.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapperExtended(null, null, registry, null);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true, false, true, false);
    Mockito.doThrow(RegistryException.class).doNothing().when(registry).delete(Mockito.anyString());
    try {
        abstractAPIManager.deleteApiSpecificMediationPolicy(identifier, resourcePath, SAMPLE_RESOURCE_ID);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to delete specific mediation policy"));
    }
    Assert.assertFalse(abstractAPIManager.deleteApiSpecificMediationPolicy(identifier, resourcePath, SAMPLE_RESOURCE_ID));
    Assert.assertTrue(abstractAPIManager.deleteApiSpecificMediationPolicy(identifier, resourcePath, SAMPLE_RESOURCE_ID));
}
Also used : APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 64 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class SOAPOperationBindingUtils method populateSoapOperationParameters.

/**
 * gets parameters from the soap operation and populates them in {@link WSDLSOAPOperation}
 *
 * @param soapOperations soap binding operations
 */
private static void populateSoapOperationParameters(Set<WSDLSOAPOperation> soapOperations) {
    String[] primitiveTypes = { "string", "byte", "short", "int", "long", "float", "double", "boolean" };
    List primitiveTypeList = Arrays.asList(primitiveTypes);
    if (soapOperations != null) {
        for (WSDLSOAPOperation operation : soapOperations) {
            String resourcePath;
            String operationName = operation.getName();
            operation.setSoapBindingOpName(operationName);
            operation.setHttpVerb(HTTPConstants.HTTP_METHOD_POST);
            if (operationName.toLowerCase().startsWith("get") && operation.getInputParameterModel() != null && operation.getInputParameterModel().size() <= 1) {
                Map<String, Property> properties = null;
                if (operation.getInputParameterModel().size() > 0 && operation.getInputParameterModel().get(0) != null) {
                    properties = operation.getInputParameterModel().get(0).getProperties();
                }
                if (properties == null) {
                    operation.setHttpVerb(HTTPConstants.HTTP_METHOD_GET);
                } else if (properties.size() <= 1) {
                    for (String property : properties.keySet()) {
                        String type = properties.get(property).getType();
                        if (!(type.equals(ObjectProperty.TYPE) || type.equals(ArrayProperty.TYPE) || type.equals(RefProperty.TYPE))) {
                            operation.setHttpVerb(HTTPConstants.HTTP_METHOD_GET);
                        }
                    }
                }
            }
            resourcePath = operationName;
            resourcePath = resourcePath.substring(0, 1).toLowerCase() + resourcePath.substring(1, resourcePath.length());
            operation.setName(resourcePath);
            if (log.isDebugEnabled()) {
                log.debug("REST resource path for SOAP operation: " + operationName + " is: " + resourcePath);
            }
            List<WSDLOperationParam> params = operation.getParameters();
            if (log.isDebugEnabled() && params != null) {
                log.debug("SOAP operation: " + operationName + " has " + params.size() + " parameters");
            }
            if (params != null) {
                for (WSDLOperationParam param : params) {
                    if (param.getDataType() != null) {
                        String dataTypeWithNS = param.getDataType();
                        String dataType = dataTypeWithNS.substring(dataTypeWithNS.indexOf(":") + 1);
                        param.setDataType(dataType);
                        if (!primitiveTypeList.contains(dataType)) {
                            param.setComplexType(true);
                        }
                    }
                }
            }
        }
    } else {
        log.info("No SOAP operations found in the WSDL");
    }
}
Also used : WSDLOperationParam(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLOperationParam) AbstractList(java.util.AbstractList) List(java.util.List) NodeList(org.w3c.dom.NodeList) WSDLSOAPOperation(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLSOAPOperation) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) RefProperty(io.swagger.models.properties.RefProperty) ObjectProperty(io.swagger.models.properties.ObjectProperty)

Example 65 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class SequenceUtils method updateResourcePolicyFromRegistryResourceId.

/**
 * Updates resource policy resource for the given resource id from the registry.
 *
 * @param identifier API identifier
 * @param resourceId Resource identifier
 * @param content    resource policy content
 * @throws APIManagementException
 */
public static void updateResourcePolicyFromRegistryResourceId(APIIdentifier identifier, String resourceId, String content) throws APIManagementException {
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        APIUtil.loadTenantRegistry(tenantId);
        UserRegistry registry = registryService.getGovernanceSystemRegistry(tenantId);
        String resourcePath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + SOAPToRESTConstants.SOAP_TO_REST_RESOURCE;
        Collection collection = (Collection) registry.get(resourcePath);
        String[] resources = collection.getChildren();
        if (resources == null) {
            handleException("Cannot find any resource policies at the path: " + resourcePath);
        }
        for (String path : resources) {
            Collection resourcePolicyCollection = (Collection) registry.get(path);
            String[] resourcePolicies = resourcePolicyCollection.getChildren();
            if (resourcePolicies == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Cannot find resource policies under path: " + path);
                }
                continue;
            }
            for (String resourcePolicyPath : resourcePolicies) {
                Resource resource = registry.get(resourcePolicyPath);
                if (StringUtils.isNotEmpty(resourceId) && resourceId.equals(((ResourceImpl) resource).getUUID())) {
                    resource.setContent(content);
                    resource.setMediaType(SOAPToRESTConstants.TEXT_XML);
                    registry.put(resourcePolicyPath, resource);
                    break;
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Number of REST resources for " + resourcePath + " is: " + resources.length);
        }
    } catch (UserStoreException e) {
        handleException("Error while reading tenant information", e);
    } catch (RegistryException e) {
        handleException("Error when create registry instance", e);
    } catch (org.wso2.carbon.registry.api.RegistryException e) {
        handleException("Error while setting the resource policy content for the registry resource", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : Resource(org.wso2.carbon.registry.api.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Collection(org.wso2.carbon.registry.core.Collection) RegistryService(org.wso2.carbon.registry.core.service.RegistryService)

Aggregations

Resource (org.wso2.carbon.registry.core.Resource)51 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)48 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)44 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)28 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)25 IOException (java.io.IOException)18 Registry (org.wso2.carbon.registry.core.Registry)16 Collection (org.wso2.carbon.registry.core.Collection)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 Test (org.junit.Test)13 Resource (org.wso2.carbon.registry.api.Resource)13 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 ArrayList (java.util.ArrayList)11 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)11 RegistryException (org.wso2.carbon.registry.api.RegistryException)11 ResourceImpl (org.wso2.carbon.registry.core.ResourceImpl)11 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)11 JSONParser (org.json.simple.parser.JSONParser)10 ParseException (org.json.simple.parser.ParseException)10 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)10