Java Code Examples for org.wso2.carbon.registry.core.Resource#setContent()

The following examples show how to use org.wso2.carbon.registry.core.Resource#setContent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadWsdl() throws RegistryException, APIManagementException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Resource resource = new ResourceImpl();
    String resourcePath = "/test/wsdl";
    String wsdlContent = "sample wsdl";
    Resource resourceMock = Mockito.mock(Resource.class);
    resourceMock.setContent(wsdlContent);
    resourceMock.setMediaType(String.valueOf(ContentType.APPLICATION_XML));
    Mockito.when(registry.newResource()).thenReturn(resource);
    Mockito.doThrow(RegistryException.class).doReturn(resourcePath).when(registry).put(resourcePath, resource);
    try {
        abstractAPIManager.uploadWsdl(resourcePath, wsdlContent);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while uploading wsdl to from the registry"));
    }
    abstractAPIManager.uploadWsdl(resourcePath, wsdlContent);
    Mockito.verify(registry, Mockito.atLeastOnce()).put(resourcePath, resource);
}
 
Example 2
Source File: DatasourceMigrator.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Migrate the password in datasource configuration
 *
 * @param tenantId
 * @param dataSources
 * @throws MigrationClientException
 */
private void updatePasswordInRegistryDataSources(int tenantId, List<Resource> dataSources)
        throws MigrationClientException {
    for (Resource dataSource : dataSources) {
        try {
            InputStream contentStream = dataSource.getContentStream();
            OMElement omElement = Utility.toOM(contentStream);
            Iterator pit = ((OMElement) ((OMElement) omElement.getChildrenWithName(Constant.DEFINITION_Q).next())
                    .getChildrenWithName(Constant.CONFIGURATION_Q).next()).getChildrenWithName(Constant.PASSWORD_Q);
            while (pit.hasNext()) {
                OMElement passwordElement = (OMElement) pit.next();
                if (Boolean.parseBoolean(passwordElement.getAttributeValue(Constant.ENCRYPTED_Q))) {
                    String password = passwordElement.getText();
                    String newEncryptedPassword = Utility.getNewEncryptedValue(password);
                    if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                        passwordElement.setText(newEncryptedPassword);
                        dataSource.setContent(omElement.toString().getBytes());
                        DataSourceDAO.saveDataSource(tenantId, dataSource);
                    }
                }
            }
        } catch (XMLStreamException | CryptoException | RegistryException | DataSourceException e) {
            throw new MigrationClientException(e.getMessage());
        }
    }
}
 
Example 3
Source File: JWTClientUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get the jwt details from the registry for tenants.
 *
 * @param tenantId for accesing tenant space.
 * @return the config for tenant
 * @throws RegistryException
 */
public static void addJWTConfigResourceToRegistry(int tenantId, String content)
		throws RegistryException {
	try {
		PrivilegedCarbonContext.startTenantFlow();
		PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
		RegistryService registryService = JWTClientExtensionDataHolder.getInstance().getRegistryService();
		if (registryService != null) {
			Registry registry = registryService.getConfigSystemRegistry(tenantId);
			JWTClientUtil.loadTenantRegistry(tenantId);
			if (!registry.resourceExists(TENANT_JWT_CONFIG_LOCATION)) {
				Resource resource = registry.newResource();
				resource.setContent(content.getBytes());
				registry.put(TENANT_JWT_CONFIG_LOCATION, resource);
			}
		}
	} finally {
		PrivilegedCarbonContext.endTenantFlow();
	}
}
 
