org.wso2.carbon.apimgt.api.APIManagementException Java Examples

The following examples show how to use org.wso2.carbon.apimgt.api.APIManagementException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsAPIAvailable() throws RegistryException, APIManagementException {
    APIIdentifier apiIdentifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String path =
            APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getProviderName()
                    + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getApiName()
                    + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    Mockito.when(registry.resourceExists(path)).thenThrow(RegistryException.class).thenReturn(true);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    try {
        abstractAPIManager.isAPIAvailable(apiIdentifier);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to check availability of api"));
    }
    Assert.assertTrue(abstractAPIManager.isAPIAvailable(apiIdentifier));
}
 
Example #2
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetWsdl() throws APIManagementException, RegistryException, IOException {
    Resource resourceMock = Mockito.mock(Resource.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String wsdlName =
            identifier.getProviderName() + "--" + identifier.getApiName() + identifier.getVersion() + ".wsdl";
    String wsdlResourcePath = APIConstants.API_WSDL_RESOURCE_LOCATION + wsdlName;
    Resource resource = new ResourceImpl(wsdlResourcePath, new ResourceDO());
    Mockito.when(registry.get(wsdlResourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(registry.resourceExists(wsdlResourcePath)).thenReturn(true);
    try {
        abstractAPIManager.getWSDL(identifier);
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while getting wsdl file from the registry"));
    }
    String wsdlContent = "sample wsdl";
    resource.setContent(wsdlContent);
    InputStream inputStream = new ArrayInputStream();
    Mockito.when(resourceMock.getContentStream()).thenReturn(inputStream);
    Assert.assertEquals(wsdlContent, IOUtils.toString(abstractAPIManager.getWSDL(identifier).getContent()));
    PowerMockito.mockStatic(IOUtils.class);
}
 
Example #3
Source File: ScopesApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST

@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Add a new Shared Scope", notes = "This operation can be used to add a new Shared Scope. ", response = ScopeDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:shared_scope_manage", description = "Manage shared scopes")
    })
}, tags={ "Scopes",  })
@ApiResponses(value = { 
    @ApiResponse(code = 201, message = "Created. Successful response with the newly created Scope object as an entity in the body. ", response = ScopeDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error ", response = ErrorDTO.class),
    @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format. ", response = Void.class) })
public Response addSharedScope(@ApiParam(value = "Scope object that needs to be added " ,required=true) ScopeDTO body) throws APIManagementException{
    return delegate.addSharedScope(body, securityContext);
}
 
Example #4
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Delete existing API specific mediation policy
 * @param identifier API or Product identifier
 * @param apiResourcePath   path to the API registry resource
 * @param mediationPolicyId mediation policy identifier
 */
@Override
public Boolean deleteApiSpecificMediationPolicy(Identifier identifier, String apiResourcePath,
        String mediationPolicyId) throws APIManagementException {
    Resource mediationResource =
            this.getApiSpecificMediationResourceFromUuid(identifier, mediationPolicyId, apiResourcePath);
    if (mediationResource != null) {
        //If resource exists
        String mediationPath = mediationResource.getPath();
        try {
            if (registry.resourceExists(mediationPath)) {
                registry.delete(mediationPath);
                if (!registry.resourceExists(mediationPath)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Mediation policy deleted successfully");
                    }
                    return true;
                }
            }
        } catch (RegistryException e) {
            String msg = "Failed to delete specific mediation policy ";
            throw new APIManagementException(msg, e);
        }
    }
    return false;
}
 
Example #5
Source File: ApplicationsApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{applicationId}/keys/{keyType}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Get key details of a given type ", notes = "This operation can be used to retrieve key details of an individual application specifying the key type in the URI. ", response = ApplicationKeyDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:app_manage", description = "Retrieve, Manage applications"),
        @AuthorizationScope(scope = "apim:subscribe", description = "Subscribe API")
    })
}, tags={ "Application Keys",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Keys of given type are returned. ", response = ApplicationKeyDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. The resource does not exist. ", response = ErrorDTO.class),
    @ApiResponse(code = 412, message = "Precondition Failed. The request has not been performed because one of the preconditions is not met. ", response = ErrorDTO.class) })
