use of org.wso2.carbon.registry.api.Registry in project carbon-apimgt by wso2.
the class ImportUtils method addAPIWsdl.
/**
* This method adds the WSDL to the registry, if there is a WSDL associated with the API.
*
* @param pathToArchive Location of the extracted folder of the API
* @param importedApi The imported API object
* @param apiProvider API Provider
* @throws APIManagementException If an error occurs while adding WSDL
*/
private static void addAPIWsdl(String pathToArchive, API importedApi, APIProvider apiProvider) throws APIManagementException {
String wsdlFileName = importedApi.getId().getApiName() + "-" + importedApi.getId().getVersion() + APIConstants.WSDL_FILE_EXTENSION;
String wsdlPath = pathToArchive + ImportExportConstants.WSDL_LOCATION + wsdlFileName;
if (CommonUtil.checkFileExistence(wsdlPath)) {
try (FileInputStream inputStream = new FileInputStream(wsdlPath)) {
String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
String fileExtension = FilenameUtils.getExtension(wsdlPath);
PublisherCommonUtils.addWsdl(fileExtension, inputStream, importedApi, apiProvider, tenantDomain);
} catch (FileNotFoundException e) {
throw new APIManagementException("WSDL file of the API: " + importedApi.getId().getName() + " is not found.", e, ExceptionCodes.NO_WSDL_FOUND_IN_WSDL_ARCHIVE);
} catch (IOException e) {
throw new APIManagementException("Error reading the WSDL file of the API: " + importedApi.getId().getName(), e, ExceptionCodes.CANNOT_PROCESS_WSDL_CONTENT);
}
}
}
use of org.wso2.carbon.registry.api.Registry in project carbon-apimgt by wso2.
the class GatewayUtils method getRegistry.
/**
* Get the config system registry for tenants
*
* @param tenantDomain - The tenant domain
* @return - A UserRegistry instance for the tenant
* @throws APIManagementException
*/
public static UserRegistry getRegistry(String tenantDomain) throws APIManagementException {
PrivilegedCarbonContext.startTenantFlow();
if (tenantDomain != null && StringUtils.isNotEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
UserRegistry registry;
try {
registry = RegistryServiceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
} catch (RegistryException e) {
String msg = "Failed to get registry instance for the tenant : " + tenantDomain + e.getMessage();
throw new APIManagementException(msg, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return registry;
}
use of org.wso2.carbon.registry.api.Registry in project carbon-apimgt by wso2.
the class APIManagerComponent method activate.
@Activate
protected void activate(ComponentContext componentContext) throws Exception {
if (log.isDebugEnabled()) {
log.debug("API manager component activated");
}
try {
BundleContext bundleContext = componentContext.getBundleContext();
addRxtConfigs();
addApplicationsPermissionsToRegistry();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String filePath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "api-manager.xml";
configuration.load(filePath);
String gatewayType = configuration.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
addDefinedSequencesToRegistry();
}
CommonConfigDeployer configDeployer = new CommonConfigDeployer();
bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), configDeployer, null);
TenantLoadMessageSender tenantLoadMessageSender = new TenantLoadMessageSender();
bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), tenantLoadMessageSender, null);
KeyMgtConfigDeployer keyMgtConfigDeployer = new KeyMgtConfigDeployer();
bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), keyMgtConfigDeployer, null);
// Registering Notifiers
bundleContext.registerService(Notifier.class.getName(), new SubscriptionsNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ApisNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ApplicationNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ApplicationRegistrationNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new PolicyNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new DeployAPIInGatewayNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ScopesNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new CertificateNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new GoogleAnalyticsNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ExternalGatewayNotifier(), null);
bundleContext.registerService(Notifier.class.getName(), new ExternallyDeployedApiNotifier(), null);
APIManagerConfigurationServiceImpl configurationService = new APIManagerConfigurationServiceImpl(configuration);
ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(configurationService);
APIMgtDBUtil.initialize();
APIMConfigService apimConfigService = new APIMConfigServiceImpl();
bundleContext.registerService(APIMConfigService.class.getName(), apimConfigService, null);
APIUtil.loadAndSyncTenantConf(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIUtil.loadTenantExternalStoreConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIUtil.loadTenantGAConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIUtil.loadTenantWorkFlowExtensions(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
// load self sigup configuration to the registry
APIUtil.loadTenantSelfSignUpConfigurations(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIUtil.loadCommonOperationPolicies(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
APIManagerAnalyticsConfiguration analyticsConfiguration = APIManagerAnalyticsConfiguration.getInstance();
analyticsConfiguration.setAPIManagerConfiguration(configuration);
registration = componentContext.getBundleContext().registerService(APIManagerConfigurationService.class.getName(), configurationService, null);
KeyManagerConfigurationServiceImpl keyManagerConfigurationService = new KeyManagerConfigurationServiceImpl();
registration = componentContext.getBundleContext().registerService(KeyManagerConfigurationService.class, keyManagerConfigurationService, null);
JWTValidationService jwtValidationService = new JWTValidationServiceImpl();
registration = componentContext.getBundleContext().registerService(JWTValidationService.class, jwtValidationService, null);
ServiceReferenceHolder.getInstance().setKeyManagerConfigurationService(keyManagerConfigurationService);
APIStatusObserverList.getInstance().init(configuration);
log.debug("Reading Analytics Configuration from file...");
// This method is called in two places. Mostly by the time activate hits,
// ServiceDataPublisherAdmin is not activated. Therefore, this same method is run,
// when ServiceDataPublisherAdmin is set.
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_APIMGT_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_APPLICATION_DATA_LOCATION), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_GOVERNANCE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + "/trunk"), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_PUBLISHER_APIMGT_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_APPLICATION_DATA_LOCATION), APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION, null);
// Enabling API Publishers/Creators to make changes on life-cycle history.
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_LIFECYCLE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_LIFE_CYCLE_HISTORY), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_PUBLISHER_LIFECYCLE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_LIFE_CYCLE_HISTORY), APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION, null);
setupImagePermissions();
GatewayArtifactsMgtDBUtil.initialize();
configureEventPublisherProperties();
configureNotificationEventPublisher();
// Load initially available api contexts at the server startup. This Cache is only use by the products other than the api-manager
/* TODO: Load Config values from apimgt.core*/
boolean apiManagementEnabled = APIUtil.isAPIManagementEnabled();
boolean loadAPIContextsAtStartup = APIUtil.isLoadAPIContextsAtStartup();
if (apiManagementEnabled && loadAPIContextsAtStartup) {
List<String> contextList = ApiMgtDAO.getInstance().getAllAvailableContexts();
Cache contextCache = APIUtil.getAPIContextCache();
for (String context : contextList) {
contextCache.put(context, Boolean.TRUE);
}
}
try {
APIUtil.createDefaultRoles(MultitenantConstants.SUPER_TENANT_ID);
} catch (APIManagementException e) {
log.error("Failed create default roles for tenant " + MultitenantConstants.SUPER_TENANT_ID, e);
} catch (Exception e) {
// The generic Exception is handled explicitly so execution does not stop during config deployment
log.error("Exception when creating default roles for tenant " + MultitenantConstants.SUPER_TENANT_ID, e);
}
// Adding default throttle policies
addDefaultAdvancedThrottlePolicies();
// Update all NULL THROTTLING_TIER values to Unlimited
boolean isNullThrottlingTierConversionEnabled = APIUtil.updateNullThrottlingTierAtStartup();
try {
if (isNullThrottlingTierConversionEnabled) {
ApiMgtDAO.getInstance().convertNullThrottlingTiers();
}
} catch (APIManagementException e) {
log.error("Failed to convert NULL THROTTLING_TIERS to Unlimited");
}
// // Initialise KeyManager.
// KeyManagerHolder.initializeKeyManager(configuration);
// Initialise sql constants
SQLConstantManagerFactory.initializeSQLConstantManager();
// Initialize PasswordResolver
PasswordResolverFactory.initializePasswordResolver();
APIUtil.init();
// Activating UserPostSelfRegistration handler componeAPITemplateBuilderImplnt
try {
registration = componentContext.getBundleContext().registerService(AbstractEventHandler.class.getName(), new UserPostSelfRegistrationHandler(), null);
} catch (Exception e) {
log.error("Error while activating UserPostSelfRegistration handler component.", e);
}
// Read the trust store
ServerConfiguration config = CarbonUtils.getServerConfiguration();
// Initialize product REST API token caches
CacheProvider.createRESTAPITokenCache();
CacheProvider.createRESTAPIInvalidTokenCache();
CacheProvider.createGatewayJWTTokenCache();
CacheProvider.createTenantConfigCache();
CacheProvider.createRecommendationsCache();
CacheProvider.createParsedSignJWTCache();
CacheProvider.createGatewayBasicAuthResourceCache();
CacheProvider.createGatewayUsernameCache();
CacheProvider.createIntrospectionCache();
// Initialize Recommendation wso2event output publisher
configureRecommendationEventPublisherProperties();
setupAccessTokenGenerator();
retrieveAndSetParentTrustStore();
if (configuration.getGatewayArtifactSynchronizerProperties().isRetrieveFromStorageEnabled()) {
if (APIConstants.GatewayArtifactSynchronizer.DB_RETRIEVER_NAME.equals(configuration.getGatewayArtifactSynchronizerProperties().getRetrieverName())) {
bundleContext.registerService(ArtifactRetriever.class.getName(), new DBRetriever(), null);
}
}
bundleContext.registerService(ScopeValidator.class, new SystemScopesIssuer(), null);
} catch (APIManagementException e) {
log.error("Error while initializing the API manager component", e);
} catch (APIManagerDatabaseException e) {
log.fatal("Error while Creating the database", e);
}
}
use of org.wso2.carbon.registry.api.Registry in project carbon-apimgt by wso2.
the class APIManagerComponent method addDefinedSequencesToRegistry.
private void addDefinedSequencesToRegistry() throws APIManagementException {
try {
RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
UserRegistry registry = registryService.getGovernanceSystemRegistry();
// Add all custom in,out and fault sequences to registry
APIUtil.addDefinedAllSequencesToRegistry(registry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
APIUtil.addDefinedAllSequencesToRegistry(registry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
APIUtil.addDefinedAllSequencesToRegistry(registry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
} catch (RegistryException e) {
throw new APIManagementException("Error while saving defined sequences to the registry ", e);
}
}
use of org.wso2.carbon.registry.api.Registry in project carbon-apimgt by wso2.
the class DocumentIndexer method fetchDocumentContent.
/**
* Write document content to document artifact as its raw content
*
* @param registry
* @param documentResource
* @return
* @throws RegistryException
* @throws IOException
* @throws APIManagementException
*/
private String fetchDocumentContent(Registry registry, Resource documentResource) throws RegistryException, IOException, APIManagementException {
GenericArtifactManager docArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
GenericArtifact documentArtifact = docArtifactManager.getGenericArtifact(documentResource.getUUID());
String sourceType = documentArtifact.getAttribute(APIConstants.DOC_SOURCE_TYPE);
String contentString = null;
if (Documentation.DocumentSourceType.FILE.name().equals(sourceType)) {
String path = documentArtifact.getAttribute(APIConstants.DOC_FILE_PATH);
int indexOfApimgt = path.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
String filepath = path.substring(indexOfApimgt);
Resource contentResource = registry.get(filepath);
int indexOfFiles = filepath.indexOf(APIConstants.DOCUMENT_FILE_DIR) + APIConstants.DOCUMENT_FILE_DIR.length() + 1;
String fileName = filepath.substring(indexOfFiles);
String extension = FilenameUtils.getExtension(fileName);
InputStream inputStream = null;
try {
inputStream = contentResource.getContentStream();
switch(extension) {
case APIConstants.PDF_EXTENSION:
PDFParser pdfParser = new PDFParser(new RandomAccessBufferedFileInputStream(inputStream));
pdfParser.parse();
COSDocument cosDocument = pdfParser.getDocument();
PDFTextStripper stripper = new PDFTextStripper();
contentString = stripper.getText(new PDDocument(cosDocument));
break;
case APIConstants.DOC_EXTENSION:
{
POIFSFileSystem pfs = new POIFSFileSystem(inputStream);
WordExtractor msWord2003Extractor = new WordExtractor(pfs);
contentString = msWord2003Extractor.getText();
break;
}
case APIConstants.DOCX_EXTENSION:
XWPFDocument doc = new XWPFDocument(inputStream);
XWPFWordExtractor msWord2007Extractor = new XWPFWordExtractor(doc);
contentString = msWord2007Extractor.getText();
break;
case APIConstants.XLS_EXTENSION:
{
POIFSFileSystem pfs = new POIFSFileSystem(inputStream);
ExcelExtractor extractor = new ExcelExtractor(pfs);
contentString = extractor.getText();
break;
}
case APIConstants.XLSX_EXTENSION:
XSSFWorkbook xssfSheets = new XSSFWorkbook(inputStream);
XSSFExcelExtractor xssfExcelExtractor = new XSSFExcelExtractor(xssfSheets);
contentString = xssfExcelExtractor.getText();
break;
case APIConstants.PPT_EXTENSION:
{
POIFSFileSystem fs = new POIFSFileSystem(inputStream);
PowerPointExtractor extractor = new PowerPointExtractor(fs);
contentString = extractor.getText();
break;
}
case APIConstants.PPTX_EXTENSION:
XMLSlideShow xmlSlideShow = new XMLSlideShow(inputStream);
XSLFPowerPointExtractor xslfPowerPointExtractor = new XSLFPowerPointExtractor(xmlSlideShow);
contentString = xslfPowerPointExtractor.getText();
break;
case APIConstants.TXT_EXTENSION:
case APIConstants.WSDL_EXTENSION:
case APIConstants.XML_DOC_EXTENSION:
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder contentBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
contentBuilder.append(line);
}
contentString = contentBuilder.toString();
break;
}
} finally {
IOUtils.closeQuietly(inputStream);
}
} else if (Documentation.DocumentSourceType.INLINE.name().equals(sourceType)) {
String fileName = ((ResourceImpl) documentResource).getName();
String pathToDocFile = documentResource.getPath();
String pathToContent = pathToDocFile.substring(0, pathToDocFile.lastIndexOf(fileName)) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + fileName;
if (registry.resourceExists(pathToContent)) {
Resource contentResource = registry.get(pathToContent);
InputStream instream = null;
BufferedReader reader = null;
String line;
try {
instream = contentResource.getContentStream();
reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder contentBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
contentBuilder.append(line);
}
contentString = contentBuilder.toString();
} finally {
if (reader != null) {
IOUtils.closeQuietly(reader);
}
}
}
}
return contentString;
}
Aggregations