Example 4
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetWsdl() throws APIManagementException, RegistryException, IOException {
    Resource resourceMock = Mockito.mock(Resource.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String wsdlName =
            identifier.getProviderName() + "--" + identifier.getApiName() + identifier.getVersion() + ".wsdl";
    String wsdlResourcePath = APIConstants.API_WSDL_RESOURCE_LOCATION + wsdlName;
    Resource resource = new ResourceImpl(wsdlResourcePath, new ResourceDO());
    Mockito.when(registry.get(wsdlResourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(registry.resourceExists(wsdlResourcePath)).thenReturn(true);
    try {
        abstractAPIManager.getWSDL(identifier);
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while getting wsdl file from the registry"));
    }
    String wsdlContent = "sample wsdl";
    resource.setContent(wsdlContent);
    InputStream inputStream = new ArrayInputStream();
    Mockito.when(resourceMock.getContentStream()).thenReturn(inputStream);
    Assert.assertEquals(wsdlContent, IOUtils.toString(abstractAPIManager.getWSDL(identifier).getContent()));
    PowerMockito.mockStatic(IOUtils.class);
}
 
Example 5
Source File: RegistryManager.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Persist an object in the local registry.
 *
 * @param dataObj      object to be persisted.
 * @param resourcePath resource path to be persisted.
 */
private void persist(Object dataObj, String resourcePath) throws AutoScalerException {

    try {
        registryService.beginTransaction();
        Resource nodeResource = registryService.newResource();
        nodeResource.setContent(Serializer.serializeToByteArray(dataObj));
        registryService.put(resourcePath, nodeResource);
        registryService.commitTransaction();
    } catch (Exception e) {
        try {
            registryService.rollbackTransaction();
        } catch (RegistryException e1) {
            if (log.isErrorEnabled()) {
                log.error("Could not rollback transaction", e1);
            }
        }
        throw new AutoScalerException("Could not persist data in registry", e);
    }
}
 
Example 6
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTagsWithAttributes() throws Exception {
    Registry userRegistry = Mockito.mock(Registry.class);
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(userRegistry, apiMgtDAO);
    System.setProperty(CARBON_HOME, "");
    PowerMockito.mockStatic(GovernanceUtils.class);
    UserRegistry userRegistry1 = Mockito.mock(UserRegistry.class);
    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt())).
            thenReturn(userRegistry1);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry1);
    List<TermData> list = new ArrayList<TermData>();
    TermData termData = new TermData("testTerm", 10);
    list.add(termData);
    Mockito.when(GovernanceUtils.getTermDataList(Mockito.anyMap(), Mockito.anyString(), Mockito.anyString(),
            Mockito.anyBoolean())).thenReturn(list);
    ResourceDO resourceDO = Mockito.mock(ResourceDO.class);
    Resource resource = new ResourceImpl("dw", resourceDO);
    resource.setContent("testContent");
    Mockito.when(userRegistry1.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(userRegistry1.get(Mockito.anyString())).thenReturn(resource);
    assertNotNull(apiConsumer.getTagsWithAttributes("testDomain"));
}
 
Example 7
Source File: RegistryManager.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Persist a serializable object in the registry with the given resource path.
 *
 * @param serializableObject object to be persisted.
 */
public synchronized void persist(String resourcePath, Serializable serializableObject) throws RegistryException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Persisting resource in registry: [resource-path] %s", resourcePath));
    }

    Registry registry = getRegistry();

    try {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        registry.beginTransaction();
        Resource nodeResource = registry.newResource();
        nodeResource.setContent(serializeToByteArray(serializableObject));
        registry.put(resourcePath, nodeResource);
        registry.commitTransaction();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Resource persisted successfully in registry: [resource-path] %s",
                    resourcePath));
        }
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (Exception e1){
            if (log.isErrorEnabled()) {
                log.error("Could not rollback transaction", e1);
            }
        }
        String msg = "Failed to persist resource in registry: " + resourcePath;
        throw new RegistryException(msg, e);
    }
}
 
Example 8
Source File: AbstractMetaDataHandler.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public void saveMetadata
        () throws ReportingException {
    try {
        RegistryService registryService = ReportingTemplateComponent.getRegistryService();
        Registry registry = registryService.getConfigSystemRegistry();
        registry.beginTransaction();
        Resource reportFilesResource = registry.newResource();
        reportFilesResource.setContent(reportsElement.toString());
        String location = ReportConstants.REPORT_META_DATA_PATH + ReportConstants.METADATA_FILE_NAME;
        registry.put(location, reportFilesResource);
        registry.commitTransaction();
    } catch (RegistryException e) {
        throw new ReportingException("Exception occured in loading the meta-data of reports", e);
    }
}
 