public Response applicationsApplicationIdKeysKeyTypeGet(@ApiParam(value = "Application Identifier consisting of the UUID of the Application. ",required=true) @PathParam("applicationId") String applicationId, @ApiParam(value = "**Application Key Type** standing for the type of the keys (i.e. Production or Sandbox). ",required=true, allowableValues="PRODUCTION, SANDBOX") @PathParam("keyType") String keyType,  @ApiParam(value = "Application Group Id ")  @QueryParam("groupId") String groupId) throws APIManagementException{
    return delegate.applicationsApplicationIdKeysKeyTypeGet(applicationId, keyType, groupId, securityContext);
}
 
Example #6
Source File: APIStateChangeApprovalWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Handle cleanup task for api state change workflow Approval executor.
 * Use workflow external reference  to delete the pending workflow request
 *
 * @param workflowExtRef External Workflow Reference of pending workflow process
 */
@Override
public void cleanUpPendingTask(String workflowExtRef) throws WorkflowException {

    if (log.isDebugEnabled()) {
        log.debug("Starting cleanup task for APIStateChangeWSWorkflowExecutor for :" + workflowExtRef);
    }
    String errorMsg;
    super.cleanUpPendingTask(workflowExtRef);
    try {
        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        apiMgtDAO.deleteWorkflowRequest(workflowExtRef);
    } catch (APIManagementException axisFault) {
        errorMsg = "Error sending out cancel pending application approval process message. cause: " + axisFault
                .getMessage();
        throw new WorkflowException(errorMsg, axisFault);
    }
}
 
Example #7
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/validate-endpoint")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Check whether given endpoint url is valid", notes = "Using this operation, it is possible check whether the given API endpoint url is a valid url ", response = ApiEndpointValidationResponseDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_create", description = "Create API")
    })
}, tags={ "Validation",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. API definition validation information is returned ", response = ApiEndpointValidationResponseDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. Workflow for the given reference in not found. ", response = ErrorDTO.class) })
public Response validateEndpoint( @NotNull @ApiParam(value = "API endpoint url",required=true)  @QueryParam("endpointUrl") String endpointUrl,  @ApiParam(value = "")  @QueryParam("apiId") String apiId) throws APIManagementException{
    return delegate.validateEndpoint(endpointUrl, apiId, securityContext);
}
 
Example #8
Source File: RolesApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@HEAD
@Path("/{roleId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Check given role name is already exist", notes = "Using this operation, user can check a given role name exists or not. ", response = Void.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_publish", description = "Publish API"),
        @AuthorizationScope(scope = "apim:api_create", description = "Create API")
    })
}, tags={ "Roles" })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Requested role name exists.", response = Void.class),
    @ApiResponse(code = 404, message = "Not Found. Requested role name does not exist.", response = Void.class) })
public Response validateSystemRole(@ApiParam(value = "The Base 64 URL encoded role name with domain. If the given role is in secondary user-store, role ID should be derived as Base64URLEncode({user-store-name}/{role-name}). If the given role is in PRIMARY user-store, role ID can be derived as Base64URLEncode(role-name) ",required=true) @PathParam("roleId") String roleId) throws APIManagementException{
    return delegate.validateSystemRole(roleId, securityContext);
}
 
Example #9
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{apiId}/publish-to-external-stores")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Publish an API to external stores", notes = "This operation can be used to publish an API to a list of external stores. ", response = APIExternalStoreListDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_publish", description = "Publish API")
    })
}, tags={ "External Stores",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. API was successfully published to all the selected external stores. ", response = APIExternalStoreListDTO.class),
    @ApiResponse(code = 404, message = "Not Found. Request API resource or external store Ids not found. ", response = ErrorDTO.class),
    @ApiResponse(code = 500, message = "Internal server error while publishing to external stores", response = ErrorDTO.class) })
