org.wso2.carbon.apimgt.api.model.API Java Examples

The following examples show how to use org.wso2.carbon.apimgt.api.model.API. 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: 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 #2
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsProductionEndpointsNotExists() throws Exception {
    API api = Mockito.mock(API.class);

    JSONObject sandboxEndpoints = new JSONObject();
    sandboxEndpoints.put("url", "https:\\/\\/localhost:9443\\/am\\/sample\\/pizzashack\\/v1\\/api\\/");
    sandboxEndpoints.put("config", null);

    JSONObject root = new JSONObject();
    root.put("sandbox_endpoints", sandboxEndpoints);
    root.put("endpoint_type", "http");

    Mockito.when(api.getEndpointConfig()).thenReturn(root.toJSONString());

    Assert.assertFalse("Unexpected production endpoint found", APIUtil.isProductionEndpointsExists(root.toJSONString()));
}
 
Example #3
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a List object of APIs into a DTO
 *
 * @param apiList List of APIs
 * @param limit   maximum number of APIs returns
 * @param offset  starting index
 * @return APIListDTO object containing APIDTOs
 */
public static APIListDTO fromAPIListToDTO(List<API> apiList, int offset, int limit) {
    APIListDTO apiListDTO = new APIListDTO();
    List<APIInfoDTO> apiInfoDTOs = apiListDTO.getList();
    if (apiInfoDTOs == null) {
        apiInfoDTOs = new ArrayList<>();
        apiListDTO.setList(apiInfoDTOs);
    }

    //add the required range of objects to be returned
    int start = offset < apiList.size() && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = offset + limit - 1 <= apiList.size() - 1 ? offset + limit - 1 : apiList.size() - 1;
    for (int i = start; i <= end; i++) {
        apiInfoDTOs.add(fromAPIToInfoDTO(apiList.get(i)));
    }
    apiListDTO.setCount(apiInfoDTOs.size());
    return apiListDTO;
}
 
Example #4
Source File: 103335311.java    From docs-apim with Apache License 2.0 6 votes vote down vote up
/**
 * The method to publish API to external WSO2 Store
 * @param api      API
 * @param store    Store
 * @return   published/not
 */

public boolean publishToStore(API api,APIStore store) throws APIManagementException {
    boolean published = 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){  //First try to login to store
        boolean added = addAPIToStore(api,store.getEndpoint(), store.getUsername(), httpContext,store.getDisplayName());
        if (added) {   //If API creation success,then try publishing the API
            published = publishAPIToStore(api.getId(), store.getEndpoint(), store.getUsername(), httpContext,store.getDisplayName());
        }
        logoutFromExternalStore(store, httpContext);
    }
    }
    return published;
}
 
Example #5
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTopRatedAPIs() throws APIManagementException, RegistryException {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact artifact = Mockito.mock(GenericArtifact.class);
    GenericArtifact[] genericArtifacts = new GenericArtifact[]{artifact};
    Mockito.when(artifactManager.getAllGenericArtifacts()).thenReturn(genericArtifacts);
    Mockito.when(artifact.getAttribute(Mockito.anyString())).thenReturn("PUBLISHED");
    Mockito.when(artifact.getPath()).thenReturn("testPath");

    Mockito.when(userRegistry.getAverageRating("testPath")).thenReturn((float)20.0);
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId1);
    Mockito.when(APIUtil.getAPI(artifact, userRegistry)).thenReturn(api);
    assertNotNull(apiConsumer.getTopRatedAPIs(10));
}
 
Example #6
Source File: EndpointBckConfigContextTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testEndpointBckConfigContext() throws Exception {
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    String url = "http://maps.googleapis.com/maps/api/geocode/json?address=Colombo";
    api.setUrl(url);
    api.setSandboxUrl(url);
    ConfigContext configcontext = new APIConfigContext(api);
    EndpointBckConfigContext endpointBckConfigContext = new EndpointBckConfigContext(configcontext, api);
    Assert.assertTrue(api.getEndpointConfig().contains(url));
    //setting an empty string as the endpoint config and checking the value which is returned
    api.setEndpointConfig("");
    String endpoint_config = "{\"production_endpoints\":{\"url\":\"" + api.getUrl() + "\", \"config\":null}," +
            "\"sandbox_endpoint\":{\"url\":\"" + api.getSandboxUrl() + "\"," +
            "\"config\":null},\"endpoint_type\":\"http\"}";
    EndpointBckConfigContext secondEndpointBckConfigContext = new EndpointBckConfigContext(configcontext, api);
    Assert.assertTrue(api.getEndpointConfig().contains(endpoint_config));
    //setting null as the endpoint config and checking the value which is returned
    api.setEndpointConfig(null);
    EndpointBckConfigContext thirdEndpointBckConfigContext = new EndpointBckConfigContext(configcontext, api);
    Assert.assertTrue(api.getEndpointConfig().contains(endpoint_config));
}
 
