Search in sources :

Example 66 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class APIProviderImplTest method testSaveGraphqlSchemaDefinition.

@Test
public void testSaveGraphqlSchemaDefinition() throws Exception {
    Resource resource = new ResourceImpl();
    String resourcePath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + "admin" + RegistryConstants.PATH_SEPARATOR + "API1" + RegistryConstants.PATH_SEPARATOR + "1.0.0" + RegistryConstants.PATH_SEPARATOR;
    String schemaContent = "sample schema";
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId);
    Mockito.when(APIUtil.getGraphqlDefinitionFilePath("API1", "1.0.0", "admin")).thenReturn(resourcePath);
    Resource resourceMock = Mockito.mock(Resource.class);
    resourceMock.setContent(schemaContent);
    resourceMock.setMediaType(String.valueOf(ContentType.TEXT_PLAIN));
    ServiceReferenceHolder sh = PowerMockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(sh);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    Mockito.when(userRegistry.newResource()).thenReturn(resource);
    PowerMockito.doNothing().when(APIUtil.class, "clearResourcePermissions", Mockito.any(), Mockito.any(), Mockito.anyInt());
    PowerMockito.doNothing().when(APIUtil.class, "setResourcePermissions", Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
    GraphQLSchemaDefinition graphQLSchemaDefinition = Mockito.mock(GraphQLSchemaDefinition.class);
    PowerMockito.doCallRealMethod().when(graphQLSchemaDefinition).saveGraphQLSchemaDefinition(api, schemaContent, userRegistry);
    // org.wso2.carbon.registry.api.RegistryException
    Mockito.doThrow(RegistryException.class).when(registry).put(Matchers.anyString(), any(Resource.class));
    try {
        graphQLSchemaDefinition.saveGraphQLSchemaDefinition(api, schemaContent, registry);
    } catch (APIManagementException e) {
        String msg = "Error while adding Graphql Definition for API1-1.0.0";
        Assert.assertEquals(msg, e.getMessage());
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 67 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class ExportUtils method addDocumentationToArchive.

/**
 * Retrieve documentation for the exporting API or API Product and store it in the archive directory.
 * FILE, INLINE, MARKDOWN and URL documentations are handled.
 *
 * @param archivePath  File path to export the documents
 * @param identifier   ID of the requesting API or API Product
 * @param exportFormat Format for export
 * @param apiProvider  API Provider
 * @param type         Type of the Project (whether an API or an API Product)
 * @throws APIImportExportException If an error occurs while retrieving documents from the
 *                                  registry or storing in the archive directory
 * @throws APIManagementException   If an error occurs while retrieving document details
 */
public static void addDocumentationToArchive(String archivePath, Identifier identifier, ExportFormat exportFormat, APIProvider apiProvider, String type) throws APIImportExportException, APIManagementException {
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    List<Documentation> docList = StringUtils.equals(type, APIConstants.API_IDENTIFIER_TYPE) ? apiProvider.getAllDocumentation(identifier.getUUID(), tenantDomain) : apiProvider.getAllDocumentation(identifier);
    if (!docList.isEmpty()) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String docDirectoryPath = archivePath + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY;
        CommonUtil.createDirectory(docDirectoryPath);
        try {
            for (Documentation doc : docList) {
                // Retrieving the document again since objects in docList might have missing fields
                Documentation individualDocument = apiProvider.getDocumentation(identifier.getUUID(), doc.getId(), tenantDomain);
                String sourceType = individualDocument.getSourceType().name();
                String resourcePath = null;
                InputStream inputStream = null;
                String localFileName = null;
                String individualDocDirectoryPath = docDirectoryPath + File.separator + cleanFolderName(individualDocument.getName());
                CommonUtil.createDirectory(individualDocDirectoryPath);
                DocumentationContent documentationContent = apiProvider.getDocumentationContent(identifier.getUUID(), doc.getId(), tenantDomain);
                if (documentationContent != null) {
                    if (Documentation.DocumentSourceType.FILE.toString().equalsIgnoreCase(sourceType)) {
                        localFileName = individualDocument.getFilePath().substring(individualDocument.getFilePath().lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
                        inputStream = documentationContent.getResourceFile().getContent();
                        individualDocument.setFilePath(localFileName);
                    } else if (Documentation.DocumentSourceType.INLINE.toString().equalsIgnoreCase(sourceType) || Documentation.DocumentSourceType.MARKDOWN.toString().equalsIgnoreCase(sourceType)) {
                        // Inline/Markdown content file name would be same as the documentation name
                        localFileName = individualDocument.getName();
                        inputStream = new ByteArrayInputStream(documentationContent.getTextContent().getBytes());
                    }
                }
                CommonUtil.writeDtoToFile(individualDocDirectoryPath + ImportExportConstants.DOCUMENT_FILE_NAME, exportFormat, ImportExportConstants.TYPE_DOCUMENTS, DocumentationMappingUtil.fromDocumentationToDTO(individualDocument));
                if (inputStream != null) {
                    // Check whether resource exists in the registry
                    try (OutputStream outputStream = new FileOutputStream(individualDocDirectoryPath + File.separator + localFileName)) {
                        IOUtils.copy(inputStream, outputStream);
                    }
                } else {
                    // Log error and avoid throwing as we give capability to export document artifact without
                    // the content if does not exists
                    log.error("Documentation resource for API/API Product: " + identifier.getName() + " not found in " + resourcePath);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Documentation retrieved successfully for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion());
            }
        } catch (IOException e) {
            throw new APIImportExportException("I/O error while writing documentation to file for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion(), e);
        }
    } else if (log.isDebugEnabled()) {
        log.debug("No documentation found for API/API Product: " + identifier + ". Skipping documentation export.");
    }
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) GsonBuilder(com.google.gson.GsonBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) Gson(com.google.gson.Gson) IOException(java.io.IOException)

Example 68 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class APIMappingUtil method fromResourcePathListToDTO.

/**
 * Converts a List object of API resource paths into a DTO.
 *
 * @param resourcePathList List of API resource paths
 * @param limit            maximum number of API resource paths to be returned
 * @param offset           starting index
 * @return ResourcePathListDTO object containing ResourcePathDTOs
 */
public static ResourcePathListDTO fromResourcePathListToDTO(List<ResourcePath> resourcePathList, int limit, int offset) {
    ResourcePathListDTO resourcePathListDTO = new ResourcePathListDTO();
    List<ResourcePathDTO> resourcePathDTOs = new ArrayList<ResourcePathDTO>();
    // identifying the proper start and end indexes
    int size = resourcePathList.size();
    int start = offset < size && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = offset + limit - 1 <= size - 1 ? offset + limit - 1 : size - 1;
    for (int i = start; i <= end; i++) {
        ResourcePath path = resourcePathList.get(i);
        ResourcePathDTO dto = new ResourcePathDTO();
        dto.setId(path.getId());
        dto.setResourcePath(path.getResourcePath());
        dto.setHttpVerb(path.getHttpVerb());
        resourcePathDTOs.add(dto);
    }
    resourcePathListDTO.setCount(resourcePathDTOs.size());
    resourcePathListDTO.setList(resourcePathDTOs);
    return resourcePathListDTO;
}
Also used : ResourcePathDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ResourcePathDTO) ResourcePath(org.wso2.carbon.apimgt.api.model.ResourcePath) ArrayList(java.util.ArrayList) ResourcePathListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ResourcePathListDTO)

Example 69 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class AbstractAPIManager method uploadWsdl.

/**
 * Create a wsdl in the path specified.
 *
 * @param resourcePath   Registry path of the resource
 * @param wsdlDefinition wsdl content
 */
@Override
public void uploadWsdl(String resourcePath, String wsdlDefinition) throws APIManagementException {
    try {
        Resource resource = registry.newResource();
        resource.setContent(wsdlDefinition);
        resource.setMediaType(String.valueOf(ContentType.APPLICATION_XML));
        registry.put(resourcePath, resource);
    } catch (RegistryException e) {
        String msg = "Error while uploading wsdl to from the registry ";
        throw new APIManagementException(msg, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 70 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class AbstractAPIManager method getAllWsdls.

/**
 * Returns list of wsdls
 *
 * @return list of wsdl objects or null
 * @throws APIManagementException If unable to return satisfied wsdl object list
 */
@Override
public List<Wsdl> getAllWsdls() throws APIManagementException {
    List<Wsdl> wsdlList = new ArrayList<Wsdl>();
    String resourcePath = APIConstants.API_WSDL_RESOURCE;
    try {
        if (registry.resourceExists(resourcePath)) {
            Resource wsdlResource = registry.get(resourcePath);
            if (wsdlResource instanceof Collection) {
                String[] wsdlCollection = ((Collection) wsdlResource).getChildren();
                if (wsdlCollection.length > 0) {
                    for (String wsdlFile : wsdlCollection) {
                        Resource wsdlResourceFile = registry.get(wsdlFile);
                        String uuid = wsdlResourceFile.getUUID();
                        Wsdl wsdl = new Wsdl();
                        String wsdlName = wsdlFile.substring(wsdlFile.lastIndexOf("/") + 1);
                        wsdl.setUuid(uuid);
                        wsdl.setName(wsdlName);
                        wsdlList.add(wsdl);
                    }
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Failed to get wsdl list";
        throw new APIManagementException(msg, e);
    }
    return wsdlList;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) Collection(org.wso2.carbon.registry.core.Collection) Wsdl(org.wso2.carbon.apimgt.api.model.Wsdl) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Aggregations

Resource (org.wso2.carbon.registry.core.Resource)51 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)48 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)44 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)28 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)25 IOException (java.io.IOException)18 Registry (org.wso2.carbon.registry.core.Registry)16 Collection (org.wso2.carbon.registry.core.Collection)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 Test (org.junit.Test)13 Resource (org.wso2.carbon.registry.api.Resource)13 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 ArrayList (java.util.ArrayList)11 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)11 RegistryException (org.wso2.carbon.registry.api.RegistryException)11 ResourceImpl (org.wso2.carbon.registry.core.ResourceImpl)11 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)11 JSONParser (org.json.simple.parser.JSONParser)10 ParseException (org.json.simple.parser.ParseException)10 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)10