Example 9
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetWsdlById() throws RegistryException, APIManagementException, IOException {
    String resourceId = SAMPLE_RESOURCE_ID;
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Collection parentCollection = new CollectionImpl();
    String wsdlResourcepath = APIConstants.API_WSDL_RESOURCE;
    String resourcePath = wsdlResourcepath + "/wsdl1";
    parentCollection.setChildren(new String[] { resourcePath });
    Mockito.when(registry.get(wsdlResourcepath)).thenReturn(parentCollection);
    Resource resource = new ResourceImpl(resourcePath, new ResourceDO());
    Mockito.when(registry.get(resourcePath)).thenThrow(RegistryException.class).thenReturn(resource);
    Mockito.when(registry.resourceExists(wsdlResourcepath)).thenReturn(false, true);
    Assert.assertNull(abstractAPIManager.getWsdlById(resourceId));
    resource.setUUID(resourceId);
    try {
        abstractAPIManager.getWsdlById(resourceId);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while accessing registry objects"));
    }
    String wsdlContent = "sample wsdl";
    resource.setContent(wsdlContent);
    Wsdl wsdl = abstractAPIManager.getWsdlById(resourceId);
    Assert.assertNotNull(wsdl);
    PowerMockito.mockStatic(IOUtils.class);
    PowerMockito.when(IOUtils.toString((InputStream) Mockito.any(), Mockito.anyString()))
            .thenThrow(IOException.class);
    abstractAPIManager.getWsdlById(resourceId);// covers logged only exception;

}
 
Example 10
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetGlobalMediationPolicy()
        throws RegistryException, APIManagementException, XMLStreamException, IOException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    String resourceUUID = SAMPLE_RESOURCE_ID;
    Collection parentCollection = new CollectionImpl();
    String mediationResourcePath = APIConstants.API_CUSTOM_SEQUENCE_LOCATION;
    String childCollectionPath = mediationResourcePath + "/testMediation";
    parentCollection.setChildren(new String[] { childCollectionPath });
    Mockito.when(registry.get(mediationResourcePath)).thenThrow(RegistryException.class).thenReturn(parentCollection);
    Collection childCollection = new CollectionImpl();
    String resourcePath = childCollectionPath + "/policy1";
    childCollection.setChildren(new String[] { resourcePath });
    Mockito.when(registry.get(childCollectionPath)).thenReturn(childCollection);
    Resource resource = new ResourceImpl(resourcePath, new ResourceDO());
    resource.setUUID(resourceUUID);

    Mockito.when(registry.get(resourcePath)).thenReturn(resource);
    try {
        abstractAPIManager.getGlobalMediationPolicy(resourceUUID);
        Assert.fail("Registry Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while accessing registry objects"));
    }
    abstractAPIManager.getGlobalMediationPolicy(resourceUUID); // test for registry exception
    String mediationPolicyContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<sequence xmlns=\"http://ws.apache.org/ns/synapse\" name=\"default-endpoint\">\n</sequence>";
    resource.setContent(mediationPolicyContent);
    Mediation policy = abstractAPIManager.getGlobalMediationPolicy(resourceUUID);
    Assert.assertNotNull(policy);
    PowerMockito.mockStatic(IOUtils.class);
    PowerMockito.mockStatic(AXIOMUtil.class);
    PowerMockito.when(IOUtils.toString((InputStream) Mockito.any(), Mockito.anyString()))
            .thenThrow(IOException.class).thenReturn(mediationPolicyContent);
    PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(XMLStreamException.class);
    abstractAPIManager.getGlobalMediationPolicy(resourceUUID); // cover the logged only exceptions
    abstractAPIManager.getGlobalMediationPolicy(resourceUUID); // cover the logged only exceptions

}
 
Example 11
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAllGlobalMediationPolicies()
        throws RegistryException, APIManagementException, IOException, XMLStreamException {
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    Collection parentCollection = new CollectionImpl();
    String mediationResourcePath = APIConstants.API_CUSTOM_SEQUENCE_LOCATION;
    String childCollectionPath = mediationResourcePath + "/testMediation";
    parentCollection.setChildren(new String[] { childCollectionPath });
    Mockito.when(registry.get(mediationResourcePath)).thenReturn(parentCollection);
    Collection childCollection = new CollectionImpl();
    String resourcePath = childCollectionPath + "/policy1";
    childCollection.setChildren(new String[] { resourcePath });
    Mockito.when(registry.get(childCollectionPath)).thenReturn(childCollection);
    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);

    Mockito.when(registry.get(resourcePath)).thenReturn(resource);
    try {
        abstractAPIManager.getAllGlobalMediationPolicies();
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get global mediation policies"));
    }
    String mediationPolicyContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<sequence xmlns=\"http://ws.apache.org/ns/synapse\" name=\"default-endpoint\">\n</sequence>";
    resource.setContent(mediationPolicyContent);

    List<Mediation> policies = abstractAPIManager.getAllGlobalMediationPolicies();
    Assert.assertNotNull(policies);
    Assert.assertEquals(policies.size(), 1);
    PowerMockito.mockStatic(IOUtils.class);
    PowerMockito.mockStatic(AXIOMUtil.class);
    PowerMockito.when(IOUtils.toString((InputStream) Mockito.any(), Mockito.anyString()))
            .thenThrow(IOException.class).thenReturn(mediationPolicyContent);
    PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(XMLStreamException.class);
    abstractAPIManager.getAllGlobalMediationPolicies(); // cover the logged only exceptions
    abstractAPIManager.getAllGlobalMediationPolicies(); // cover the logged only exceptions

}
 