Example #7
Source File: ResponseCacheConfigContextTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponseCacheConfigContext() throws Exception {
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setResponseCache(APIConstants.DISABLED);
    ConfigContext configcontext = new APIConfigContext(api);
    ResponseCacheConfigContext responseCacheConfigContext = new ResponseCacheConfigContext(configcontext, api);
    Assert.assertFalse((Boolean) responseCacheConfigContext.getContext().get("responseCacheEnabled"));

    api.setResponseCache(APIConstants.ENABLED);
    api.setCacheTimeout(100);
    responseCacheConfigContext = new ResponseCacheConfigContext(configcontext, api);
    Assert.assertTrue((Boolean) responseCacheConfigContext.getContext().get("responseCacheEnabled"));
    Assert.assertEquals(100, responseCacheConfigContext.getContext().get("responseCacheTimeOut"));
}
 
Example #8
Source File: SearchResultMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get API result representation for content search
 *
 * @param api API
 * @return APISearchResultDTO
 */
public static APISearchResultDTO fromAPIToAPIResultDTO(API api) {

    APISearchResultDTO apiResultDTO = new APISearchResultDTO();
    apiResultDTO.setId(api.getUUID());
    APIIdentifier apiId = api.getId();
    apiResultDTO.setName(apiId.getApiName());
    apiResultDTO.setVersion(apiId.getVersion());
    apiResultDTO.setProvider(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
    String context = api.getContextTemplate();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    apiResultDTO.setContext(context);
    apiResultDTO.setType(SearchResultDTO.TypeEnum.API);
    apiResultDTO.setTransportType(api.getType());
    apiResultDTO.setDescription(api.getDescription());
    apiResultDTO.setStatus(api.getStatus());
    apiResultDTO.setThumbnailUri(api.getThumbnailUrl());
    return apiResultDTO;
}
 
Example #9
Source File: SearchResultMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get Document result representation for content search
 *
 * @param document Api Document
 * @return DocumentSearchResultDTO
 */
public static DocumentSearchResultDTO fromDocumentationToDocumentResultDTO(Documentation document, API api) {

    DocumentSearchResultDTO docResultDTO = new DocumentSearchResultDTO();
    docResultDTO.setId(document.getId());
    docResultDTO.setName(document.getName());
    docResultDTO.setDocType(DocumentSearchResultDTO.DocTypeEnum.valueOf(document.getType().toString()));
    docResultDTO.setType(SearchResultDTO.TypeEnum.DOC);
    docResultDTO.setSummary(document.getSummary());
    docResultDTO.associatedType(APIConstants.AuditLogConstants.API);
    docResultDTO.setVisibility(DocumentSearchResultDTO.VisibilityEnum.valueOf(document.getVisibility().toString()));
    docResultDTO.setSourceType(DocumentSearchResultDTO.SourceTypeEnum.valueOf(document.getSourceType().toString()));
    docResultDTO.setOtherTypeName(document.getOtherTypeName());
    APIIdentifier apiId = api.getId();
    docResultDTO.setApiName(apiId.getApiName());
    docResultDTO.setApiVersion(apiId.getVersion());
    docResultDTO.setApiProvider(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
    docResultDTO.setApiUUID(api.getUUID());
    return docResultDTO;
}
 
Example #10
Source File: AlertsMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get a map of API name, version list. This is used to filter the retrieved alert configurations as there can be
 * api visibility restrictions.
 * @return A map with [api name, version list]
 * */
public static Map<String, List<String>> getAllowedAPIInfo() throws APIManagementException {
    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    List<API> allowedAPIs = apiProvider.getAllAPIs();
    Map<String, List<String>> allowedAPINameVersionMap = new HashMap<>();

    for (API api : allowedAPIs) {
        List<String> versions;
        APIIdentifier identifier = api.getId();
        if (allowedAPINameVersionMap.containsKey(identifier.getApiName())) {
            versions = allowedAPINameVersionMap.get(identifier.getApiName());
            versions.add(identifier.getVersion());
            allowedAPINameVersionMap.put(identifier.getApiName(), versions);
        } else {
            versions = new ArrayList<>();
            versions.add(identifier.getVersion());
            allowedAPINameVersionMap.put(identifier.getApiName(), versions);
        }
    }
    return allowedAPINameVersionMap;
}
 
Example #11
Source File: DefaultMonetizationImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {

    monetizationImpl = Mockito.mock(DefaultMonetizationImpl.class);
    subPolicy = Mockito.mock(SubscriptionPolicy.class);
    api = Mockito.mock(API.class);
    apiProvider = Mockito.mock(APIProvider.class);
    monetizationUsagePublishInfo = Mockito.mock(MonetizationUsagePublishInfo.class);
    Mockito.when(monetizationImpl.createBillingPlan(subPolicy)).thenReturn(true);
    Mockito.when(monetizationImpl.updateBillingPlan(subPolicy)).thenReturn(true);
    Mockito.when(monetizationImpl.deleteBillingPlan(subPolicy)).thenReturn(true);
    Mockito.when(monetizationImpl.enableMonetization(tenantDomain, api, dataMap)).thenReturn(true);
    Mockito.when(monetizationImpl.disableMonetization(tenantDomain, api, dataMap)).thenReturn(true);
    Mockito.when(monetizationImpl.getMonetizedPoliciesToPlanMapping(api)).thenReturn(dataMap);
    Mockito.when(monetizationImpl.getCurrentUsageForSubscription(subscriptionUUID, apiProvider)).thenReturn(dataMap);
    Mockito.when(monetizationImpl.getTotalRevenue(api, apiProvider)).thenReturn(dataMap);
    Mockito.when(monetizationImpl.publishMonetizationUsageRecords(monetizationUsagePublishInfo)).thenReturn(true);
}
 
Example #12
Source File: 103335311.java    From docs-apim with Apache License 2.0 6 votes vote down vote up
public boolean updateToStore(API api, APIStore store) throws APIManagementException {
	boolean updated = 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) {
    	updated = updateWSO2Store(api, store.getUsername(), store.getEndpoint(), httpContext,store.getDisplayName());
    	logoutFromExternalStore(store, httpContext);
    }
    return updated;
    }
}
 
