Java Code Examples for org.wso2.carbon.apimgt.api.model.APIIdentifier

The following examples show how to use org.wso2.carbon.apimgt.api.model.APIIdentifier. These examples are extracted from open source projects. 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 Project: docs-apim   Source File: 103335311.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean deleteFromStore(APIIdentifier apiId, APIStore store) throws APIManagementException {
	boolean deleted = false;
    if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) {
        String msg = "External APIStore endpoint URL or credentials are not defined.Cannot proceed with publishing API to the APIStore - " + store.getDisplayName();
        throw new APIManagementException(msg);

    } else {
        CookieStore cookieStore = new BasicCookieStore();
        HttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        boolean authenticated = authenticateAPIM(store,httpContext);
        if (authenticated) {
        	deleted = deleteWSO2Store(apiId, store.getUsername(), store.getEndpoint(), httpContext,store.getDisplayName());
        	logoutFromExternalStore(store, httpContext);
        }
        return deleted;
    }
}
 
Example 2
private String getDestinationCell(TokenValidationContext validationContext) throws APIManagementException {

        String providerName = validationContext.getValidationInfoDTO().getApiPublisher();
        String apiName = validationContext.getValidationInfoDTO().getApiName();
        String apiVersion = removeDefaultVersion(validationContext);

        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
        APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(providerName);
        API api = apiProvider.getAPI(apiIdentifier);

        Object cellName = api.getAdditionalProperties().get(CELL_NAME);
        if (cellName instanceof String) {
            String destinationCell = String.valueOf(cellName);
            log.debug("Destination Cell for API call is '" + destinationCell + "'");
            return destinationCell;
        } else {
            log.debug("Property:" + CELL_NAME + " was not found for the API. This API call is going to an API not " +
                    "published by a Cellery Cell.");
            return null;
        }
    }
 
Example 3
Source Project: carbon-apimgt   Source File: AbstractAPIManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get the thumbnailLastUpdatedTime for a thumbnail for a given api
 *
 * @param apiIdentifier
 * @return
 * @throws APIManagementException
 */
@Override
public String getThumbnailLastUpdatedTime(APIIdentifier apiIdentifier) throws APIManagementException {
    String artifactPath = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();

    String thumbPath = artifactPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
    try {
        if (registry.resourceExists(thumbPath)) {
            Resource res = registry.get(thumbPath);
            Date lastModifiedTime = res.getLastModified();
            return lastModifiedTime == null ? String.valueOf(res.getCreatedTime().getTime()) : String.valueOf(lastModifiedTime.getTime());
        }
    } catch (RegistryException e) {
        String msg = "Error while loading API icon from the registry";
        throw new APIManagementException(msg, e);
    }
    return null;

}
 
Example 4
Source Project: carbon-apimgt   Source File: TransportConfigContextTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTransportConfigContext() throws Exception {

    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setTransports(Constants.TRANSPORT_HTTP);
    ConfigContext configcontext = new APIConfigContext(api);
    TransportConfigContext transportConfigContext = new TransportConfigContext(configcontext, api);
    transportConfigContext.validate();
    Assert.assertTrue(Constants.TRANSPORT_HTTP.equalsIgnoreCase
            (transportConfigContext.getContext().get("transport").toString()));
    api.setTransports(Constants.TRANSPORT_HTTP + "," + Constants.TRANSPORT_HTTPS);
    configcontext = new APIConfigContext(api);
    transportConfigContext = new TransportConfigContext(configcontext, api);
    Assert.assertTrue(StringUtils.EMPTY.equalsIgnoreCase
            (transportConfigContext.getContext().get("transport").toString()));
}
 
Example 5
@Test
public void testStatusChanged() throws Exception {

    API api = Mockito.mock(API.class);
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    String previousStatus = APIConstants.CREATED;
    String currentStatus = APIConstants.PUBLISHED;

    Mockito.when(api.getId()).thenReturn(apiIdentifier);
    Mockito.when(apiIdentifier.getApiName()).thenReturn(API_NAME);
    Mockito.when(apiIdentifier.getVersion()).thenReturn(API_VERSION);

    SimpleLoggingObserver simpleLoggingObserver = new SimpleLoggingObserver();
    boolean returnValue = simpleLoggingObserver.statusChanged(previousStatus, currentStatus, api);
    Assert.assertTrue(returnValue);
}
 