Example 12
Source File: CarbonRepositoryUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Save the given DeploymentSynchronizerConfiguration to the registry. The target
 * configuration registry space will be selected using the specified tenant ID. As a result
 * the configuration will be stored in the configuration registry of the specified
 * tenant.
 *
 * @param config The configuration to be saved
 * @param tenantId Tenant ID to select the configuration registry
 * @throws org.wso2.carbon.registry.core.exceptions.RegistryException if an error occurs while accessing the registry
 */
public static void persistConfiguration(DeploymentSynchronizerConfiguration config,
                                        int tenantId) throws RegistryException {

    Resource resource;
    UserRegistry localRepository = getLocalRepository(tenantId);
    if (!localRepository.resourceExists(DeploymentSynchronizerConstants.CARBON_REPOSITORY)) {
        resource = localRepository.newResource();
    } else {
        resource = localRepository.get(DeploymentSynchronizerConstants.CARBON_REPOSITORY);
    }

    resource.setProperty(DeploymentSynchronizerConstants.AUTO_COMMIT_MODE,
            String.valueOf(config.isAutoCommit()));
    resource.setProperty(DeploymentSynchronizerConstants.AUTO_CHECKOUT_MODE,
            String.valueOf(config.isAutoCheckout()));
    resource.setProperty(DeploymentSynchronizerConstants.AUTO_SYNC_PERIOD,
            String.valueOf(config.getPeriod()));
    resource.setProperty(DeploymentSynchronizerConstants.USE_EVENTING,
            String.valueOf(config.isUseEventing()));
    resource.setProperty(DeploymentSynchronizerConstants.REPOSITORY_TYPE,
            config.getRepositoryType());
    resource.setContent(config.isEnabled() ? "enabled" : "disabled");

    //Get Repository specific configuration parameters from config object.
    RepositoryConfigParameter[] parameters = config.getRepositoryConfigParameters();

    if (parameters != null && parameters.length != 0) {
        //Save each Repository specific configuration parameter in registry.
        for (int i = 0; i < parameters.length; i++) {
            resource.setProperty(parameters[i].getName(), parameters[i].getValue());
        }
    }

    localRepository.put(DeploymentSynchronizerConstants.CARBON_REPOSITORY, resource);
    resource.discard();
}
 
Example 13
Source File: ProviderMigrationClient.java    From product-es with Apache License 2.0 5 votes vote down vote up
private void migrateProvider(Collection root, Registry registry)
        throws RegistryException, SAXException, TransformerException, ParserConfigurationException, IOException {
    String[] childrenPaths = root.getChildren();
    for (String child : childrenPaths) {
        Resource childResource = registry.get(child);
        if (childResource instanceof Collection) {
            migrateProvider((Collection) childResource, registry);
        } else {
            String path = childResource.getPath();
            byte[] configContent = (byte[]) childResource.getContent();
            String contentString = RegistryUtils.decodeBytes(configContent);
            Document dom = stringToDocument(contentString);
            if (dom.getElementsByTagName(Constants.OVERVIEW).getLength() > 0) {
                Node overview = dom.getElementsByTagName(Constants.OVERVIEW).item(0);
                NodeList childrenList = overview.getChildNodes();
                for (int j = 0; j < childrenList.getLength(); j++) {
                    Node node = childrenList.item(j);
                    if (Constants.PROVIDER.equals(node.getNodeName())) {
                        overview.removeChild(node);
                    }
                }
                String newContentString = documentToString(dom);
                byte[] newContentObject = RegistryUtils.encodeString(newContentString);
                childResource.setContent(newContentObject);
                registry.put(path, childResource);
            }
        }
    }
}
 
Example 14
Source File: APIEndpointPasswordRegistryHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called for a registry get operation
 *
 * @param requestContext - The request context
 * @return - returns the modified resource
 * @throws RegistryException
 */
