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();
}
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);
}
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;
}
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;
}
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;
}
Aggregations