Example 6
Source Project: carbon-apimgt   Source File: APIUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIsPerAPISequenceSequenceMissing() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    String path = artifactPath + RegistryConstants.PATH_SEPARATOR + "in" + RegistryConstants.PATH_SEPARATOR;

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);
    Mockito.when(registry.resourceExists(eq(path))).thenReturn(true);
    Mockito.when(registry.get(eq(path))).thenReturn(null);

    boolean isPerAPiSequence = APIUtil.isPerAPISequence("sample", 1, apiIdentifier, "in");

    Assert.assertFalse(isPerAPiSequence);
}
 
Example 7
Source Project: carbon-apimgt   Source File: APIConsumerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAllPublishedAPIs() throws APIManagementException, GovernanceException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    APINameComparator apiNameComparator = Mockito.mock(APINameComparator.class);
    SortedSet<API> apiSortedSet = new TreeSet<API>(apiNameComparator);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager(apiConsumer.registry, APIConstants.API_KEY)).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    APIIdentifier apiId1 = new APIIdentifier(API_PROVIDER, SAMPLE_API_NAME, SAMPLE_API_VERSION);
    API api = new API(apiId1);

    Mockito.when(artifactManager.getAllGenericArtifacts()).thenReturn(genericArtifacts);
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("PUBLISHED");
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);

    Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
    latestPublishedAPIs.put("user:key", api);
    apiSortedSet.addAll(latestPublishedAPIs.values());
    assertNotNull(apiConsumer.getAllPublishedAPIs("testDomain"));
}
 
Example 8
Source Project: carbon-apimgt   Source File: ExportApiUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Exports an API from API Manager for a given API using the ApiId. ID. Meta information, API icon, documentation,
 * WSDL and sequences are exported. This service generates a zipped archive which contains all the above mentioned
 * resources for a given API.
 *
 * @param apiIdentifier
 * @param preserveStatus Preserve API status on export
 * @return Zipped file containing exported API
 */
public Response exportApiById(APIIdentifier apiIdentifier, Boolean preserveStatus) {
    ExportFormat exportFormat;
    APIProvider apiProvider;
    String userName;
    File file;
    try {
        exportFormat = ExportFormat.YAML;
        apiProvider = RestApiUtil.getLoggedInUserProvider();
        userName = RestApiUtil.getLoggedInUsername();
        file = APIExportUtil.exportApi(apiProvider, apiIdentifier, userName, exportFormat, preserveStatus);
        return Response.ok(file)
                .header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\""
                        + file.getName() + "\"")
                .build();
    } catch (APIManagementException | APIImportExportException e) {
        RestApiUtil.handleInternalServerError("Error while exporting " + RestApiConstants.RESOURCE_API, e, log);
    }
    return null;
}
 
Example 9
Source Project: carbon-apimgt   Source File: APIConsumerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAPIsWithTag() throws Exception {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.mockStatic(GovernanceUtils.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager(apiConsumer.registry, APIConstants.API_KEY)).
            thenReturn(artifactManager);
    List<GovernanceArtifact> governanceArtifacts = new ArrayList<GovernanceArtifact>();
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    governanceArtifacts.add(artifact);
    Mockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(),(UserRegistry)Mockito.anyObject(),
            Mockito.anyString())).thenReturn(governanceArtifacts);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact)).thenReturn(api);
    Mockito.when(artifact.getAttribute("overview_status")).thenReturn("PUBLISHED");
    assertNotNull(apiConsumer.getAPIsWithTag("testTag", "testDomain"));
}
 
Example 10
Source Project: carbon-apimgt   Source File: APIMgtDAOTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLifeCycleEvents() throws Exception {
    APIIdentifier apiId = new APIIdentifier("hiranya", "WSO2Earth", "1.0.0");
    API api = new API(apiId);
    api.setContext("/wso2earth");
    api.setContextTemplate("/wso2earth/{version}");

    apiMgtDAO.addAPI(api, -1234);

    List<LifeCycleEvent> events = apiMgtDAO.getLifeCycleEvents(apiId);
    assertEquals(1, events.size());
    LifeCycleEvent event = events.get(0);
    assertEquals(apiId, event.getApi());
    assertNull(event.getOldStatus());
    assertEquals(APIConstants.CREATED, event.getNewStatus());
    assertEquals("hiranya", event.getUserId());

    apiMgtDAO.recordAPILifeCycleEvent(apiId, APIStatus.CREATED, APIStatus.PUBLISHED, "admin", -1234);
    apiMgtDAO.recordAPILifeCycleEvent(apiId, APIStatus.PUBLISHED, APIStatus.DEPRECATED, "admin", -1234);
    events = apiMgtDAO.getLifeCycleEvents(apiId);
    assertEquals(3, events.size());
}
 
