Search in sources :

Example 11 with ResourceNotFoundException

use of org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException in project carbon-apimgt by wso2.

the class GatewaySourceGeneratorImpl method getEndpointConfigStringFromTemplate.

@Override
public String getEndpointConfigStringFromTemplate(Endpoint endpoint) throws APITemplateException {
    StringWriter writer = new StringWriter();
    String templatePath = "resources" + File.separator + "template" + File.separator + "endpoint.xml";
    try {
        // build the context for template and apply the necessary decorators
        ConfigContext configcontext = new EndpointContext(endpoint, packageName);
        VelocityContext context = configcontext.getContext();
        VelocityEngine velocityengine = new VelocityEngine();
        velocityengine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityengine.init();
        Template template = velocityengine.getTemplate(templatePath);
        template.merge(context, writer);
    } catch (ResourceNotFoundException e) {
        log.error("Template " + templatePath + " not Found", e);
        throw new APITemplateException("Template " + templatePath + " not Found", ExceptionCodes.TEMPLATE_EXCEPTION);
    } catch (ParseErrorException e) {
        log.error("Syntax error in " + templatePath, e);
        throw new APITemplateException("Syntax error in " + templatePath, ExceptionCodes.TEMPLATE_EXCEPTION);
    }
    return writer.toString();
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) StringWriter(java.io.StringWriter) EndpointContext(org.wso2.carbon.apimgt.core.template.EndpointContext) VelocityContext(org.apache.velocity.VelocityContext) ParseErrorException(org.apache.velocity.exception.ParseErrorException) ClasspathResourceLoader(org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader) APITemplateException(org.wso2.carbon.apimgt.core.template.APITemplateException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) CompositeAPIConfigContext(org.wso2.carbon.apimgt.core.template.CompositeAPIConfigContext) ConfigContext(org.wso2.carbon.apimgt.core.template.ConfigContext) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext) ResourceConfigContext(org.wso2.carbon.apimgt.core.template.ResourceConfigContext) Template(org.apache.velocity.Template)

Example 12 with ResourceNotFoundException

use of org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException in project carbon-apimgt by wso2.

the class InboundWebSocketProcessor method setMatchingResource.

/**
 * Get matching resource for invoking handshake request.
 *
 * @param ctx                   Channel context
 * @param req                   Handshake request
 * @param inboundMessageContext InboundMessageContext
 * @throws WebSocketApiException     If an error occurs
 * @throws ResourceNotFoundException If no matching API or resource found
 */
private void setMatchingResource(ChannelHandlerContext ctx, FullHttpRequest req, InboundMessageContext inboundMessageContext) throws WebSocketApiException, ResourceNotFoundException {
    String matchingResource;
    try {
        MessageContext synCtx = getMessageContext(inboundMessageContext);
        API api = InboundWebsocketProcessorUtil.getApi(synCtx, inboundMessageContext);
        if (api == null) {
            throw new ResourceNotFoundException("No matching API found to dispatch the request");
        }
        inboundMessageContext.setApi(api);
        reConstructFullUriWithVersion(req, synCtx, inboundMessageContext);
        inboundMessageContext.setApiContext(api.getContext());
        Resource selectedResource = null;
        Utils.setSubRequestPath(api, synCtx);
        Set<Resource> acceptableResources = new LinkedHashSet<>(Arrays.asList(api.getResources()));
        if (!acceptableResources.isEmpty()) {
            for (RESTDispatcher dispatcher : ApiUtils.getDispatchers()) {
                Resource resource = dispatcher.findResource(synCtx, acceptableResources);
                if (resource != null) {
                    selectedResource = resource;
                    if (APIUtil.isAnalyticsEnabled()) {
                        WebSocketUtils.setApiPropertyToChannel(ctx, APIMgtGatewayConstants.SYNAPSE_ENDPOINT_ADDRESS, WebSocketUtils.getEndpointUrl(resource, synCtx));
                    }
                    break;
                }
            }
        }
        setApiPropertiesToChannel(ctx, inboundMessageContext);
        if (selectedResource == null) {
            throw new ResourceNotFoundException("No matching resource found to dispatch the request");
        }
        if (APIConstants.GRAPHQL_API.equals(inboundMessageContext.getElectedAPI().getApiType())) {
            inboundMessageContext.setGraphQLSchemaDTO(DataHolder.getInstance().getGraphQLSchemaDTOForAPI(inboundMessageContext.getElectedAPI().getUuid()));
        }
        matchingResource = selectedResource.getDispatcherHelper().getString();
        if (log.isDebugEnabled()) {
            log.info("Selected resource for API dispatch : " + matchingResource);
        }
    } catch (AxisFault | URISyntaxException e) {
        throw new WebSocketApiException("Error while getting matching resource for Websocket API");
    }
    inboundMessageContext.setMatchingResource(matchingResource);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) AxisFault(org.apache.axis2.AxisFault) RESTDispatcher(org.apache.synapse.api.dispatch.RESTDispatcher) WebSocketApiException(org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketApiException) Resource(org.apache.synapse.api.Resource) API(org.apache.synapse.api.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) URISyntaxException(java.net.URISyntaxException) ResourceNotFoundException(org.wso2.carbon.apimgt.gateway.handlers.security.ResourceNotFoundException)