public Resource get(RequestContext requestContext) throws RegistryException {
    Resource resource = requestContext.getResource();
    if (resource != null) {
        String resourceContent = RegistryUtils.decodeBytes((byte[]) resource.getContent());
        try {
            OMElement omElement = AXIOMUtil.stringToOM(resourceContent);
            Iterator mainChildIt = omElement.getChildren();
            while (mainChildIt.hasNext()) {
                Object childObj = mainChildIt.next();
                if ((childObj instanceof OMElement) && ((APIConstants.OVERVIEW_ELEMENT)
                        .equals(((OMElement) childObj).getLocalName()))) {
                    Iterator childIt = ((OMElement) childObj)
                            .getChildrenWithLocalName(APIConstants.ENDPOINT_PASSWORD_ELEMENT);
                    //There is only one ep-password, hence no iteration
                    if (childIt.hasNext()) {
                        OMElement child = (OMElement) childIt.next();
                        String actualPassword = child.getText();
                        //Store the password in a hidden property to access in the PUT method.
                        if (!actualPassword.isEmpty()) {
                            resource.setProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY, actualPassword);
                            child.setText(APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD);
                        }
                    }
                }
            }
            resource.setContent(RegistryUtils.encodeString(omElement.toString()));
            log.debug("Modified API resource content with default password before get operation");
        } catch (XMLStreamException e) {
            log.error("There was an error in reading XML Stream during API get.");
            throw new RegistryException("There was an error reading the API resource.", e);
        }
    }
    return resource;
}
 
Example 15
Source File: RegistryManager.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Persist a serializable object in the registry with the given resource path.
 *
 * @param serializableObject object to be persisted.
 */
public synchronized void persist(String resourcePath, Serializable serializableObject) throws RegistryException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Persisting resource in registry: [resource-path] %s", resourcePath));
    }

    Registry registry = getRegistry();

    try {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        registry.beginTransaction();
        Resource nodeResource = registry.newResource();
        nodeResource.setContent(serializeToByteArray(serializableObject));
        registry.put(resourcePath, nodeResource);
        registry.commitTransaction();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Resource persisted successfully in registry: [resource-path] %s",
                    resourcePath));
        }
    } catch (Exception e) {
       try {
           registry.rollbackTransaction();
       }catch (Exception e1){
           if (log.isErrorEnabled()) {
               log.error("Could not rollback transaction", e1);
           }
       }
        String msg = "Failed to persist resource in registry: " + resourcePath;
        throw new RegistryException(msg, e);
    }
}
 
Example 16
Source File: SecurityConfigAdmin.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void persistPolicy(AxisService service, OMElement policy, String policyID) throws RegistryException {

        //Registry registryToLoad = SecurityServiceHolder.getRegistryService().getConfigSystemRegistry();
        Resource resource = registry.newResource();
        resource.setContent(policy.toString());
        String servicePath = getRegistryServicePath(service);
        String policyResourcePath = servicePath + RegistryResources.POLICIES + policyID;
        registry.put(policyResourcePath, resource);

    }
 
Example 17
Source File: MigrateData.java    From product-es with Apache License 2.0 5 votes vote down vote up
private void updateResource(Registry registry, String path) throws RegistryException {
    if (registry.resourceExists(path)) {
        Resource resource = registry.get(path);
        String content = new String((byte[]) resource.getContent());
        if (content.contains(Constants.LOGIN_SCRIPT)) {
            content = content.replace(Constants.LOGIN_PERMISSION, "");
            content = content.replace(Constants.PERMISSION_ACTION, "");
            resource.setContent(content);
            registry.put(path, resource);
        }

    }
}
 
Example 18
Source File: APIManagerComponent.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
private void updateRegistryResourceContent(Resource resource, UserRegistry systemRegistry, String rxtDir, String rxtPath, String resourcePath) throws RegistryException, IOException {
    String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
    resource.setContent(rxt.getBytes(Charset.defaultCharset()));
    resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
    systemRegistry.put(resourcePath, resource);
}
 
Example 19
Source File: RegistryDataManager.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Encrypt the security policy password by new algorithm and update
 *
 * @param tenantId
 * @throws RegistryException
 * @throws CryptoException
 * @throws XMLStreamException
 */
