use of org.wso2.carbon.apimgt.core.models.APIDetails 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.apimgt.core.models.APIDetails in project carbon-apimgt by wso2.
the class ExportApiServiceImpl method exportApisGet.
/**
* Exports an existing API
*
* @param query Search query
* @param limit maximum APIs to export
* @param offset Starting position of the search
* @param request ms4j request object
* @return Zip file containing the exported APIs
* @throws NotFoundException When the particular resource does not exist in the system
*/
@Override
public Response exportApisGet(String query, Integer limit, Integer offset, Request request) throws NotFoundException {
APIPublisher publisher = null;
String exportedFilePath, zippedFilePath = null;
Set<APIDetails> apiDetails;
String exportedApiDirName = "exported-apis";
String pathToExportDir = System.getProperty("java.io.tmpdir") + File.separator + "exported-api-archives-" + UUID.randomUUID().toString();
try {
publisher = RestAPIPublisherUtil.getApiPublisher(RestApiUtil.getLoggedInUsername(request));
FileBasedApiImportExportManager importExportManager = new FileBasedApiImportExportManager(publisher, pathToExportDir);
apiDetails = importExportManager.getAPIDetails(limit, offset, query);
if (apiDetails.isEmpty()) {
// 404
String errorMsg = "No APIs found for query " + query;
log.error(errorMsg);
HashMap<String, String> paramList = new HashMap<>();
paramList.put("query", query);
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(ExceptionCodes.API_NOT_FOUND, paramList);
return Response.status(Response.Status.NOT_FOUND).entity(errorDTO).build();
}
exportedFilePath = importExportManager.exportAPIs(apiDetails, exportedApiDirName);
zippedFilePath = importExportManager.createArchiveFromExportedApiArtifacts(exportedFilePath, pathToExportDir, exportedApiDirName);
} catch (APIManagementException e) {
String errorMessage = "Error while exporting APIs";
log.error(errorMessage, e);
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
File exportedApiArchiveFile = new File(zippedFilePath);
Response.ResponseBuilder responseBuilder = Response.status(Response.Status.OK).entity(exportedApiArchiveFile);
responseBuilder.header("Content-Disposition", "attachment; filename=\"" + exportedApiArchiveFile.getName() + "\"");
Response response = responseBuilder.build();
return response;
}
use of org.wso2.carbon.apimgt.core.models.APIDetails in project carbon-apimgt by wso2.
the class APIImportExportTestCase method testGetApiDetails.
@Test(description = "Test getAPIDetails - single API")
void testGetApiDetails() throws APIManagementException {
printTestMethodName();
apiPublisher = Mockito.mock(APIPublisher.class);
String api1Id = UUID.randomUUID().toString();
Endpoint api1SandBoxEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("abcd").build();
Endpoint api1ProdEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("cdef").build();
API api1 = createApi("provider1", api1Id, "testapi1", "1.0.0", "Test API 1 - version 1.0.0", createEndpointTypeToIdMap(api1SandBoxEndpointId, api1ProdEndpointId)).build();
String api1Doc1Id = UUID.randomUUID().toString();
DocumentInfo api1Doc1Info = createAPIDoc(api1Doc1Id, "api1doc1", "", "API 1 DOC 1", DocumentInfo.DocType.HOWTO, "other type", DocumentInfo.SourceType.INLINE, "", DocumentInfo.Visibility.PRIVATE);
String api1Doc2Id = UUID.randomUUID().toString();
DocumentInfo api1Doc2Info = createAPIDoc(api1Doc2Id, "api1doc2.pdf", "api1doc2.pdf", "API 1 DOC 2", DocumentInfo.DocType.PUBLIC_FORUM, "other type", DocumentInfo.SourceType.FILE, "", DocumentInfo.Visibility.API_LEVEL);
String api1Doc3Id = UUID.randomUUID().toString();
DocumentInfo api1Doc3Info = createAPIDoc(api1Doc3Id, "api1doc3", "", "API 1 DOC 3", DocumentInfo.DocType.OTHER, "other type", DocumentInfo.SourceType.OTHER, "", DocumentInfo.Visibility.API_LEVEL);
List<DocumentInfo> api1DocumentInfo = new ArrayList<>();
api1DocumentInfo.add(api1Doc1Info);
api1DocumentInfo.add(api1Doc2Info);
api1DocumentInfo.add(api1Doc3Info);
// contents for documents
DocumentContent api1Doc1Content = createDocContent(api1Doc1Info, "Sample inline content for API1 DOC 1", null);
DocumentContent api1Doc2Content = createDocContent(api1Doc2Info, "", api1Doc2Stream);
DocumentContent api1Doc3Content = createDocContent(api1Doc3Info, "", null);
Mockito.when(apiPublisher.getAPIbyUUID(api1Id)).thenReturn(api1);
Mockito.when(apiPublisher.getApiSwaggerDefinition(api1Id)).thenReturn(api1Definition);
Mockito.when(apiPublisher.getApiGatewayConfig(api1Id)).thenReturn(api1GatewayConfig);
Mockito.when(apiPublisher.getAllDocumentation(api1Id, 0, Integer.MAX_VALUE)).thenReturn(api1DocumentInfo);
Mockito.when(apiPublisher.getDocumentationContent(api1Doc1Id)).thenReturn(api1Doc1Content);
Mockito.when(apiPublisher.getDocumentationContent(api1Doc2Id)).thenReturn(api1Doc2Content);
Mockito.when(apiPublisher.getDocumentationContent(api1Doc3Id)).thenReturn(api1Doc3Content);
Mockito.when(apiPublisher.getThumbnailImage(api1Id)).thenReturn(getClass().getClassLoader().getResourceAsStream("api1_thumbnail.png"));
List<API> apis = new ArrayList<>();
apis.add(api1);
Mockito.when(apiPublisher.searchAPIs(Integer.MAX_VALUE, 0, "*")).thenReturn(apis);
ApiImportExportManager importExportManager = new ApiImportExportManager(apiPublisher);
Set<APIDetails> apiDetailsSet = importExportManager.getAPIDetails(Integer.MAX_VALUE, 0, "*");
Assert.assertEquals(new ArrayList<>(apiDetailsSet).get(0).getApi().getId().equals(api1Id), true, "APIDetails not retrieved correctly for API: " + api1.getName() + ", version: " + api1.getVersion());
}
use of org.wso2.carbon.apimgt.core.models.APIDetails in project carbon-apimgt by wso2.
the class APIImportExportTestCase method testGetMultipleApiDetailsWithNonFatalErrors.
@Test(description = "Test getAPIDetails - multiple APIs with non-critical error in retrieving information of one API")
void testGetMultipleApiDetailsWithNonFatalErrors() throws APIManagementException {
printTestMethodName();
apiPublisher = Mockito.mock(APIPublisher.class);
String api4Id = UUID.randomUUID().toString();
Endpoint api4SandBoxEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("abcd").build();
Endpoint api4ProdEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("cdef").build();
API api4 = createApi("provider4", api4Id, "testapi4", "1.0.0", "Test API 4 - version 1.0.0", createEndpointTypeToIdMap(api4SandBoxEndpointId, api4ProdEndpointId)).build();
String api4Doc1Id = UUID.randomUUID().toString();
DocumentInfo api4Doc1Info = createAPIDoc(api4Doc1Id, "api1doc1", "", "API 4 DOC 1", DocumentInfo.DocType.HOWTO, "other type", DocumentInfo.SourceType.INLINE, "", DocumentInfo.Visibility.PRIVATE);
String api4Doc2Id = UUID.randomUUID().toString();
DocumentInfo api4Doc2Info = createAPIDoc(api4Doc2Id, "api1doc2.pdf", "api1doc2.pdf", "API 4 DOC 2", DocumentInfo.DocType.PUBLIC_FORUM, "other type", DocumentInfo.SourceType.FILE, "", DocumentInfo.Visibility.API_LEVEL);
String api4Doc3Id = UUID.randomUUID().toString();
DocumentInfo api4Doc3Info = createAPIDoc(api4Doc3Id, "api1doc3", "", "API 4 DOC 3", DocumentInfo.DocType.OTHER, "other type", DocumentInfo.SourceType.OTHER, "", DocumentInfo.Visibility.API_LEVEL);
List<DocumentInfo> api1DocumentInfo = new ArrayList<>();
api1DocumentInfo.add(api4Doc1Info);
api1DocumentInfo.add(api4Doc2Info);
api1DocumentInfo.add(api4Doc3Info);
// contents for documents
DocumentContent api4Doc1Content = createDocContent(api4Doc1Info, "Sample inline content for API1 DOC 1", null);
DocumentContent api4Doc2Content = createDocContent(api4Doc2Info, "", api1Doc2Stream);
DocumentContent api4Doc3Content = createDocContent(api4Doc3Info, "", null);
Mockito.when(apiPublisher.getAPIbyUUID(api4Id)).thenReturn(api4);
Mockito.when(apiPublisher.getApiSwaggerDefinition(api4Id)).thenReturn(api1Definition);
Mockito.when(apiPublisher.getApiGatewayConfig(api4Id)).thenReturn(api1GatewayConfig);
Mockito.when(apiPublisher.getAllDocumentation(api4Id, 0, Integer.MAX_VALUE)).thenReturn(api1DocumentInfo);
Mockito.when(apiPublisher.getDocumentationContent(api4Doc1Id)).thenReturn(api4Doc1Content);
Mockito.when(apiPublisher.getDocumentationContent(api4Doc2Id)).thenReturn(api4Doc2Content);
Mockito.when(apiPublisher.getDocumentationContent(api4Doc3Id)).thenReturn(api4Doc3Content);
Mockito.when(apiPublisher.getThumbnailImage(api4Id)).thenReturn(null);
String api5Id = UUID.randomUUID().toString();
Endpoint api5SandBoxEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("abcd").build();
Endpoint api5ProdEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("cdef").build();
API api5 = createApi("provider5", api5Id, "testapi4", "1.0.0", "Test API 5 - version 1.0.0", createEndpointTypeToIdMap(api5SandBoxEndpointId, api5ProdEndpointId)).build();
String api5Doc1Id = UUID.randomUUID().toString();
DocumentInfo api5Doc1Info = createAPIDoc(api5Doc1Id, "api1doc1", "", "API 5 DOC 1", DocumentInfo.DocType.HOWTO, "other type", DocumentInfo.SourceType.INLINE, "", DocumentInfo.Visibility.PRIVATE);
String api5Doc3Id = UUID.randomUUID().toString();
DocumentInfo api5Doc3Info = createAPIDoc(api5Doc3Id, "api1doc3", "", "API 5 DOC 3", DocumentInfo.DocType.OTHER, "other type", DocumentInfo.SourceType.OTHER, "", DocumentInfo.Visibility.API_LEVEL);
List<DocumentInfo> api5DocumentInfo = new ArrayList<>();
api5DocumentInfo.add(api5Doc1Info);
api5DocumentInfo.add(api5Doc3Info);
// contents for documents
DocumentContent api5Doc1Content = createDocContent(api5Doc1Info, "Sample inline content for API1 DOC 1", null);
DocumentContent api5Doc3Content = createDocContent(api5Doc3Info, "", null);
Mockito.when(apiPublisher.getAPIbyUUID(api5Id)).thenReturn(api5);
Mockito.when(apiPublisher.getApiSwaggerDefinition(api5Id)).thenReturn(api1Definition);
Mockito.when(apiPublisher.getApiGatewayConfig(api5Id)).thenReturn(api1GatewayConfig);
Mockito.when(apiPublisher.getAllDocumentation(api5Id, 0, Integer.MAX_VALUE)).thenReturn(api5DocumentInfo);
Mockito.when(apiPublisher.getDocumentationContent(api5Doc1Id)).thenReturn(api5Doc1Content);
Mockito.when(apiPublisher.getDocumentationContent(api5Doc3Id)).thenReturn(api5Doc3Content);
Mockito.when(apiPublisher.getThumbnailImage(api5Id)).thenReturn(getClass().getClassLoader().getResourceAsStream("api1_thumbnail.png"));
Mockito.when(apiPublisher.getAllDocumentation(api4Id, 0, Integer.MAX_VALUE)).thenThrow(APIManagementException.class);
List<API> apis = new ArrayList<>();
apis.add(api4);
apis.add(api5);
Mockito.when(apiPublisher.searchAPIs(Integer.MAX_VALUE, 0, "*")).thenReturn(apis);
ApiImportExportManager importExportManager = new ApiImportExportManager(apiPublisher);
Set<APIDetails> apiDetailsSet = importExportManager.getAPIDetails(Integer.MAX_VALUE, 0, "*");
Assert.assertEquals(apiDetailsSet.size() == 2, true, "Error getting API details");
}
use of org.wso2.carbon.apimgt.core.models.APIDetails in project carbon-apimgt by wso2.
the class FileBasedApiImportExportManager method exportAPIs.
/**
* Export a given set of APIs to the file system as a zip archive.
* The export root location is given by {@link FileBasedApiImportExportManager#path}/exported-apis.
*
* @param apiDetailSet Set of {@link APIDetails} objects to be exported
* @param exportDirectoryName Name of the directory to do the export
* @return Path to the directory with exported artifacts
* @throws APIMgtEntityImportExportException if an error occurred while exporting APIs to file system or
* no APIs are exported successfully
*/
public String exportAPIs(Set<APIDetails> apiDetailSet, String exportDirectoryName) throws APIMgtEntityImportExportException {
// this is the base directory for the archive. after export happens, this directory will
// be archived to be sent as a application/zip response to the client
String apiArtifactsBaseDirectoryPath = path + File.separator + exportDirectoryName;
try {
APIFileUtils.createDirectory(apiArtifactsBaseDirectoryPath);
} catch (APIMgtDAOException e) {
String errorMsg = "Unable to create directory for export API at :" + apiArtifactsBaseDirectoryPath;
throw new APIMgtEntityImportExportException(errorMsg, e);
}
for (APIDetails apiDetails : apiDetailSet) {
// derive the folder structure
String apiExportDirectory = APIFileUtils.getAPIBaseDirectory(apiArtifactsBaseDirectoryPath, new FileApi(apiDetails.getApi()));
API exportAPI = apiDetails.getApi();
try {
// create per-api export directory
APIFileUtils.createDirectory(apiExportDirectory);
// export API definition
APIFileUtils.exportApiDefinitionToFileSystem(new FileApi(exportAPI), apiExportDirectory);
// export swagger definition
APIFileUtils.exportSwaggerDefinitionToFileSystem(apiDetails.getSwaggerDefinition(), exportAPI, apiExportDirectory);
// export gateway configs
APIFileUtils.exportGatewayConfigToFileSystem(apiDetails.getGatewayConfiguration(), exportAPI, apiExportDirectory);
if (apiDetails.getEndpoints() != null && !apiDetails.getEndpoints().isEmpty()) {
exportEndpointsToFileSystem(apiDetails.getEndpoints(), exportAPI, apiExportDirectory);
}
} catch (APIMgtDAOException e) {
// no need to throw, log
log.error("Error in exporting API: " + exportAPI.getName() + ", version: " + apiDetails.getApi().getVersion(), e);
// cleanup the API directory
try {
APIFileUtils.deleteDirectory(path);
} catch (APIMgtDAOException e1) {
log.warn("Unable to remove directory " + path);
}
// skip this API
continue;
}
// as exported correctly.
if (apiDetails.getThumbnailStream() != null) {
try {
APIFileUtils.exportThumbnailToFileSystem(apiDetails.getThumbnailStream(), apiExportDirectory);
} catch (APIMgtDAOException warn) {
// log the warning without throwing
log.warn("Error in exporting thumbnail to file system for api: " + exportAPI.getName() + ", version: " + exportAPI.getVersion());
}
}
exportDocumentationToFileSystem(apiDetails.getAllDocumentInformation(), apiDetails, apiExportDirectory);
log.info("Successfully exported API: " + exportAPI.getName() + ", version: " + exportAPI.getVersion());
}
// if the directory is empty, no APIs have been exported!
try {
if (APIFileUtils.getDirectoryList(apiArtifactsBaseDirectoryPath).isEmpty()) {
// cleanup the archive root directory
APIFileUtils.deleteDirectory(path);
String errorMsg = "No APIs exported successfully";
throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_EXPORT_ERROR);
}
} catch (APIMgtDAOException e) {
String errorMsg = "Unable to find API definitions at: " + apiArtifactsBaseDirectoryPath;
log.error(errorMsg, e);
throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_IMPORT_ERROR);
}
return apiArtifactsBaseDirectoryPath;
}
Aggregations