Example #13
Source File: APIGatewayManager.java    From carbon-apimgt with 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 #14
Source File: WSDL11ProcessorImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Update the endpoint information of the WSDL (WSDL archive scenario) when an API and the environment details are
 * provided
 *
 * @param api API
 * @param environmentName name of the gateway environment
 * @param environmentType type of the gateway environment
 * @throws APIMgtWSDLException when error occurred while updating the endpoints
 */
private void updateEndpointsOfWSDLArchive(API api, String environmentName, String environmentType)
        throws APIMgtWSDLException {
    for (Map.Entry<String, Definition> entry : pathToDefinitionMap.entrySet()) {
        Definition definition = entry.getValue();
        if (log.isDebugEnabled()) {
            log.debug("Updating endpoints of WSDL: " + entry.getKey());
        }
        updateEndpointsOfSingleWSDL(api, environmentName, environmentType, definition);
        if (log.isDebugEnabled()) {
            log.debug("Successfully updated endpoints of WSDL: " + entry.getKey());
        }
        try (FileOutputStream wsdlFileOutputStream = new FileOutputStream(new File(entry.getKey()))) {
            WSDLWriter writer = getWsdlFactoryInstance().newWSDLWriter();
            writer.writeWSDL(definition, wsdlFileOutputStream);
        } catch (IOException | WSDLException e) {
            throw new APIMgtWSDLException("Failed to create WSDL archive for API:" + api.getId().getName() + ":"
                    + api.getId().getVersion() + " for environment " + environmentName, e,
                    ExceptionCodes.ERROR_WHILE_CREATING_WSDL_ARCHIVE);
        }
    }
}
 