private void updateSecurityPolicyPassword(int tenantId) throws RegistryException, CryptoException,
        XMLStreamException {
    InputStream resourceContent = null;
    XMLStreamReader parser = null;
    try {
        Registry registry = MigrationServiceDataHolder.getRegistryService().getConfigSystemRegistry(tenantId);
        List<String> policyPaths = getSTSPolicyPaths(registry);
        String newEncryptedPassword = null;
        for (String resourcePath : policyPaths) {
            if (registry.resourceExists(resourcePath)) {
                Resource resource = registry.get(resourcePath);
                resourceContent = resource.getContentStream();
                parser = XMLInputFactory.newInstance().createXMLStreamReader(resourceContent);
                StAXOMBuilder builder = new StAXOMBuilder(parser);
                OMElement documentElement = builder.getDocumentElement();
                Iterator it = documentElement.getChildrenWithName(new QName(Constant.CARBON_SEC_CONFIG));

                while (it != null && it.hasNext()) {
                    OMElement secConfig = (OMElement) it.next();
                    Iterator kerberosProperties = secConfig.getChildrenWithName(new QName(Constant.KERBEROS));
                    Iterator propertySet = null;
                    if ((kerberosProperties != null && kerberosProperties.hasNext())) {
                        propertySet = ((OMElement) kerberosProperties.next()).getChildElements();
                    }
                    if (propertySet != null) {
                        while (propertySet.hasNext()) {
                            OMElement kbProperty = (OMElement) propertySet.next();
                            if (Constant.SERVICE_PRINCIPAL_PASSWORD
                                    .equals(kbProperty.getAttributeValue(Constant.NAME_Q))) {
                                String encryptedPassword = kbProperty.getText();
                                newEncryptedPassword = Utility.getNewEncryptedValue(encryptedPassword);
                                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                                    kbProperty.setText(newEncryptedPassword);
                                }
                            }
                        }
                    }
                }
                if (StringUtils.isNotEmpty(newEncryptedPassword)) {
                    resource.setContent(RegistryUtils.encodeString(documentElement.toString()));
                    registry.beginTransaction();
                    registry.put(resourcePath, resource);
                    registry.commitTransaction();
                }
            }
        }
    } finally {
        try {
            if (parser != null) {
                parser.close();
            }
            if (resourceContent != null) {
                try {
                    resourceContent.close();
                } catch (IOException e) {
                    log.error("Error occurred while closing Input stream", e);
                }
            }
        } catch (XMLStreamException ex) {
            log.error("Error while closing XML stream", ex);
        }
    }

}
 
Example 20
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAllApiSpecificMediationPolicies()
        throws RegistryException, APIManagementException, IOException, XMLStreamException {
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    String parentCollectionPath =
            APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName()
                    + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR
                    + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
    parentCollectionPath = parentCollectionPath.substring(0, parentCollectionPath.lastIndexOf("/"));
    Collection parentCollection = new CollectionImpl();
    parentCollection.setChildren(new String[] {
            parentCollectionPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN,
            parentCollectionPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT,
            parentCollectionPath + RegistryConstants.PATH_SEPARATOR
                    + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT });
    Collection childCollection = new CollectionImpl();
    childCollection.setChildren(new String[] { "mediation1" });
    Mockito.when(registry.get(parentCollectionPath)).thenThrow(RegistryException.class)
            .thenReturn(parentCollection);
    Mockito.when(registry.get(
            parentCollectionPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN))
            .thenReturn(childCollection);

    Resource resource = new ResourceImpl();
    resource.setUUID(SAMPLE_RESOURCE_ID);

    String mediationPolicyContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<sequence xmlns=\"http://ws.apache.org/ns/synapse\" name=\"default-endpoint\">\n</sequence>";
    resource.setContent(mediationPolicyContent);
    Mockito.when(registry.get("mediation1")).thenReturn(resource);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
    try {
        abstractAPIManager.getAllApiSpecificMediationPolicies(identifier);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(
                e.getMessage().contains("Error occurred  while getting Api Specific mediation policies "));
    }
    Assert.assertEquals(abstractAPIManager.getAllApiSpecificMediationPolicies(identifier).size(), 1);
    PowerMockito.mockStatic(IOUtils.class);
    PowerMockito.mockStatic(AXIOMUtil.class);
    PowerMockito.when(IOUtils.toString((InputStream) Mockito.any(), Mockito.anyString()))
            .thenThrow(IOException.class).thenReturn(mediationPolicyContent);
    PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(XMLStreamException.class);
    abstractAPIManager.getAllApiSpecificMediationPolicies(identifier);// covers exception which is only logged
    abstractAPIManager.getAllApiSpecificMediationPolicies(identifier);// covers exception which is only logged
}