public Response publishAPIToExternalStores(@ApiParam(value = "**API ID** consisting of the **UUID** of the API. ",required=true) @PathParam("apiId") String apiId,  @NotNull @ApiParam(value = "External Store Ids of stores which the API needs to be published or updated.",required=true)  @QueryParam("externalStoreIds") String externalStoreIds, @ApiParam(value = "Validator for conditional requests; based on ETag. " )@HeaderParam("If-Match") String ifMatch) throws APIManagementException{
    return delegate.publishAPIToExternalStores(apiId, externalStoreIds, ifMatch, securityContext);
}
 
Example #10
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/{apiId}/mediation-policies/{mediationPolicyId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Delete an API specific mediation policy", notes = "This operation can be used to delete an existing API specific mediation policy providing the Id of the API and the Id of the mediation policy. ", response = Void.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_create", description = "Create API"),
        @AuthorizationScope(scope = "apim:mediation_policy_manage", description = "Update and delete mediation policies")
    })
}, tags={ "API Mediation Policy",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Resource successfully deleted. ", response = Void.class),
    @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. Resource to be deleted does not exist. ", response = ErrorDTO.class),
    @ApiResponse(code = 412, message = "Precondition Failed. The request has not been performed because one of the preconditions is not met. ", response = ErrorDTO.class) })
public Response apisApiIdMediationPoliciesMediationPolicyIdDelete(@ApiParam(value = "**API ID** consisting of the **UUID** of the API. ",required=true) @PathParam("apiId") String apiId, @ApiParam(value = "Mediation policy Id ",required=true) @PathParam("mediationPolicyId") String mediationPolicyId, @ApiParam(value = "Validator for conditional requests; based on ETag. " )@HeaderParam("If-Match") String ifMatch) throws APIManagementException{
    return delegate.apisApiIdMediationPoliciesMediationPolicyIdDelete(apiId, mediationPolicyId, ifMatch, securityContext);
}
 
Example #11
Source File: APIKeyValidationService.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public ArrayList<URITemplate> getAPIProductURITemplates(String context, String version)
        throws APIManagementException {
    Timer timer6 = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(
            APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_URI_TEMPLATE"));
    Timer.Context timerContext6 = timer6.start();
    if (log.isDebugEnabled()) {
        log.debug("getAllURITemplates request from gateway to keymanager: requestTime="
                + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date())
                + " ,for:" + context);
    }
    ArrayList<URITemplate> templates = getTemplates(context, version);
    if (log.isDebugEnabled()) {
        log.debug("getAllURITemplates response from keyManager to gateway for:" + context + " at "
                + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
    }
    timerContext6.stop();
    return templates;
}
 
Example #12
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Remove x-wso2-examples from all the paths from the swagger.
 *
 * @param swaggerString Swagger as String
 */
public String removeExamplesFromSwagger(String swaggerString) throws APIManagementException {
    try {
        SwaggerParser swaggerParser = new SwaggerParser();
        Swagger swagger = swaggerParser.parse(swaggerString);
        swagger.getPaths().values().forEach(path -> {
            path.getOperations().forEach(operation -> {
                if (operation.getVendorExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) {
                    operation.getVendorExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
                }
            });
        });
        return Yaml.pretty().writeValueAsString(swagger);
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while removing examples from OpenAPI definition", e,
                ExceptionCodes.ERROR_REMOVING_EXAMPLES);
    }
}
 
Example #13
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/{apiId}/documents/{documentId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Update a document of an API", notes = "This operation can be used to update metadata of an API's document. ", response = DocumentDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:document_manage", description = "Update and delete API documents"),
        @AuthorizationScope(scope = "apim:api_create", description = "Create API")
    })
}, tags={ "API Documents",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Document updated ", response = DocumentDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. The resource to be updated does not exist. ", response = ErrorDTO.class),
    @ApiResponse(code = 412, message = "Precondition Failed. The request has not been performed because one of the preconditions is not met. ", response = ErrorDTO.class) })
public Response apisApiIdDocumentsDocumentIdPut(@ApiParam(value = "**API ID** consisting of the **UUID** of the API. ",required=true) @PathParam("apiId") String apiId, @ApiParam(value = "Document Identifier ",required=true) @PathParam("documentId") String documentId, @ApiParam(value = "Document object that needs to be added " ,required=true) DocumentDTO body, @ApiParam(value = "Validator for conditional requests; based on ETag. " )@HeaderParam("If-Match") String ifMatch) throws APIManagementException{
    return delegate.apisApiIdDocumentsDocumentIdPut(apiId, documentId, body, ifMatch, securityContext);
}
 
