Search in sources :

Example 51 with Collection

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

the class APIUtilTest method testGetMediationSequenceUuidOutSequence.

@Test
public void testGetMediationSequenceUuidOutSequence() 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_OUT;
    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, "out", apiIdentifier);
    Assert.assertEquals(expectedUUID, actualUUID);
    sampleSequence.close();
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Collection(org.wso2.carbon.registry.core.Collection) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) FileInputStream(java.io.FileInputStream) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 52 with Collection

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

the class APIManagerComponentPermissionsTest method testShouldAddApplicationPermissionsToRegistry.

@Test
public void testShouldAddApplicationPermissionsToRegistry() throws Exception {
    RealmConfiguration realmConfig = Mockito.mock(RealmConfiguration.class);
    Collection collection = Mockito.mock(Collection.class);
    Mockito.when(realm.getRealmConfiguration()).thenReturn(realmConfig);
    Mockito.when(realmConfig.getAdminUserName()).thenReturn(USER_NAME);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(false).thenReturn(true);
    Mockito.when(registry.newCollection()).thenReturn(collection);
    Mockito.when(registry.put(Mockito.anyString(), Mockito.any(Collection.class))).thenReturn("");
    APIManagerComponent apiManagerComponent = new APIManagerComponent();
    try {
        apiManagerComponent.activate(componentContext);
    } catch (Exception ex) {
        Assert.fail("Unexpected exception was thrown");
    }
    Assert.assertTrue(true);
    // Resource doesn't exists
    try {
        apiManagerComponent.activate(componentContext);
    } catch (Exception ex) {
        Assert.fail("Unexpected exception was thrown");
    }
    Assert.assertTrue(true);
}
Also used : RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) Collection(org.wso2.carbon.registry.core.Collection) UserStoreException(org.wso2.carbon.user.core.UserStoreException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 53 with Collection

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

the class ApisApiServiceImpl method createAuditApi.

/**
 * Send API Definition to Security Audit for the first time
 * @param collectionId Collection ID in which the Definition should be sent to
 * @param apiToken API Token to access Security Audit
 * @param apiIdentifier API Identifier object
 * @param apiDefinition API Definition of API
 * @param baseUrl Base URL to communicate with Security Audit
 * @param isDebugEnabled Boolean whether debug is enabled
 * @param organization Organization
 * @return String UUID of API in Security Audit
 * @throws IOException In the event of any problems in the request
 * @throws APIManagementException In the event of unexpected response
 * @throws ParseException In the event of any parse errors from the response
 */
private String createAuditApi(String collectionId, String apiToken, APIIdentifier apiIdentifier, String apiDefinition, String baseUrl, boolean isDebugEnabled, String organization) throws IOException, APIManagementException, ParseException {
    HttpURLConnection httpConn;
    OutputStream outputStream;
    PrintWriter writer;
    String auditUuid = null;
    URL url = new URL(baseUrl);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    // indicates POST method
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestProperty(APIConstants.HEADER_CONTENT_TYPE, APIConstants.MULTIPART_CONTENT_TYPE + APIConstants.MULTIPART_FORM_BOUNDARY);
    httpConn.setRequestProperty(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
    httpConn.setRequestProperty(APIConstants.HEADER_API_TOKEN, apiToken);
    httpConn.setRequestProperty(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);
    // Name property
    writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"name\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiIdentifier.getApiName()).append(APIConstants.MULTIPART_LINE_FEED);
    writer.flush();
    // Specfile property
    writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"specfile\"; filename=\"swagger.json\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.HEADER_CONTENT_TYPE + ": " + APIConstants.APPLICATION_JSON_MEDIA_TYPE).append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiDefinition).append(APIConstants.MULTIPART_LINE_FEED);
    writer.flush();
    // CollectionID property
    writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"cid\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(collectionId).append(APIConstants.MULTIPART_LINE_FEED);
    writer.flush();
    writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY + "--").append(APIConstants.MULTIPART_LINE_FEED);
    writer.close();
    // Checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        if (isDebugEnabled) {
            log.debug("HTTP status " + status);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
        String inputLine;
        StringBuilder responseString = new StringBuilder();
        while ((inputLine = reader.readLine()) != null) {
            responseString.append(inputLine);
        }
        reader.close();
        httpConn.disconnect();
        JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
        auditUuid = (String) ((JSONObject) responseJson.get(APIConstants.DESC)).get(APIConstants.ID);
        ApiMgtDAO.getInstance().addAuditApiMapping(apiIdentifier, auditUuid, organization);
    } else {
        if (httpConn.getErrorStream() != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuilder responseString = new StringBuilder();
            while ((inputLine = reader.readLine()) != null) {
                responseString.append(inputLine);
            }
            reader.close();
            httpConn.disconnect();
            JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
            String errorMessage = httpConn.getResponseMessage();
            if (responseJson.containsKey("message")) {
                errorMessage = (String) responseJson.get("message");
            }
            throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + errorMessage);
        } else {
            throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + httpConn.getResponseMessage());
        }
    }
    return auditUuid;
}
Also used : InputStreamReader(java.io.InputStreamReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) JSONParser(org.json.simple.parser.JSONParser) PrintWriter(java.io.PrintWriter)

Example 54 with Collection

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

the class EnvironmentMappingUtil method fromEnvironmentCollectionToDTO.

/**
 * Converts a List object of SubscribedAPIs into a DTO.
 *
 * @param environmentCollection a collection of Environment objects
 * @return EnvironmentListDTO object containing EnvironmentDTOs
 */
