use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.
the class FileBasedApiImportExportManager method decodeApiInformationFromDirectoryStructure.
/**
* Reads and decodes APIs and relevant information from the given set of paths
*
* @param apiArtifactsBasePath path to the directory with API related artifacts
* @param newApiProvider API newApiProvider to be updated
* @return Set of {@link APIDetails} objects
* @throws APIMgtEntityImportExportException if any error occurs while decoding the APIs
*/
public Set<APIDetails> decodeApiInformationFromDirectoryStructure(String apiArtifactsBasePath, String newApiProvider) throws APIMgtEntityImportExportException {
Set<String> apiDefinitionsRootDirectoryPaths = null;
try {
apiDefinitionsRootDirectoryPaths = APIFileUtils.getDirectoryList(apiArtifactsBasePath);
} catch (APIMgtDAOException e) {
String errorMsg = "Unable to find API definitions at: " + apiArtifactsBasePath;
log.error(errorMsg, e);
throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_IMPORT_ERROR);
}
if (apiDefinitionsRootDirectoryPaths.isEmpty()) {
try {
APIFileUtils.deleteDirectory(path);
} catch (APIMgtDAOException e) {
log.warn("Unable to remove directory " + path);
}
String errorMsg = "Unable to find API definitions at: " + apiArtifactsBasePath;
throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_IMPORT_ERROR);
}
Set<APIDetails> apiDetailsSet = new HashSet<>();
for (String apiDefinitionDirectoryPath : apiDefinitionsRootDirectoryPaths) {
File apiDefinitionFile = getFileFromPrefix(apiDefinitionDirectoryPath, APIMgtConstants.APIFileUtilConstants.API_DEFINITION_FILE_PREFIX);
File swaggerDefinitionFile = getFileFromPrefix(apiDefinitionDirectoryPath, APIMgtConstants.APIFileUtilConstants.SWAGGER_DEFINITION_FILE_PREFIX);
API api;
String swaggerDefinition, gatewayConfiguration;
Set<Endpoint> endpoints;
try {
api = getApiDefinitionFromExtractedArchive(apiDefinitionFile.getPath());
swaggerDefinition = getSwaggerDefinitionFromExtractedArchive(swaggerDefinitionFile.getPath());
gatewayConfiguration = getGatewayConfigurationFromExtractedArchive(apiDefinitionDirectoryPath + File.separator + APIMgtConstants.APIFileUtilConstants.GATEWAY_CONFIGURATION_DEFINITION_FILE);
endpoints = getEndpointsFromExtractedArchive(apiDefinitionDirectoryPath + File.separator + ENDPOINTS_ROOT_DIRECTORY, api.getName(), api.getVersion());
} catch (APIManagementException e) {
log.error("Error occurred while importing api from path: " + apiDefinitionDirectoryPath, e);
// skip this API
continue;
}
if (newApiProvider != null && !newApiProvider.isEmpty()) {
// update the newApiProvider
api = new API.APIBuilder(api).provider(newApiProvider).build();
}
String documentsRootDirectory = apiDefinitionDirectoryPath + File.separator + DOCUMENTS_ROOT_DIRECTORY;
Set<DocumentInfo> documentInfoSet = getDocumentInfoFromExtractedArchive(documentsRootDirectory, api.getName(), api.getVersion());
Set<DocumentContent> documentContents = new HashSet<>();
for (DocumentInfo aDocumentInfo : documentInfoSet) {
DocumentContent aDocumentContent = getDocumentContentFromExtractedArchive(aDocumentInfo, documentsRootDirectory + File.separator + aDocumentInfo.getId());
if (aDocumentContent != null) {
documentContents.add(aDocumentContent);
}
}
InputStream thumbnailStream = null;
try {
thumbnailStream = APIFileUtils.getThumbnailImage(apiDefinitionDirectoryPath + File.separator + APIMgtConstants.APIFileUtilConstants.THUMBNAIL_FILE_NAME);
} catch (APIMgtDAOException e) {
// log and ignore
log.error("Error occurred while reading thumbnail image.", e);
}
APIDetails apiDetails = new APIDetails(api, swaggerDefinition);
apiDetails.setGatewayConfiguration(gatewayConfiguration);
apiDetails.setEndpoints(endpoints);
if (!documentInfoSet.isEmpty()) {
apiDetails.addDocumentInformation(documentInfoSet);
}
if (!documentContents.isEmpty()) {
apiDetails.addDocumentContents(documentContents);
}
if (thumbnailStream != null) {
apiDetails.setThumbnailStream(thumbnailStream);
}
apiDetailsSet.add(apiDetails);
}
return apiDetailsSet;
}
use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.
the class FileBasedApiImportExportManager method getEndpointsFromExtractedArchive.
private Set<Endpoint> getEndpointsFromExtractedArchive(String endpointLocation, String apiName, String version) throws APIMgtEntityImportExportException {
File endpointsRootDirectory = new File(endpointLocation);
Set<Endpoint> endpoints = new HashSet<>();
if (endpointsRootDirectory.isDirectory()) {
File[] endpointFiles = endpointsRootDirectory.listFiles(File::isFile);
if (endpointFiles == null) {
// no endpoints in the given location, can't continue
String errorMsg = "No endpoints found at " + endpointsRootDirectory;
log.error(errorMsg);
throw new APIMgtEntityImportExportException(errorMsg);
}
Gson gson = new GsonBuilder().create();
for (File endpointFile : endpointFiles) {
// read everything
String content = null;
try {
content = APIFileUtils.readFileContentAsText(endpointFile.getPath());
} catch (APIMgtDAOException e) {
String errorMsg = "Unable to read endpoints from " + endpointFile.getPath();
log.error(errorMsg, e);
throw new APIMgtEntityImportExportException(errorMsg, e);
}
endpoints.add(gson.fromJson(content, Endpoint.class));
}
}
return endpoints;
}
use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.
the class ApiImportExportManager method addAPIDetails.
/**
* Adds the API details
*
* @param apiDetails {@link APIDetails} instance
* @throws APIManagementException if an error occurs while adding API details
*/
public void addAPIDetails(APIDetails apiDetails) throws APIManagementException {
// update everything
String swaggerDefinition = apiDetails.getSwaggerDefinition();
String gatewayConfig = apiDetails.getGatewayConfiguration();
Map<String, Endpoint> endpointTypeToIdMap = apiDetails.getApi().getEndpoint();
Map<String, UriTemplate> uriTemplateMap = apiDetails.getApi().getUriTemplates();
// endpoints
for (Endpoint endpoint : apiDetails.getEndpoints()) {
try {
Endpoint existingEndpoint = apiPublisher.getEndpointByName(endpoint.getName());
String endpointId;
if (existingEndpoint == null) {
// no endpoint by that name, add it
endpointId = apiPublisher.addEndpoint(endpoint);
} else {
endpointId = existingEndpoint.getId();
if (log.isDebugEnabled()) {
log.debug("Endpoint with id " + endpoint.getId() + " already exists, not adding again");
}
// endpoint with same name exists, add to endpointTypeToIdMap
// endpointTypeToIdMap.put(endpoint.getType(), existingEndpoint.getId());
}
endpointTypeToIdMap.forEach((String k, Endpoint v) -> {
if (endpoint.getName().equals(v.getName())) {
Endpoint replacedEndpoint = new Endpoint.Builder(v).id(endpointId).build();
endpointTypeToIdMap.replace(k, replacedEndpoint);
}
});
uriTemplateMap.forEach(((String templateId, UriTemplate uriTemplate) -> {
UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(uriTemplate);
Map<String, Endpoint> uriEndpointMap = uriTemplateBuilder.getEndpoint();
uriEndpointMap.forEach((String type, Endpoint endpoint1) -> {
if (endpoint.getName().equals(endpoint1.getName())) {
Endpoint replacedEndpoint = new Endpoint.Builder(endpoint1).id(endpointId).build();
uriEndpointMap.replace(type, replacedEndpoint);
}
});
uriTemplateMap.replace(templateId, uriTemplateBuilder.endpoint(uriEndpointMap).build());
}));
} catch (APIManagementException e) {
// skip adding this API; log and continue
log.error("Error while adding the endpoint with id: " + endpoint.getId() + ", type: " + endpoint.getType() + " for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion());
}
}
API.APIBuilder apiBuilder = new API.APIBuilder(apiDetails.getApi());
apiPublisher.addAPI(apiBuilder.apiDefinition(swaggerDefinition).gatewayConfig(gatewayConfig).endpoint(endpointTypeToIdMap).uriTemplates(uriTemplateMap));
// docs
try {
Set<DocumentInfo> documentInfo = apiDetails.getAllDocumentInformation();
for (DocumentInfo aDocInfo : documentInfo) {
apiPublisher.addDocumentationInfo(apiDetails.getApi().getId(), aDocInfo);
}
for (DocumentContent aDocContent : apiDetails.getDocumentContents()) {
// add documentation
if (aDocContent.getDocumentInfo().getSourceType().equals(DocumentInfo.SourceType.FILE)) {
apiPublisher.uploadDocumentationFile(aDocContent.getDocumentInfo().getId(), aDocContent.getFileContent(), URLConnection.guessContentTypeFromStream(aDocContent.getFileContent()));
} else if (aDocContent.getDocumentInfo().getSourceType().equals(DocumentInfo.SourceType.INLINE)) {
apiPublisher.addDocumentationContent(aDocContent.getDocumentInfo().getId(), aDocContent.getInlineContent());
}
}
} catch (APIManagementException e) {
// no need to throw, log and continue
log.error("Error while adding Document details for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
} catch (IOException e) {
// no need to throw, log and continue
log.error("Error while retrieving content type of the File documentation of API : " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
}
// add thumbnail
try {
apiPublisher.saveThumbnailImage(apiDetails.getApi().getId(), apiDetails.getThumbnailStream(), "thumbnail");
} catch (APIManagementException e) {
// no need to throw, log and continue
log.error("Error while adding thumbnail for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
}
}
use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.
the class SampleTestObjectCreator method createDefaultAPI.
public static API.APIBuilder createDefaultAPI() {
Set<String> transport = new HashSet<>();
transport.add(HTTP);
transport.add(HTTPS);
Set<String> tags = new HashSet<>();
tags.add(TAG_CLIMATE);
Set<Policy> policies = new HashSet<>();
policies.add(goldSubscriptionPolicy);
policies.add(silverSubscriptionPolicy);
policies.add(bronzeSubscriptionPolicy);
BusinessInformation businessInformation = new BusinessInformation();
businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
Set<String> visibleRoles = new HashSet<>();
visibleRoles.add("testRple");
List<String> labels = new ArrayList<>();
labels.add("testLabel");
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setEnabled(true);
corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowOrigins(Arrays.asList("*"));
Map<String, Endpoint> endpointMap = new HashMap<>();
endpointMap.put("TestEndpoint", createMockEndpoint());
API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
Map map = new HashMap();
map.put(DEVELOPER_ROLE_ID, 6);
map.put(ADMIN_ROLE_ID, 15);
apiBuilder.permissionMap(map);
return apiBuilder;
}
use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.
the class SampleTestObjectCreator method createUniqueAPI.
/**
* Create an unique API.
*
* @return APIBuilder with unique API details
*/
public static API.APIBuilder createUniqueAPI() {
Set<String> transport = new HashSet<>();
transport.add(HTTP);
Set<String> tags = new HashSet<>();
tags.add(TAG_FOOD);
tags.add(TAG_BEVERAGE);
Set<Policy> policies = new HashSet<>();
policies.add(silverSubscriptionPolicy);
policies.add(bronzeSubscriptionPolicy);
BusinessInformation businessInformation = new BusinessInformation();
businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
businessInformation.setTechnicalOwner(NAME_BUSINESS_OWNER_2);
businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_2);
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setEnabled(true);
corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowOrigins(Arrays.asList("*"));
String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\"]}]";
Map permissionMap = new HashMap();
permissionMap.put(DEVELOPER_ROLE_ID, 6);
permissionMap.put(ADMIN_ROLE_ID, 7);
API.APIBuilder apiBuilder = new API.APIBuilder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), API_VERSION).id(UUID.randomUUID().toString()).context(UUID.randomUUID().toString()).description("Get Food & Beverage Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).endpoint(Collections.emptyMap()).wsdlUri(SAMPLE_API_WSDL).isResponseCachingEnabled(true).cacheTimeout(120).isDefaultVersion(true).apiPolicy(goldApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.RESTRICTED).visibleRoles(new HashSet<>(Arrays.asList(CUSTOMER_ROLE, MANAGER_ROLE, EMPLOYEE_ROLE))).businessInformation(businessInformation).corsConfiguration(corsConfiguration).apiPermission(permissionJson).permissionMap(permissionMap).createdTime(LocalDateTime.now()).createdBy(API_CREATOR).uriTemplates(Collections.emptyMap()).apiDefinition(apiDefinition).lastUpdatedTime(LocalDateTime.now()).threatProtectionPolicies(new HashSet<>(Arrays.asList("a", "b")));
return apiBuilder;
}
Aggregations