Example 13 with ResourceNotFoundException

use of org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException in project carbon-apimgt by wso2.

the class APIKeyValidator method getResourceAuthenticationScheme.

@MethodStats
public String getResourceAuthenticationScheme(MessageContext synCtx) throws APISecurityException {
    String authType = "";
    List<VerbInfoDTO> verbInfoList;
    try {
        verbInfoList = findMatchingVerb(synCtx);
        if (verbInfoList != null && verbInfoList.toArray().length > 0) {
            for (VerbInfoDTO verb : verbInfoList) {
                authType = verb.getAuthType();
                if (authType == null || !StringUtils.capitalize(APIConstants.AUTH_TYPE_NONE.toLowerCase()).equals(authType)) {
                    authType = StringUtils.capitalize(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN.toLowerCase());
                    break;
                }
            }
            synCtx.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
        }
    } catch (ResourceNotFoundException e) {
        log.error("Could not find matching resource for request", e);
        return APIConstants.NO_MATCHING_AUTH_SCHEME;
    }
    if (!authType.isEmpty()) {
        return authType;
    } else {
        // No matching resource found. return the highest level of security
        return APIConstants.NO_MATCHING_AUTH_SCHEME;
    }
}
Also used : VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 14 with ResourceNotFoundException

use of org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException in project carbon-apimgt by wso2.

the class APIKeyValidator method findMatchingVerb.