Example 11
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIsDocumentationExist() throws APIManagementException, RegistryException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String docName = "sampleDoc";
    String docPath =
            APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName()
                    + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR
                    + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR
                    + RegistryConstants.PATH_SEPARATOR + docName;
    Mockito.when(registry.resourceExists(docPath)).thenThrow(RegistryException.class).thenReturn(true);
    try {
        abstractAPIManager.isDocumentationExist(identifier, docName);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to check existence of the document"));
    }
    Assert.assertTrue(abstractAPIManager.isDocumentationExist(identifier, docName));
}
 
Example 12
Source Project: carbon-apimgt   Source File: ApisApiServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Response deleteComment(String commentId, String apiId, String ifMatch, MessageContext messageContext) throws APIManagementException {
    String requestedTenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    try {
        APIConsumer apiConsumer = RestApiUtil.getLoggedInUserConsumer();
        APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId, requestedTenantDomain);

        apiConsumer.deleteComment(apiIdentifier, commentId);
        return Response.ok("The comment has been deleted").build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            String errorMessage = "Error while deleting comment " + commentId + "for API " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
 
Example 13
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: 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 14
Source Project: carbon-apimgt   Source File: APIGatewayManager.java    License: Apache License 2.0 6 votes vote down vote up
public void setProductResourceSequences(APIProviderImpl apiProvider, APIProduct apiProduct)
        throws APIManagementException {

    for (APIProductResource resource : apiProduct.getProductResources()) {
        APIIdentifier apiIdentifier = resource.getApiIdentifier();
        API api = apiProvider.getAPI(apiIdentifier);

        String inSequenceKey = APIUtil.getSequenceExtensionName(api) + APIConstants.API_CUSTOM_SEQ_IN_EXT;
        if (APIUtil.isSequenceDefined(api.getInSequence())) {
            resource.setInSequenceName(inSequenceKey);
        }

        String outSequenceKey = APIUtil.getSequenceExtensionName(api) + APIConstants.API_CUSTOM_SEQ_OUT_EXT;
        if (APIUtil.isSequenceDefined(api.getOutSequence())) {
            resource.setOutSequenceName(outSequenceKey);
        }

        String faultSequenceKey = APIUtil.getFaultSequenceName(api);
        if (APIUtil.isSequenceDefined(api.getFaultSequence())) {
            resource.setFaultSequenceName(faultSequenceKey);
        }
    }
}
 
Example 15
Source Project: carbon-apimgt   Source File: CertificateManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ResponseCode addClientCertificate(APIIdentifier apiIdentifier, String certificate, String alias,
        String tierName, int tenantId) {
    ResponseCode responseCode;
    try {
        responseCode = certificateMgtUtils.validateCertificate(alias, tenantId, certificate);
        if (responseCode == ResponseCode.SUCCESS) {
            if (certificateMgtDAO.checkWhetherAliasExist(alias, tenantId)) {
                responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE;
            } else {
                certificateMgtDAO.addClientCertificate(certificate, apiIdentifier, alias, tierName, tenantId, null);
            }
        }
    } catch (CertificateManagementException e) {
        log.error("Error when adding client certificate with alias " + alias + " to database for the API "
                + apiIdentifier.toString(), e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    }
    return responseCode;
}
 
Example 16
Source Project: carbon-apimgt   Source File: APIUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMediationSequenceUuidInSequence() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);

    Collection collection = Mockito.mock(Collection.class);
    String path = APIConstants.API_CUSTOM_SEQUENCE_LOCATION + File.separator + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN;
    Mockito.when(registry.get(eq(path))).thenReturn(collection);

    String[] childPaths = {"test"};
    Mockito.when(collection.getChildren()).thenReturn(childPaths);

    String expectedUUID = UUID.randomUUID().toString();

    InputStream sampleSequence = new FileInputStream(Thread.currentThread().getContextClassLoader().
            getResource("sampleSequence.xml").getFile());

    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(registry.get(eq("test"))).thenReturn(resource);
    Mockito.when(resource.getContentStream()).thenReturn(sampleSequence);
    Mockito.when(resource.getUUID()).thenReturn(expectedUUID);


    String actualUUID = APIUtil.getMediationSequenceUuid("sample", 1, "in", apiIdentifier);

    Assert.assertEquals(expectedUUID, actualUUID);
    sampleSequence.close();
}
 