Example #14
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/validate-graphql-schema")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@ApiOperation(value = "Validate GraphQL API definition and retrieve a summary", notes = "This operation can be used to validate a graphQL definition and retrieve a summary. ", response = GraphQLValidationResponseDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_create", description = "Create API")
    })
}, tags={ "Validation",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. API definition validation information is returned ", response = GraphQLValidationResponseDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. Workflow for the given reference in not found. ", response = ErrorDTO.class) })
public Response apisValidateGraphqlSchemaPost( @Multipart(value = "file") InputStream fileInputStream, @Multipart(value = "file" ) Attachment fileDetail) throws APIManagementException{
    return delegate.apisValidateGraphqlSchemaPost(fileInputStream, fileDetail, securityContext);
}
 
Example #15
Source File: SignupObserverTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateConfigurationContext() throws APIManagementException {
    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("foo.com");
    Mockito.when(privilegedCarbonContext.getTenantId()).thenReturn(1234);

    ConfigurationContext configurationContext = Mockito.mock(ConfigurationContext.class);
    PowerMockito.mockStatic(APIUtil.class);

    SignupObserver signupObserver = new SignupObserver();
    signupObserver.createdConfigurationContext(configurationContext);

    PowerMockito.verifyStatic(APIUtil.class);
    APIUtil.createSelfSignUpRoles(1234);
}
 
Example #16
Source File: SdkGenApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/languages")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Get a list of supported SDK languages ", notes = "This operation will provide a list of programming languages that are supported by the swagger codegen library for generating System Development Kits (SDKs) for APIs available in the API Manager Store ", response = Void.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:subscribe", description = "Subscribe API")
    })
}, tags={ "SDKs" })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. List of supported languages for generating SDKs. ", response = Void.class),
    @ApiResponse(code = 404, message = "Not Found. The list of languages is not found. ", response = ErrorDTO.class),
    @ApiResponse(code = 500, message = "Internal Server Error. Error while retrieving the list. ", response = ErrorDTO.class) })
public Response sdkGenLanguagesGet() throws APIManagementException{
    return delegate.sdkGenLanguagesGet(securityContext);
}
 
Example #17
Source File: APIGatewayManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Store the secured endpoint username password to registry
 *
 * @param api
 * @param tenantDomain
 * @throws APIManagementException
 */
private void setSecureVaultProperty(APIGatewayAdminClient securityAdminClient, API api, String tenantDomain)
        throws APIManagementException {

    boolean isSecureVaultEnabled =
            Boolean.parseBoolean(ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().
                    getAPIManagerConfiguration().getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE));
    if (api.isEndpointSecured() && isSecureVaultEnabled) {
        try {
            securityAdminClient.setSecureVaultProperty(api, tenantDomain);
        } catch (Exception e) {
            String msg = "Error in setting secured password.";
            log.error(msg + ' ' + e.getLocalizedMessage(), e);
            throw new APIManagementException(msg);
        }
    }
}
 
Example #18
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static APIMonetizationInfoDTO getMonetizationInfoDTO(APIProductIdentifier apiProductIdentifier)
        throws APIManagementException {

    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
    APIMonetizationInfoDTO apiMonetizationInfoDTO = new APIMonetizationInfoDTO();
    //set the information related to monetization to the DTO
    apiMonetizationInfoDTO.setEnabled(apiProduct.getMonetizationStatus());
    Map<String, String> monetizationPropertiesMap = new HashMap<>();
    if (apiProduct.getMonetizationProperties() != null) {
        JSONObject monetizationProperties = apiProduct.getMonetizationProperties();
        for (Object propertyKey : monetizationProperties.keySet()) {
            String key = (String) propertyKey;
            monetizationPropertiesMap.put(key, (String) monetizationProperties.get(key));
        }
    }
    apiMonetizationInfoDTO.setProperties(monetizationPropertiesMap);
    return apiMonetizationInfoDTO;
}
 