Example #15
Source File: APIAPIProductNameComparator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public int compare(Object o1, Object o2) {
    Identifier identifier1;
    Identifier identifier2;

    if (o1 instanceof API) {
        identifier1 = ((API) o1).getId();
    } else {
        identifier1 = ((APIProduct) o1).getId();
    }

    if (o2 instanceof API) {
        identifier2 = ((API) o2).getId();
    } else {
        identifier2 = ((APIProduct) o2).getId();
    }

    Provider provider = new Provider(identifier1.getProviderName(), identifier2.getProviderName());
    Name name = new Name(identifier1.getName(), identifier2.getName());
    Version version = new Version(identifier1.getVersion(), identifier2.getVersion());

    return compareFields(provider, name, version);
}
 
Example #16
Source File: APIMWSDLReader.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private void setServiceDefinitionForWSDL2(org.apache.woden.wsdl20.Description definition, API api)
        throws APIManagementException {
    org.apache.woden.wsdl20.Service[] serviceMap = definition.getServices();
    // URL addressURI;
    try {
        for (org.apache.woden.wsdl20.Service svc : serviceMap) {
            Endpoint[] portMap = svc.getEndpoints();
            for (Endpoint endpoint : portMap) {
                EndpointElement element = endpoint.toElement();
                // addressURI = endpoint.getAddress().toURL();
                // if (addressURI == null) {
                //    break;
                // } else {
                String endpointTransport = determineURLTransport(endpoint.getAddress().getScheme(),
                                                                 api.getTransports());
                setAddressUrl(element, new URI(APIUtil.getGatewayendpoint(endpointTransport) +
                                               api.getContext() + '/' + api.getId().getVersion()));
                //}
            }
        }
    } catch (Exception e) {
        String errorMsg = "Error occurred while getting the wsdl address location";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e);
    }
}
 
Example #17
Source File: APIMgtDAOTest.java    From carbon-apimgt with 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 #18
Source File: APIConsumerImplTest.java    From carbon-apimgt with 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 #19
Source File: APIExecutorTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithDeprecated() throws Exception {
    Mockito.when(genericArtifact.isLCItemChecked(0, APIConstants.API_LIFE_CYCLE)).thenReturn(true);
    List<API> apiList = new ArrayList<API>();
    APIIdentifier apiIdTemp = Mockito.mock(APIIdentifier.class);

    Mockito.when(apiIdTemp.getProviderName()).thenReturn(USER_NAME);
    Mockito.when(apiIdTemp.getVersion()).thenReturn("1.0.0");
    Mockito.when(apiIdTemp.getApiName()).thenReturn(API_NAME);
    API apiTemp = new API(apiIdTemp);

    apiTemp.setStatus(APIConstants.PUBLISHED);
    apiList.add(apiTemp);
    Mockito.when(apiProvider.getAPIsByProvider(USER_NAME)).thenReturn(apiList);

    APIExecutor apiExecutor = new APIExecutor();
    boolean isExecuted = apiExecutor.execute(requestContext, "CREATED", "PUBLISHED");
    Assert.assertTrue(isExecuted);
}
 
Example #20
Source File: APIConfigContextTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetContext() throws Exception {
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.BLOCKED);
    api.setContextTemplate("/");
    APIConfigContext configContext = new APIConfigContext(api);
    boolean isBlocked = (Boolean) configContext.getContext().get("apiIsBlocked");
    Assert.assertTrue(isBlocked);
}
 
Example #21
Source File: APIMgtDAOTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddAndGetApi() throws Exception{
    APIIdentifier apiIdentifier = new APIIdentifier("testAddAndGetApi",
            "testAddAndGetApi", "1.0.0");
    API api = new API(apiIdentifier);
    api.setContext("/testAddAndGetApi");
    api.setContextTemplate("/testAddAndGetApi/{version}");
    api.setUriTemplates(getUriTemplateSet());
    api.setScopes(getScopes());
    api.setStatus(APIConstants.PUBLISHED);
    api.setAsDefaultVersion(true);
    int apiID = apiMgtDAO.addAPI(api, -1234);
    apiMgtDAO.addURITemplates(apiID, api, -1234);
    apiMgtDAO.updateAPI(api);
    apiMgtDAO.updateURITemplates(api, -1234);
    Set<APIStore> apiStoreSet = new HashSet<APIStore>();
    APIStore apiStore = new APIStore();
    apiStore.setDisplayName("wso2");
    apiStore.setEndpoint("http://localhost:9433/store");
    apiStore.setName("wso2");
    apiStore.setType("wso2");
    apiStoreSet.add(apiStore);
    apiMgtDAO.addExternalAPIStoresDetails(apiIdentifier,apiStoreSet);
    assertTrue(apiMgtDAO.getExternalAPIStoresDetails(apiIdentifier).size()>0);
    apiMgtDAO.deleteExternalAPIStoresDetails(apiIdentifier, apiStoreSet);
    apiMgtDAO.updateExternalAPIStoresDetails(apiIdentifier, Collections.<APIStore>emptySet());
    assertTrue(apiMgtDAO.getExternalAPIStoresDetails(apiIdentifier).size()==0);
    apiMgtDAO.deleteAPI(apiIdentifier);
}
 