Example 17
Source Project: carbon-apimgt   Source File: APIMgtDAOTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddSubscription() throws Exception {
    APIIdentifier apiIdentifier = new APIIdentifier("SUMEDHA", "API1", "V1.0.0");
    apiIdentifier.setApplicationId("APPLICATION99");
    apiIdentifier.setTier("T1");
    API api = new API(apiIdentifier);
    ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(api);
    apiMgtDAO.addSubscription(apiTypeWrapper, 100, "UNBLOCKED", "admin");
}
 
Example 18
Source Project: carbon-apimgt   Source File: OASTestBase.java    License: Apache License 2.0 5 votes vote down vote up
public String testGenerateAPIDefinitionWithExtension(APIDefinition parser, String content) throws Exception {
    JSONObject jsonObject = new JSONObject(content);
    String equalNoOfResourcesWithExtension = jsonObject.getJSONObject("equalNoOfResourcesWithExtension").toString();

    Scope newScope = new Scope();
    newScope.setName("newScope");
    newScope.setKey("newScope");
    newScope.setRoles("admin");
    newScope.setDescription("newScopeDescription");

    URITemplate updatedItemGet = new URITemplate();
    updatedItemGet.setUriTemplate("/items");
    updatedItemGet.setAuthType("Application & Application User");
    updatedItemGet.setAuthTypes("Application & Application User");
    updatedItemGet.setHTTPVerb("GET");
    updatedItemGet.setHttpVerbs("GET");
    updatedItemGet.setThrottlingTier("Unlimited");
    updatedItemGet.setThrottlingTiers("Unlimited");
    updatedItemGet.setScope(newScope);
    updatedItemGet.setScopes(newScope);

    APIIdentifier identifier = new APIIdentifier("admin", "simple", "1.0.0");
    API api = new API(identifier);
    api.setScopes(new HashSet<>(Arrays.asList(sampleScope, extensionScope, newScope)));
    api.setUriTemplates(new HashSet<>(Arrays.asList(petPost, updatedItemGet)));

    String definition = parser.generateAPIDefinition(new SwaggerData(api), equalNoOfResourcesWithExtension);
    APIDefinitionValidationResponse response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    return definition;
}
 
Example 19
Source Project: carbon-apimgt   Source File: ApisApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response apisApiIdGraphqlPoliciesComplexityTypesGet(String apiId, MessageContext messageContext) throws APIManagementException {
    GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
    try {
        APIConsumer apiConsumer = RestApiUtil.getLoggedInUserConsumer();
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId, tenantDomain);
        API api = apiConsumer.getAPIbyUUID(apiId, tenantDomain);
        if (APIConstants.GRAPHQL_API.equals(api.getType())) {
            String schemaContent = apiConsumer.getGraphqlSchema(apiIdentifier);
            List<GraphqlSchemaType> typeList = graphql.extractGraphQLTypeList(schemaContent);
            GraphQLSchemaTypeListDTO graphQLSchemaTypeListDTO =
                    GraphqlQueryAnalysisMappingUtil.fromGraphqlSchemaTypeListtoDTO(typeList);
            return Response.ok().entity(graphQLSchemaTypeListDTO).build();
        } else {
            throw new APIManagementException(ExceptionCodes.API_NOT_GRAPHQL);
        }
    } catch (APIManagementException e) {
        //Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(
                    "Authorization failure while retrieving types and fields of API : " + apiId, e, log);
        } else {
            String msg = "Error while retrieving types and fields of the schema of API " + apiId;
            RestApiUtil.handleInternalServerError(msg, e, log);
        }
    }
    return null;
}
 
Example 20
Source Project: carbon-apimgt   Source File: AbstractAPIManager.java    License: Apache License 2.0 5 votes vote down vote up
private GenericArtifactManager getAPIGenericArtifactManager(APIIdentifier identifier, Registry registry)
        throws APIManagementException {

    String tenantDomain = getTenantDomain(identifier);
    GenericArtifactManager manager = genericArtifactCache.get(tenantDomain);
    if (manager != null) {
        return manager;
    }
    manager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
    genericArtifactCache.put(tenantDomain, manager);
    return manager;
}
 