Example #19
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response applicationsApplicationIdChangeOwnerPost(String owner, String applicationId) {

    APIConsumer apiConsumer = null;
    try {
        apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(owner);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        boolean applicationUpdated = apiConsumer.updateApplicationOwner(owner, application);
        if (applicationUpdated) {
            return Response.ok().build();
        } else {
            RestApiUtil.handleInternalServerError("Error while updating application owner " + applicationId, log);
        }

    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while updating application owner " + applicationId, e, log);
    }

    return null;
}
 
Example #20
Source File: ApplicationsApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{applicationId}/keys")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Retrieve all application keys", notes = "Retrieve keys (Consumer key/secret) of application ", response = ApplicationKeyListDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:app_manage", description = "Retrieve, Manage applications"),
        @AuthorizationScope(scope = "apim:subscribe", description = "Subscribe API")
    })
}, tags={ "Application Keys",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Keys are returned. ", response = ApplicationKeyListDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. The resource does not exist. ", response = ErrorDTO.class),
    @ApiResponse(code = 412, message = "Precondition Failed. The request has not been performed because one of the preconditions is not met. ", response = ErrorDTO.class) })
public Response applicationsApplicationIdKeysGet(@ApiParam(value = "Application Identifier consisting of the UUID of the Application. ",required=true) @PathParam("applicationId") String applicationId) throws APIManagementException{
    return delegate.applicationsApplicationIdKeysGet(applicationId, securityContext);
}
 
Example #21
Source File: ApplicationsApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{applicationId}/api-keys/{keyType}/generate")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Generate API Key", notes = "Generate a self contained API Key for the application ", response = APIKeyDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:app_manage", description = "Retrieve, Manage applications"),
        @AuthorizationScope(scope = "apim:api_key", description = "Generate API Keys"),
        @AuthorizationScope(scope = "apim:subscribe", description = "Subscribe API")
    })
}, tags={ "API Keys",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. apikey generated. ", response = APIKeyDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. The resource to be updated does not exist. ", response = ErrorDTO.class),
    @ApiResponse(code = 412, message = "Precondition Failed. The request has not been performed because one of the preconditions is not met. ", response = ErrorDTO.class) })
public Response applicationsApplicationIdApiKeysKeyTypeGeneratePost(@ApiParam(value = "Application Identifier consisting of the UUID of the Application. ",required=true) @PathParam("applicationId") String applicationId, @ApiParam(value = "**Application Key Type** standing for the type of the keys (i.e. Production or Sandbox). ",required=true, allowableValues="PRODUCTION, SANDBOX") @PathParam("keyType") String keyType, @ApiParam(value = "API Key generation request object " ) APIKeyGenerateRequestDTO body, @ApiParam(value = "Validator for conditional requests; based on ETag. " )@HeaderParam("If-Match") String ifMatch) throws APIManagementException{
    return delegate.applicationsApplicationIdApiKeysKeyTypeGeneratePost(applicationId, keyType, body, ifMatch, securityContext);
}
 
Example #22
Source File: SettingsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response settingsApplicationAttributesGet(String ifNoneMatch, MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        List<ApplicationAttributeDTO> applicationAttributeDTOList = new ArrayList<>();
        JSONArray attributeArray = apiConsumer.getAppAttributesFromConfig(username);
        for (int i = 0; i < attributeArray.size(); i++) {
            JSONObject obj = (JSONObject) attributeArray.get(i);
            ApplicationAttributeDTO applicationAttributeDTO = ApplicationMappingUtil
                    .fromApplicationAttributeJsonToDTO(obj);
            applicationAttributeDTOList.add(applicationAttributeDTO);
        }
        ApplicationAttributeListDTO applicationAttributeListDTO = ApplicationMappingUtil
                .fromApplicationAttributeListToDTO(applicationAttributeDTOList);
        return Response.ok().entity(applicationAttributeListDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil
                .handleInternalServerError("Error occurred in reading application attributes from config", e, log);
    }
    return null;
}
 
