Search in sources :

Example 61 with Resource

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

the class APIStoreImpl method addCompositeApiFromDefinition.

/**
 * {@inheritDoc}
 */
@Override
public String addCompositeApiFromDefinition(String swaggerResourceUrl) throws APIManagementException {
    try {
        URL url = new URL(swaggerResourceUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod(APIMgtConstants.HTTP_GET);
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), StandardCharsets.UTF_8);
            CompositeAPI.Builder apiBuilder = apiDefinitionFromSwagger20.generateCompositeApiFromSwaggerResource(getUsername(), responseStr);
            apiBuilder.apiDefinition(responseStr);
            addCompositeApi(apiBuilder);
            return apiBuilder.getId();
        } else {
            throw new APIManagementException("Error while getting swagger resource from url : " + url, ExceptionCodes.API_DEFINITION_MALFORMED);
        }
    } catch (UnsupportedEncodingException e) {
        String msg = "Unsupported encoding exception while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (ProtocolException e) {
        String msg = "Protocol exception while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (MalformedURLException e) {
        String msg = "Malformed url while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (IOException e) {
        String msg = "Error while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    }
}
Also used : ProtocolException(java.net.ProtocolException) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL)

Example 62 with Resource

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

the class KubernetesGatewayImpl method createServiceResource.

/**
 * Create a service in cms
 *
 * @param serviceTemplate Service template as a String
 * @param serviceName     Name of the service
 * @throws ContainerBasedGatewayException if failed to create a service
 */