Example #22
Source File: APIGatewayAdminClientTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetSecureVaultProperty() throws Exception {

    PowerMockito.whenNew(APIGatewayAdminStub.class)
            .withArguments(Mockito.any(ConfigurationContext.class), Mockito.anyString())
            .thenReturn(apiGatewayAdminStub);
    Mockito.when(apiGatewayAdminStub.doEncryption(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).
            thenReturn("");
    APIGatewayAdminClient client = new APIGatewayAdminClient(environment);
    APIIdentifier identifier = new APIIdentifier("P1_API1_v1.0.0");
    API api = new API(identifier);
    client.setSecureVaultProperty(api, null);
    Mockito.verify(apiGatewayAdminStub, times(1))
            .doEncryption(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
}
 
Example #23
Source File: APIVersionComparator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(API api1, API api2) {
    // In tenant mode, we could have same api published by two tenants to public store. So we need to check the
    // provider as well.
    if (api1.getId().getProviderName().equals(api2.getId().getProviderName()) &&
            api1.getId().getApiName().equals(api2.getId().getApiName())) {
        return stringComparator.compare(api1.getId().getVersion(), api2.getId().getVersion());
    } else {
        APINameComparator apiNameComparator = new APINameComparator();
        return apiNameComparator.compare(api1, api2);
    }

}
 
Example #24
Source File: APIGatewayManagerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test public void testFailureWhilePublishingAPIUpdateToGateway() throws Exception {
    API api = new API(apiIdentifier);
    api.setType("HTTP");
    api.setAsPublishedDefaultVersion(true);
    api.setImplementation("ENDPOINT");
    api.setEndpointConfig(prodEndpointConfig);
    api.setInSequence(inSequenceName);
    api.setAsDefaultVersion(true);
    api.setSwaggerDefinition(swaggerDefinition);
    api.setUUID(apiUUId);
    APITemplateBuilder apiTemplateBuilder = new APITemplateBuilderImpl(api);
    Set<String> environments = new HashSet<String>();
    environments.add(prodEnvironmentName);
    environments.add(null);
    OMElement inSequence = AXIOMUtil.stringToOM(testSequenceDefinition);
    api.setEnvironments(environments);
    Mockito.when(apiGatewayAdminClient.getApi(tenantDomain, apiIdentifier)).thenReturn(apiData);
    PowerMockito.when(APIUtil.getCustomSequence(inSequenceName, tenantID, "in", api.getId()))
            .thenReturn(inSequence);
    PowerMockito.when(APIUtil.isProductionEndpointsExists(Mockito.anyString())).thenReturn(true);
    PowerMockito.when(APIUtil.isSequenceDefined(Mockito.anyString())).thenReturn(true);
    //Test API deployment failure when custom sequence update failed
    Map<String, String> failedEnvironmentsMap = gatewayManager
            .publishToGateway(api, apiTemplateBuilder, tenantDomain);
    Assert.assertEquals(failedEnvironmentsMap.size(), 1);
    Assert.assertTrue(failedEnvironmentsMap.keySet().contains(prodEnvironmentName));
}
 
Example #25
Source File: APIMWSDLReader.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
    * Update WSDL 1.0 service definitions saved in registry
    *
    * @param wsdl 	byte array of registry content
 * @param api 	API object
 * @return 		the OMElemnt of the new WSDL content
 * @throws APIManagementException
    */
public OMElement updateWSDL(byte[] wsdl, API api) throws APIManagementException {

	try {
		// Generate wsdl document from registry data
		WSDLReader wsdlReader = getWsdlFactoryInstance().newWSDLReader();
		// switch off the verbose mode
		wsdlReader.setFeature(JAVAX_WSDL_VERBOSE_MODE, false);
		wsdlReader.setFeature(JAVAX_WSDL_IMPORT_DOCUMENTS, false);

		if (wsdlReader instanceof WSDLReaderImpl) {
		    ((WSDLReaderImpl) wsdlReader).setIgnoreSchemaContent(true);
		}

		Definition wsdlDefinition = wsdlReader.readWSDL(null, getSecuredParsedDocumentFromContent(wsdl));

		// Update transports
		setServiceDefinition(wsdlDefinition, api);

		WSDLWriter writer = getWsdlFactoryInstance().newWSDLWriter();
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		writer.writeWSDL(wsdlDefinition, byteArrayOutputStream);
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( byteArrayOutputStream.toByteArray());
		return APIUtil.buildOMElement(byteArrayInputStream);

	} catch (Exception e) {
		String msg = " Error occurs when updating WSDL ";
		log.error(msg);
		throw new APIManagementException(msg, e);
	}
}
 
Example #26
Source File: APIGatewayAdminClientTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test(expected = APIManagementException.class)
public void testSetSecureVaultPropertyException() throws Exception {

    PowerMockito.whenNew(APIGatewayAdminStub.class)
            .withArguments(Mockito.any(ConfigurationContext.class), Mockito.anyString())
            .thenReturn(apiGatewayAdminStub);
    Mockito.when(apiGatewayAdminStub.doEncryption(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).
            thenThrow(RemoteException.class);
    APIGatewayAdminClient client = new APIGatewayAdminClient(environment);
    APIIdentifier identifier = new APIIdentifier("P1_API1_v1.0.0");
    API api = new API(identifier);
    client.setSecureVaultProperty(api, null);
}
 
Example #27
Source File: APINameComparator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public int compare(API api1, API api2) {
    if (api1.getId().getProviderName().equalsIgnoreCase(api2.getId().getProviderName())) {
        if (api1.getId().getApiName().equals(api2.getId().getApiName())) {
            //only compare version
            return api1.getId().getVersion().compareToIgnoreCase(api2.getId().getVersion());
        } else {
            //only compare API name
            return api1.getId().getApiName().compareToIgnoreCase(api2.getId().getApiName());
        }
    } else {
        //only compare provider name
        return api1.getId().getProviderName().compareToIgnoreCase(api2.getId().getProviderName());
    }
}
 
Example #28
Source File: SearchResultMappingUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a API or Product into a DTO
 *
 * @param api api or Product
 * @return APISearchResultDTO
 */
public static APISearchResultDTO fromAPIToAPIResultDTO(Object api) {
    if (api instanceof APIProduct) {
        return fromAPIToAPIResultDTO((APIProduct) api);
    }
    return fromAPIToAPIResultDTO((API) api);
}
 
Example #29
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method saves api definition json in the registry
 *
 * @param api               API to be saved
 * @param apiDefinitionJSON API definition as JSON string
 * @param registry          user registry
 * @throws APIManagementException
 */
public static void saveAPIDefinition(API api, String apiDefinitionJSON, Registry registry)
        throws APIManagementException {
    String apiName = api.getId().getApiName();
    String apiVersion = api.getId().getVersion();
    String apiProviderName = api.getId().getProviderName();

    try {
        String resourcePath = APIUtil.getOpenAPIDefinitionFilePath(apiName, apiVersion, apiProviderName);
        resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
        Resource resource;
        if (!registry.resourceExists(resourcePath)) {
            resource = registry.newResource();
        } else {
            resource = registry.get(resourcePath);
        }
        resource.setContent(apiDefinitionJSON);
        resource.setMediaType("application/json");
        registry.put(resourcePath, resource);

        String[] visibleRoles = null;
        if (api.getVisibleRoles() != null) {
            visibleRoles = api.getVisibleRoles().split(",");
        }

        //Need to set anonymous if the visibility is public
        APIUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
        APIUtil.setResourcePermissions(apiProviderName, api.getVisibility(), visibleRoles, resourcePath);

    } catch (RegistryException e) {
        handleException("Error while adding Swagger Definition for " + apiName + '-' + apiVersion, e);
    }
}
 
Example #30
Source File: AbstractAPIManagerWrapper.java    From carbon-apimgt with 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);
    }
}