Example #23
Source File: ApplicationRegistrationSimpleWorkflowExecutorTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws APIManagementException {
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    keyManager = Mockito.mock(KeyManager.class);
    application = new Application("test", new Subscriber("testUser"));
    oAuthAppRequest = new OAuthAppRequest();
    oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo);
    workflowDTO = new ApplicationRegistrationWorkflowDTO();
    workflowDTO.setWorkflowReference("1");
    workflowDTO.setApplication(application);
    workflowDTO.setAppInfoDTO(oAuthAppRequest);
    workflowDTO.setKeyManager("default");

    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    PowerMockito.when(KeyManagerHolder.getKeyManagerInstance("carbon.super", "default")).thenReturn(keyManager);
    KeyManagerConfiguration keyManagerConfiguration = new KeyManagerConfiguration();
    Mockito.when(keyManager.getKeyManagerConfiguration()).thenReturn(keyManagerConfiguration);
    applicationRegistrationSimpleWorkflowExecutor = new ApplicationRegistrationSimpleWorkflowExecutor();

}
 
Example #24
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, List<KeyManagerConfigurationDTO>> getAllKeyManagerConfigurations()
        throws APIManagementException {

    List<KeyManagerConfigurationDTO> keyManagerConfigurations = apiMgtDAO.getKeyManagerConfigurations();
    Map<String, List<KeyManagerConfigurationDTO>> keyManagerConfigurationsByTenant = new HashMap<>();
    for (KeyManagerConfigurationDTO keyManagerConfiguration : keyManagerConfigurations) {
        List<KeyManagerConfigurationDTO> keyManagerConfigurationDTOS;
        if (keyManagerConfigurationsByTenant.containsKey(keyManagerConfiguration.getTenantDomain())) {
            keyManagerConfigurationDTOS =
                    keyManagerConfigurationsByTenant.get(keyManagerConfiguration.getTenantDomain());
        } else {
            keyManagerConfigurationDTOS = new ArrayList<>();
        }
        if (APIConstants.KeyManager.DEFAULT_KEY_MANAGER.equals(keyManagerConfiguration.getName())) {
            APIUtil.getAndSetDefaultKeyManagerConfiguration(keyManagerConfiguration);
        }
        keyManagerConfigurationDTOS.add(keyManagerConfiguration);
        keyManagerConfigurationsByTenant
                .put(keyManagerConfiguration.getTenantDomain(), keyManagerConfigurationDTOS);
    }
    return keyManagerConfigurationsByTenant;
}
 
Example #25
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/{apiId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Delete an API", notes = "This operation can be used to delete an existing API proving the Id of the API. ", response = Void.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_delete", description = "Delete API"),
        @AuthorizationScope(scope = "apim:api_import_export", description = "Import and export APIs related operations")
    })
}, tags={ "APIs",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Resource successfully deleted. ", response = Void.class),
    @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. Resource to be deleted does not exist. ", response = ErrorDTO.class),
    @ApiResponse(code = 409, message = "Conflict. The request could not be completed due to a conflict with the current state of the target resource. ", response = ErrorDTO.class),
    @ApiResponse(code = 412, message = "Precondition Failed. The request has not been performed because one of the preconditions is not met. ", response = ErrorDTO.class) })
public Response apisApiIdDelete(@ApiParam(value = "**API ID** consisting of the **UUID** of the API. ",required=true) @PathParam("apiId") String apiId, @ApiParam(value = "Validator for conditional requests; based on ETag. " )@HeaderParam("If-Match") String ifMatch) throws APIManagementException{
    return delegate.apisApiIdDelete(apiId, ifMatch, securityContext);
}
 
Example #26
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{apiId}/client-certificates")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Retrieve/ Search uploaded Client Certificates.", notes = "This operation can be used to retrieve and search the uploaded client certificates. ", response = ClientCertificatesDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:client_certificates_view", description = "View client certificates"),
        @AuthorizationScope(scope = "apim:api_view", description = "View API")
    })
}, tags={ "Client Certificates",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Successful response with the list of matching certificate information in the body. ", response = ClientCertificatesDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Failure due to not providing alias or server is not configured to support mutual SSL authentication. ", response = ErrorDTO.class),
    @ApiResponse(code = 500, message = "Internal Server Error ", response = ErrorDTO.class) })