public static EnvironmentListDTO fromEnvironmentCollectionToDTO(Collection<Environment> environmentCollection) {
    EnvironmentListDTO environmentListDTO = new EnvironmentListDTO();
    List<EnvironmentDTO> environmentDTOs = environmentListDTO.getList();
    if (environmentDTOs == null) {
        environmentDTOs = new ArrayList<>();
        environmentListDTO.setList(environmentDTOs);
    }
    for (Environment environment : environmentCollection) {
        environmentDTOs.add(fromEnvironmentToDTO(environment));
    }
    environmentListDTO.setCount(environmentDTOs.size());
    return environmentListDTO;
}
Also used : EnvironmentListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.EnvironmentListDTO) EnvironmentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.EnvironmentDTO) ExternalEnvironment(org.wso2.carbon.apimgt.impl.ExternalEnvironment) Environment(org.wso2.carbon.apimgt.api.model.Environment)

Example 55 with Collection

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

the class ApisApiServiceImpl method getAuditReportOfAPI.

/**
 * Method to retrieve Security Audit Report
 * @param apiId API ID of the API
 * @param accept Accept header string
 * @param messageContext Message Context string
 * @return Response object of Security Audit
 */
@Override
public Response getAuditReportOfAPI(String apiId, String accept, MessageContext messageContext) {
    boolean isDebugEnabled = log.isDebugEnabled();
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        APIIdentifier apiIdentifier = api.getId();
        String apiDefinition = apiProvider.getOpenAPIDefinition(apiIdentifier, organization);
        // Get configuration file, retrieve API token and collection id
        JSONObject securityAuditPropertyObject = apiProvider.getSecurityAuditAttributesFromConfig(username);
        String apiToken = (String) securityAuditPropertyObject.get("apiToken");
        String collectionId = (String) securityAuditPropertyObject.get("collectionId");
        String baseUrl = (String) securityAuditPropertyObject.get("baseUrl");
        if (baseUrl == null) {
            baseUrl = APIConstants.BASE_AUDIT_URL;
        }
        // Retrieve the uuid from the database
        String auditUuid = ApiMgtDAO.getInstance().getAuditApiId(api.getUuid());
        if (auditUuid != null) {
            updateAuditApi(apiDefinition, apiToken, auditUuid, baseUrl, isDebugEnabled);
        } else {
            auditUuid = createAuditApi(collectionId, apiToken, apiIdentifier, apiDefinition, baseUrl, isDebugEnabled, organization);
        }
        // Logic for the HTTP request
        String getUrl = baseUrl + "/" + auditUuid + APIConstants.ASSESSMENT_REPORT;
        URL getReportUrl = new URL(getUrl);
        try (CloseableHttpClient getHttpClient = (CloseableHttpClient) APIUtil.getHttpClient(getReportUrl.getPort(), getReportUrl.getProtocol())) {
            HttpGet httpGet = new HttpGet(getUrl);
            // Set the header properties of the request
            httpGet.setHeader(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
            httpGet.setHeader(APIConstants.HEADER_API_TOKEN, apiToken);
            httpGet.setHeader(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
            // Code block for the processing of the response
            try (CloseableHttpResponse response = getHttpClient.execute(httpGet)) {
                if (isDebugEnabled) {
                    log.debug("HTTP status " + response.getStatusLine().getStatusCode());
                }
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
                    String inputLine;
                    StringBuilder responseString = new StringBuilder();
                    while ((inputLine = reader.readLine()) != null) {
                        responseString.append(inputLine);
                    }
                    reader.close();
                    JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
                    String report = responseJson.get(APIConstants.DATA).toString();
                    String grade = (String) ((JSONObject) ((JSONObject) responseJson.get(APIConstants.ATTR)).get(APIConstants.DATA)).get(APIConstants.GRADE);
                    Integer numErrors = Integer.valueOf((String) ((JSONObject) ((JSONObject) responseJson.get(APIConstants.ATTR)).get(APIConstants.DATA)).get(APIConstants.NUM_ERRORS));
                    String decodedReport = new String(Base64Utils.decode(report), StandardCharsets.UTF_8);
                    AuditReportDTO auditReportDTO = new AuditReportDTO();
                    auditReportDTO.setReport(decodedReport);
                    auditReportDTO.setGrade(grade);
                    auditReportDTO.setNumErrors(numErrors);
                    auditReportDTO.setExternalApiId(auditUuid);
                    return Response.ok().entity(auditReportDTO).build();
                }
            }
        }
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error occurred while getting " + "HttpClient instance", e, log);
    } catch (ParseException e) {
        RestApiUtil.handleInternalServerError("API Definition String " + "could not be parsed into JSONObject.", e, log);
    } catch (APIManagementException e) {
        String errorMessage = "Error while Auditing API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URL(java.net.URL) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) AuditReportDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AuditReportDTO)

Aggregations

Collection (org.wso2.carbon.registry.core.Collection)45 Resource (org.wso2.carbon.registry.core.Resource)39 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)26 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)25 Test (org.junit.Test)24 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)23 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)22 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)20 IOException (java.io.IOException)19 InputStream (java.io.InputStream)19 ArrayList (java.util.ArrayList)17 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)17 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)16 FileInputStream (java.io.FileInputStream)14 OMElement (org.apache.axiom.om.OMElement)13 StreamEvent (org.wso2.siddhi.core.event.stream.StreamEvent)13 Collection (java.util.Collection)11 CollectionImpl (org.wso2.carbon.registry.core.CollectionImpl)11 ResourceImpl (org.wso2.carbon.registry.core.ResourceImpl)11 File (java.io.File)10