Example 21
Source Project: carbon-apimgt   Source File: AbstractAPIManagerTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDocumentation() throws APIManagementException, RegistryException {
    Registry registry = Mockito.mock(UserRegistry.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(genericArtifactManager, registry, null);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String documentationName = "doc1";
    String contentPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName()
            + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR
            + identifier.getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.DOC_DIR
            + RegistryConstants.PATH_SEPARATOR + documentationName;
    GenericArtifact genericArtifact = getGenericArtifact(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION,
            "sample");
    String docType = "other";
    genericArtifact.setAttribute(APIConstants.DOC_TYPE, docType);
    genericArtifact.setAttribute(APIConstants.DOC_SOURCE_TYPE, "URL");
    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);
    Mockito.when(registry.get(contentPath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(genericArtifactManager.getGenericArtifact(SAMPLE_RESOURCE_ID)).thenReturn(genericArtifact);
    try {
        abstractAPIManager.getDocumentation(identifier, DocumentationType.OTHER, documentationName);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get documentation details"));
    }
    Assert.assertTrue(
            abstractAPIManager.getDocumentation(identifier, DocumentationType.OTHER, documentationName).getId()
                    .equals(genericArtifact.getId()));
}
 
Example 22
Source Project: carbon-apimgt   Source File: APIUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCustomSequenceNotFound() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);

    Collection collection = Mockito.mock(Collection.class);
    String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    String path = artifactPath + RegistryConstants.PATH_SEPARATOR + "custom" + RegistryConstants.PATH_SEPARATOR;

    Mockito.when(registry.get(eq(path))).thenReturn(null, collection);

    String[] childPaths = {"test"};
    Mockito.when(collection.getChildren()).thenReturn(childPaths);

    String expectedUUID = UUID.randomUUID().toString();

    InputStream sampleSequence = new FileInputStream(Thread.currentThread().getContextClassLoader().
            getResource("sampleSequence.xml").getFile());

    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(registry.get(eq("test"))).thenReturn(resource);
    Mockito.when(resource.getContentStream()).thenReturn(sampleSequence);
    Mockito.when(resource.getUUID()).thenReturn(expectedUUID);


    OMElement customSequence = APIUtil.getCustomSequence("sample", 1, "custom", apiIdentifier);

    Assert.assertNotNull(customSequence);
    sampleSequence.close();
}
 
Example 23
Source Project: carbon-apimgt   Source File: APIConsumerImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetUserRating() throws APIManagementException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    APIIdentifier apiIdentifier = new APIIdentifier(API_PROVIDER, SAMPLE_API_NAME, SAMPLE_API_VERSION);
    when(apiMgtDAO.getUserRating(apiIdentifier, "admin")).thenReturn(2);
    apiConsumer.apiMgtDAO = apiMgtDAO;
    assertEquals(2, apiConsumer.getUserRating(apiIdentifier, "admin"));
}
 
Example 24
Source Project: carbon-apimgt   Source File: UserAwareAPIProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void updateDocumentation(APIIdentifier apiId,
                                Documentation documentation) throws APIManagementException {
    if (!checkCreateOrPublishPermission()) {
        throw new APIManagementException("User '" + username + "' has neither '" +
                APIConstants.Permissions.API_CREATE + "' nor the '" + APIConstants.Permissions.API_PUBLISH +
                "' permission to update API documentation");
    }
    checkAccessControlPermission(apiId);
    super.updateDocumentation(apiId, documentation);
}
 
Example 25
Source Project: carbon-apimgt   Source File: AbstractAPIManagerWrapper.java    License: Apache License 2.0 5 votes vote down vote up
protected API getApi(GovernanceArtifact artifact) throws APIManagementException {
    try {

        APIIdentifier apiIdentifier = new APIIdentifier(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER),
                artifact.getAttribute(APIConstants.API_OVERVIEW_NAME),
                artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
        API api = new API(apiIdentifier);
        return api;
    } catch (GovernanceException e) {
        throw new APIManagementException("Error while getting attribute", e);
    }
}
 