private void createServiceResource(String serviceTemplate, String serviceName) throws ContainerBasedGatewayException {
    HasMetadata resource = getResourcesFromTemplate(serviceTemplate);
    try {
        if (resource instanceof Service) {
            // check whether there are existing service already
            if (client.services().inNamespace(namespace).withName(serviceName).get() == null) {
                log.debug("Deploying in CMS type: {} and the Service resource definition: {} ", cmsType, serviceTemplate);
                Service service = (Service) resource;
                Service result = client.services().inNamespace(namespace).create(service);
                log.info("Created Service : " + result.getMetadata().getName() + " in Namespace : " + result.getMetadata().getNamespace() + " in " + cmsType);
            } else {
                log.info("There exist a service with the same name in " + cmsType + ". Service name : " + serviceName);
            }
        } else {
            throw new ContainerBasedGatewayException("Loaded Resource is not a Service in " + cmsType + "! " + resource, ExceptionCodes.LOADED_RESOURCE_DEFINITION_IS_NOT_VALID);
        }
    } catch (KubernetesClientException e) {
        throw new ContainerBasedGatewayException("Error while creating container based gateway service in " + cmsType + "!", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Service(io.fabric8.kubernetes.api.model.Service) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 63 with Resource

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

the class ApiApiServiceImpl method apiCountOverTimeGet.

/**
 * Get list of API count information
 *
 * @param startTime Filter for start time stamp
 * @param endTime   Filter for end time stamp
 * @param createdBy Filter for created user
 * @param request   MSF4J request
 * @return API Count information
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apiCountOverTimeGet(String startTime, String endTime, String createdBy, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        log.debug("Retrieving APIs created over time. [From: {}  To: {} Created By: {}]", startTime, endTime, createdBy);
        Analyzer analyzer = RestApiUtil.getAnalyzer(username);
        ZoneId requestTimezone = RestApiUtil.getRequestTimeZone(startTime);
        List<APICount> apiCountList = analyzer.getAPICount(fromISO8601ToInstant(startTime), fromISO8601ToInstant(endTime), createdBy);
        APICountListDTO apiCountListDTO = AnalyticsMappingUtil.fromAPICountToListDTO(apiCountList, requestTimezone);
        return Response.ok().entity(apiCountListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API created over time info";
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APICount(org.wso2.carbon.apimgt.core.models.analytics.APICount) ZoneId(java.time.ZoneId) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APICountListDTO(org.wso2.carbon.apimgt.rest.api.analytics.dto.APICountListDTO) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) Analyzer(org.wso2.carbon.apimgt.core.api.Analyzer)

Example 64 with Resource

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

the class PolicyExportManager method getApiPolicySiddhiApps.

/**
 * Get execution plan/ siddhi apps for custom policies.
 *
 * @param apiPolicies APIPolicy object list
 * @return Map<String, String> containing execution plan name and execution plans.
 * @throws APITemplateException If template generating fails
 */
private List<Map<String, String>> getApiPolicySiddhiApps(List<APIPolicy> apiPolicies) throws APITemplateException {
    if (log.isDebugEnabled()) {
        log.debug("Get execution plans for API policies.");
    }
    List<Map<String, String>> policies = new ArrayList<>();
    Map<String, String> siddhiApps = new HashMap<>();
    APIThrottlePolicyTemplateBuilder templateBuilder;
    for (APIPolicy apiPolicy : apiPolicies) {
        templateBuilder = new APIThrottlePolicyTemplateBuilder(apiPolicy);
        if (apiPolicy.getPipelines() != null) {
            siddhiApps = templateBuilder.getThrottlePolicyTemplateForPipelines();
        }
        siddhiApps.put(RESOURCE + apiPolicy.getPolicyName() + DEFAULT, templateBuilder.getThrottlePolicyTemplateForAPILevelDefaultCondition());
        policies.add(siddhiApps);
    }
    return policies;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APIThrottlePolicyTemplateBuilder(org.wso2.carbon.apimgt.core.template.APIThrottlePolicyTemplateBuilder) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) HashMap(java.util.HashMap) Map(java.util.Map)

Example 65 with Resource

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

the class ApisApiServiceImplTestCase method apisApiIdGatewayConfigGetTestCase.

@Test
public void apisApiIdGatewayConfigGetTestCase() throws Exception {
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIMgtAdminServiceImpl adminService = Mockito.mock(APIMgtAdminServiceImpl.class);
    String apiID = UUID.randomUUID().toString();
    String gatewayConfig = "package deployment.org.wso2.apim;\n" + "import ballerina.net.http;\n" + "\n" + "@http:BasePath(\"/aaa1\")\n" + "service aaa1_1489666767745 {\n" + "\n" + "    @http:GET\n" + "    @http:Path(\"/*\")\n" + "    resource get_star_ (message m) {\n" + "        http:ClientConnector productionEndpoint = create http:ClientConnector(getUrlFromKey" + "(\"aaa1_1.0.0__ep\"));\n   http:ClientConnector sandboxEndpoint = create http:ClientConnector" + "(getUrlFromKey(\"aaa1_1.0.0__ep\"));\n message response;\n string endpointType;\n string " + "productionType;\n \n \n      endpointType = \"production\";\n productionType = \"production\";\n" + "\n      if (endpointType == productionType) {\n" + "            response = http:ClientConnector.execute(productionEndpoint, \"get\", \"\", m);\n" + "        } else {\n" + "            response = http:ClientConnector.execute(sandboxEndpoint, \"get\", \"\", m);\n" + "        }\n" + "\n" + "        reply response;\n" + "    }\n" + "}";
    Mockito.when(adminService.getAPIGatewayServiceConfig(apiID)).thenReturn(gatewayConfig);
    APIManagerFactory instance = Mockito.mock(APIManagerFactory.class);
    PowerMockito.mockStatic(APIManagerFactory.class);
    PowerMockito.when(APIManagerFactory.getInstance()).thenReturn(instance);
    Mockito.when(instance.getAPIMgtAdminService()).thenReturn(adminService);
    Response response = apisApiService.apisApiIdGatewayConfigGet(apiID, null, getRequest());
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
Also used : Response(javax.ws.rs.core.Response) APIManagerFactory(org.wso2.carbon.apimgt.core.impl.APIManagerFactory) APIMgtAdminServiceImpl(org.wso2.carbon.apimgt.core.impl.APIMgtAdminServiceImpl) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)111 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)102 HashMap (java.util.HashMap)91 Test (org.testng.annotations.Test)64 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)59 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)56 HttpMessageDataStreamer (org.wso2.transport.http.netty.message.HttpMessageDataStreamer)53 BJSON (org.ballerinalang.model.values.BJSON)46 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)38 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)29 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)27 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)24 CharonException (org.wso2.charon3.core.exceptions.CharonException)24 IOException (java.io.IOException)23 Map (java.util.Map)20 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)20 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)17 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)17 ArrayList (java.util.ArrayList)15 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)15