public Response apisApiIdClientCertificatesGet(@ApiParam(value = "UUID of the API",required=true) @PathParam("apiId") String apiId,  @ApiParam(value = "Maximum size of resource array to return. ", defaultValue="25") @DefaultValue("25") @QueryParam("limit") Integer limit,  @ApiParam(value = "Starting point within the complete list of items qualified. ", defaultValue="0") @DefaultValue("0") @QueryParam("offset") Integer offset,  @ApiParam(value = "Alias for the client certificate")  @QueryParam("alias") String alias) throws APIManagementException{
    return delegate.apisApiIdClientCertificatesGet(apiId, limit, offset, alias, securityContext);
}
 
Example #27
Source File: SubscriptionsApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/multiple")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Add new subscriptions ", notes = "This operation can be used to add a new subscriptions providing the ids of the APIs and the applications. ", response = SubscriptionDTO.class, responseContainer = "List", authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:sub_manage", description = "Retrieve, Manage subscriptions"),
        @AuthorizationScope(scope = "apim:subscribe", description = "Subscribe API")
    })
}, tags={ "Subscriptions",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Successful response with the newly created objects as entity in the body. ", response = SubscriptionDTO.class, responseContainer = "List"),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error. ", response = ErrorDTO.class),
    @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format. ", response = Void.class) })
public Response subscriptionsMultiplePost(@ApiParam(value = "Subscription objects that should to be added " ,required=true) List<SubscriptionDTO> body, @ApiParam(value = "For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be   retirieved from. " )@HeaderParam("X-WSO2-Tenant") String xWSO2Tenant) throws APIManagementException{
    return delegate.subscriptionsMultiplePost(body, xWSO2Tenant, securityContext);
}
 
Example #28
Source File: APIKeyValidationService.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Return the URI Templates for an API
 *
 * @param context Requested context
 * @param version API Version
 * @return APIKeyValidationInfoDTO with authorization info and tier info if authorized. If it is not
 * authorized, tier information will be <pre>null</pre>
 * @throws APIKeyMgtException Error occurred when accessing the underlying database or registry.
 */
public ArrayList<URITemplate> getAllURITemplates(String context, String version)
        throws APIKeyMgtException, APIManagementException {
    Timer timer6 = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(
            APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_URI_TEMPLATE"));
    Timer.Context timerContext6 = timer6.start();
    if (log.isDebugEnabled()) {
        log.debug("getAllURITemplates request from gateway to keymanager: requestTime="
                + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date())
                + " ,for:" + context);
    }
    ArrayList<URITemplate> templates = getTemplates(context, version);
    if (log.isDebugEnabled()) {
        log.debug("getAllURITemplates response from keyManager to gateway for:" + context + " at "
                + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
    }
    timerContext6.stop();
    return templates;
}
 
Example #29
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all Advanced level policies
 *
 * @param accept          Accept header value
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return All matched Advanced Throttle policies to the given request
 */
@Override
public Response throttlingPoliciesAdvancedGet(String accept, String ifNoneMatch, String ifModifiedSince) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String userName = RestApiUtil.getLoggedInUsername();
        APIPolicy[] apiPolicies = (APIPolicy[]) apiProvider.getPolicies(userName, PolicyConstants.POLICY_LEVEL_API);
        AdvancedThrottlePolicyListDTO listDTO = AdvancedThrottlePolicyMappingUtil
                .fromAPIPolicyArrayToListDTO(apiPolicies);
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving Advanced level policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #30
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a json string using the swagger object.
 *
 * @param swaggerObj swagger object
 * @return json string using the swagger object
 * @throws APIManagementException error while creating swagger json
 */
public static String getSwaggerJsonString(Swagger swaggerObj) throws APIManagementException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    //this is to ignore "originalRef" in schema objects
    mapper.addMixIn(RefModel.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefProperty.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefPath.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefParameter.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefResponse.class, IgnoreOriginalRefMixin.class);

    //this is to ignore "responseSchema" in response schema objects
    mapper.addMixIn(Response.class, ResponseSchemaMixin.class);
    try {
        return new String(mapper.writeValueAsBytes(swaggerObj));
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while generating Swagger json from model", e);
    }
}