Example 26
Source Project: carbon-apimgt   Source File: UserAwareAPIProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientCertificateDTO getClientCertificate(int tenantId, String alias, APIIdentifier apiIdentifier)
        throws APIManagementException {
    ClientCertificateDTO clientCertificateDTO = super.getClientCertificate(tenantId, alias);
    if (clientCertificateDTO != null) {
        checkAccessControlPermission(clientCertificateDTO.getApiIdentifier());
    }
    return clientCertificateDTO;
}
 
Example 27
Source Project: carbon-apimgt   Source File: UserAwareAPIProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateAPIStatus(APIIdentifier identifier, String status, boolean publishToGateway,
        boolean deprecateOldVersions, boolean makeKeysForwardCompatible)
        throws APIManagementException, FaultGatewaysException {
    checkAccessControlPermission(identifier);
    return super
            .updateAPIStatus(identifier, status, publishToGateway, deprecateOldVersions, makeKeysForwardCompatible);
}
 
Example 28
Source Project: carbon-apimgt   Source File: RestApiUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if the user's tenant and the API's tenant is equal. If it is not this will throw an
 * APIMgtAuthorizationFailedException
 *
 * @param apiIdentifier API Identifier
 * @throws APIMgtAuthorizationFailedException
 */
public static void validateUserTenantWithAPIIdentifier(APIIdentifier apiIdentifier)
        throws APIMgtAuthorizationFailedException {
    String username = RestApiUtil.getLoggedInUsername();
    String providerName = APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName());
    String providerTenantDomain = MultitenantUtils.getTenantDomain(providerName);
    String loggedInUserTenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    if (!providerTenantDomain.equals(loggedInUserTenantDomain)) {
        String errorMsg = "User " + username + " is not allowed to access " + apiIdentifier.toString()
                + " as it belongs to a different tenant : " + providerTenantDomain;
        throw new APIMgtAuthorizationFailedException(errorMsg);
    }
}
 
Example 29
/**
 * Check whether a target Tier is available to subscribe
 *
 * @param targetTier Target Tier
 * @param api        - {@link org.wso2.carbon.apimgt.api.model.API}
 * @return true, if the target tier is available
 */
private boolean isTierAvailable(Tier targetTier, API api) {
    APIIdentifier apiId = api.getId();
    Set<Tier> availableTiers = api.getAvailableTiers();
    if (availableTiers.contains(targetTier)) {
        return true;
    } else {
        log.error("Tier:" + targetTier.getName() + " is not available for API " + apiId.getApiName() + "-" +
                apiId.getVersion());
        return false;
    }
}
 
Example 30
Source Project: carbon-apimgt   Source File: APIConsumerImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubscribedIdentifiers() throws APIManagementException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(apiMgtDAO);
    Set<SubscribedAPI> originalSubscribedAPIs = new HashSet<>();
    SubscribedAPI subscribedAPI = Mockito.mock(SubscribedAPI.class);
    originalSubscribedAPIs.add(subscribedAPI);
    Subscriber subscriber = new Subscriber("Subscriber");
    APIIdentifier apiId1 = new APIIdentifier(API_PROVIDER, SAMPLE_API_NAME, SAMPLE_API_VERSION);
    Tier tier = Mockito.mock(Tier.class);

    when(apiMgtDAO.getSubscribedAPIs(subscriber, "testID")).thenReturn(originalSubscribedAPIs);
    when(subscribedAPI.getTier()).thenReturn(tier);
    when(tier.getName()).thenReturn("tier");
    when(subscribedAPI.getApiId()).thenReturn(apiId1);
    Application app = Mockito.mock(Application.class);
    when(app.getId()).thenReturn(1);
    when(subscribedAPI.getApplication()).thenReturn(app);
    Set<APIKey> apiKeys = new HashSet<>();
    APIKey apiKey = new APIKey();
    apiKey.setType("Production");
    apiKeys.add(apiKey);
    Mockito.when(apiMgtDAO.getKeyMappingsFromApplicationId(Mockito.anyInt())).thenReturn(apiKeys);

    AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
    accessTokenInfo.setAccessToken(UUID.randomUUID().toString());
    Mockito.when(keyManager.getAccessTokenByConsumerKey(Mockito.anyString())).thenReturn(accessTokenInfo);
    assertNotNull(apiConsumer.getSubscribedIdentifiers(subscriber, apiId1,"testID"));
}