public List<VerbInfoDTO> findMatchingVerb(MessageContext synCtx) throws ResourceNotFoundException, APISecurityException {
    List<VerbInfoDTO> verbInfoList = new ArrayList<>();
    String resourceCacheKey;
    String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String fullRequestPath = (String) synCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
    String electedResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    ArrayList<String> resourceArray = null;
    if (electedResource != null) {
        if (APIConstants.GRAPHQL_API.equalsIgnoreCase((String) synCtx.getProperty(APIConstants.API_TYPE))) {
            resourceArray = new ArrayList<>(Arrays.asList(electedResource.split(",")));
        } else {
            resourceArray = new ArrayList<>(Arrays.asList(electedResource));
        }
    }
    String requestPath = getRequestPath(synCtx, apiContext, apiVersion, fullRequestPath);
    if ("".equals(requestPath)) {
        requestPath = "/";
    }
    if (log.isDebugEnabled()) {
        log.debug("Setting REST_SUB_REQUEST_PATH in msg context: " + requestPath);
    }
    synCtx.setProperty(RESTConstants.REST_SUB_REQUEST_PATH, requestPath);
    // verb has been put into the cache.
    if (resourceArray != null) {
        for (String resourceString : resourceArray) {
            VerbInfoDTO verbInfo;
            if (isGatewayAPIResourceValidationEnabled) {
                String apiCacheKey = APIUtil.getAPIInfoDTOCacheKey(apiContext, apiVersion);
                if (!getResourceCache().containsKey(apiCacheKey)) {
                    break;
                }
                resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, resourceString, httpMethod);
                verbInfo = (VerbInfoDTO) getResourceCache().get(resourceCacheKey);
                // Cache hit
                if (verbInfo != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Found resource in Cache for key: " + resourceCacheKey);
                    }
                    verbInfoList.add(verbInfo);
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Resource not found in cache for key: " + resourceCacheKey);
                    }
                }
            }
        }
        if (resourceArray.size() == verbInfoList.size()) {
            return verbInfoList;
        }
    } else {
        API selectedApi = Utils.getSelectedAPI(synCtx);
        Resource selectedResource = null;
        String resourceString;
        if (selectedApi != null) {
            Resource[] selectedAPIResources = selectedApi.getResources();
            Set<Resource> acceptableResources = new LinkedHashSet<Resource>();
            for (Resource resource : selectedAPIResources) {
                // If the requesting method is OPTIONS or if the Resource contains the requesting method
                if (RESTConstants.METHOD_OPTIONS.equals(httpMethod) || (resource.getMethods() != null && Arrays.asList(resource.getMethods()).contains(httpMethod))) {
                    acceptableResources.add(resource);
                }
            }
            if (acceptableResources.size() > 0) {
                for (RESTDispatcher dispatcher : RESTUtils.getDispatchers()) {
                    Resource resource = dispatcher.findResource(synCtx, acceptableResources);
                    if (resource != null && Arrays.asList(resource.getMethods()).contains(httpMethod)) {
                        selectedResource = resource;
                        break;
                    }
                }
            }
        }
        if (selectedResource == null) {
            // No matching resource found.
            String msg = "Could not find matching resource for " + requestPath;
            log.error(msg);
            throw new ResourceNotFoundException(msg);
        }
        resourceString = selectedResource.getDispatcherHelper().getString();
        resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, resourceString, httpMethod);
        if (log.isDebugEnabled()) {
            log.debug("Selected Resource: " + resourceString);
        }
        // Set the elected resource
        synCtx.setProperty(APIConstants.API_ELECTED_RESOURCE, resourceString);
        if (isGatewayAPIResourceValidationEnabled) {
            VerbInfoDTO verbInfo;
            verbInfo = (VerbInfoDTO) getResourceCache().get(resourceCacheKey);
            // Cache hit
            if (verbInfo != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Got Resource from cache for key: " + resourceCacheKey);
                }
                verbInfoList.add(verbInfo);
                return verbInfoList;
            } else if (log.isDebugEnabled()) {
                log.debug("Cache miss for Resource for key: " + resourceCacheKey);
            }
        }
    }
    String apiCacheKey = APIUtil.getAPIInfoDTOCacheKey(apiContext, apiVersion);
    APIInfoDTO apiInfoDTO = null;
    if (isGatewayAPIResourceValidationEnabled) {
        apiInfoDTO = (APIInfoDTO) getResourceCache().get(apiCacheKey);
    }
    // Cache miss
    if (apiInfoDTO == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find API object in cache for key: " + apiCacheKey);
        }
        String apiType = (String) synCtx.getProperty(APIMgtGatewayConstants.API_TYPE);
        if (APIConstants.ApiTypes.PRODUCT_API.name().equalsIgnoreCase(apiType)) {
            apiInfoDTO = doGetAPIProductInfo(synCtx, apiContext, apiVersion);
        } else {
            apiInfoDTO = doGetAPIInfo(synCtx, apiContext, apiVersion);
        }
        if (isGatewayAPIResourceValidationEnabled) {
            getResourceCache().put(apiCacheKey, apiInfoDTO);
        }
    }
    if (apiInfoDTO.getResources() != null) {
        for (ResourceInfoDTO resourceInfoDTO : apiInfoDTO.getResources()) {
            Set<VerbInfoDTO> verbDTOList = resourceInfoDTO.getHttpVerbs();
            for (VerbInfoDTO verb : verbDTOList) {
                if (verb.getHttpVerb().equals(httpMethod)) {
                    for (String resourceString : resourceArray) {
                        if (isResourcePathMatching(resourceString, resourceInfoDTO)) {
                            resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, resourceString, httpMethod);
                            verb.setRequestKey(resourceCacheKey);
                            verbInfoList.add(verb);
                            if (isGatewayAPIResourceValidationEnabled) {
                                // Set cache key in the message c\ontext so that it can be used by the subsequent handlers.
                                if (log.isDebugEnabled()) {
                                    log.debug("Putting resource object in cache with key: " + resourceCacheKey);
                                }
                                getResourceCache().put(resourceCacheKey, verb);
                                synCtx.setProperty(APIConstants.API_RESOURCE_CACHE_KEY, resourceCacheKey);
                            }
                        }
                    }
                }
            }
        }
    }
    if (verbInfoList.size() == 0) {
        verbInfoList = null;
    }
    return verbInfoList;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) Resource(org.apache.synapse.api.Resource) RESTDispatcher(org.apache.synapse.api.dispatch.RESTDispatcher) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) API(org.apache.synapse.api.API) APIInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIInfoDTO) ResourceInfoDTO(org.wso2.carbon.apimgt.impl.dto.ResourceInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 15 with ResourceNotFoundException

use of org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException in project carbon-apimgt by wso2.

the class RestApiUtilTest method testisDueToAuthorizationFailureWithInvalidException.

@Test
public void testisDueToAuthorizationFailureWithInvalidException() throws Exception {
    ResourceNotFoundException sampleResourceNotFoundException = new ResourceNotFoundException("New Sample exception");
    Throwable testThrowable = new Throwable();
    PowerMockito.spy(RestApiUtil.class);
    PowerMockito.doReturn(sampleResourceNotFoundException).when(RestApiUtil.class, "getPossibleErrorCause", testThrowable);
    Assert.assertFalse("Invalid exception has been passed.", RestApiUtil.isDueToAuthorizationFailure(testThrowable));
}
Also used : ResourceNotFoundException(org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 API (org.apache.synapse.api.API)6 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)6 MessageContext (org.apache.synapse.MessageContext)5 Resource (org.apache.synapse.api.Resource)5 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)5 Cache (javax.cache.Cache)4 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)4 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)4 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)4 APIManagerConfigurationService (org.wso2.carbon.apimgt.impl.APIManagerConfigurationService)4 CacheProvider (org.wso2.carbon.apimgt.impl.caching.CacheProvider)4 ResourceNotFoundException (org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException)4 StringWriter (java.io.StringWriter)3 ArrayList (java.util.ArrayList)3 Template (org.apache.velocity.Template)3 VelocityContext (org.apache.velocity.VelocityContext)3 VelocityEngine (org.apache.velocity.app.VelocityEngine)3 ParseErrorException (org.apache.velocity.exception.ParseErrorException)3