org.wso2.carbon.utils.CarbonUtils Java Examples

The following examples show how to use org.wso2.carbon.utils.CarbonUtils. 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: FileDataPublisherTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void tryPublish() throws Exception {
    PowerMockito.mockStatic(AgentHolder.class);
    AgentHolder agentHolder = Mockito.mock(AgentHolder.class);
    PowerMockito.when(AgentHolder.getInstance()).thenReturn(agentHolder);
    DataEndpointAgent dataEndpointAgent = Mockito.mock(DataEndpointAgent.class);
    Mockito.when(agentHolder.getDefaultDataEndpointAgent()).thenReturn(dataEndpointAgent);
    AgentConfiguration agentConfig = Mockito.mock(AgentConfiguration.class);
    Mockito.when(dataEndpointAgent.getAgentConfiguration()).thenReturn(agentConfig);
    Mockito.when(agentConfig.getQueueSize()).thenReturn(32768);
    String carbonHome = System.getProperty(Constants.CARBON_HOME);
    String carbonConfigPath = System.getProperty(CARBON_HOME) + CARBON_CONFIGS_PATH;
    PowerMockito.mockStatic(CarbonUtils.class);
    PowerMockito.when(CarbonUtils.getCarbonHome()).thenReturn(carbonHome);
    PowerMockito.when(CarbonUtils.getCarbonConfigDirPath()).thenReturn(carbonConfigPath);
    DataBridgeRequestResponseStreamPublisherDTO dataBridgeRequestStreamPublisherDTO = Mockito.mock(DataBridgeRequestResponseStreamPublisherDTO.class);
    FileDataPublisher fileDataPublisher = new FileDataPublisher();
    fileDataPublisher.tryPublish("org.wso2.apimgt.statistics.request:1.0.0", 12324343,
            (Object[]) dataBridgeRequestStreamPublisherDTO.createMetaData(), null,
            (Object[]) dataBridgeRequestStreamPublisherDTO.createPayload());
}
 
Example #2
Source File: DefaultServiceURLBuilderTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {

    mockStatic(CarbonUtils.class);
    mockStatic(ServerConfiguration.class);
    mockStatic(NetworkUtils.class);
    mockStatic(IdentityCoreServiceComponent.class);
    mockStatic(IdentityTenantUtil.class);
    mockStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext privilegedCarbonContext = mock(PrivilegedCarbonContext.class);

    when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    when(ServerConfiguration.getInstance()).thenReturn(mockServerConfiguration);
    when(IdentityCoreServiceComponent.getConfigurationContextService()).thenReturn(mockConfigurationContextService);
    when(mockConfigurationContextService.getServerConfigContext()).thenReturn(mockConfigurationContext);
    when(mockConfigurationContext.getAxisConfiguration()).thenReturn(mockAxisConfiguration);
    try {
        when(NetworkUtils.getLocalHostname()).thenReturn("localhost");
    } catch (SocketException e) {
        // Mock behaviour, hence ignored
    }

    System.setProperty(IdentityConstants.CarbonPlaceholders.CARBON_PORT_HTTP_PROPERTY, "9763");
    System.setProperty(IdentityConstants.CarbonPlaceholders.CARBON_PORT_HTTPS_PROPERTY, "9443");
}
 
Example #3
Source File: TokenGenTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    PowerMockito.mockStatic(CarbonUtils.class);
    PowerMockito.mockStatic(SubscriptionDataHolder.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    Mockito.when(serverConfiguration.getFirstProperty(APIConstants.PORT_OFFSET_CONFIG)).thenReturn("2");
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    String dbConfigPath = System.getProperty("APIManagerDBConfigurationPath");
    APIManagerConfiguration config = new APIManagerConfiguration();
    config.load(dbConfigPath);
    ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(
            new APIManagerConfigurationServiceImpl(config));
    SubscriptionDataStore subscriptionDataStore = Mockito.mock(SubscriptionDataStore.class);
    SubscriptionDataHolder subscriptionDataHolder = Mockito.mock(SubscriptionDataHolder.class);
    PowerMockito.when(SubscriptionDataHolder.getInstance()).thenReturn(subscriptionDataHolder);
    PowerMockito.when(SubscriptionDataHolder.getInstance()
            .getTenantSubscriptionStore(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))
            .thenReturn(subscriptionDataStore);
    Application application = new Application();
    application.setId(1);
    application.setName("app2");
    application.setUUID(UUID.randomUUID().toString());
    application.addAttribute("abc","cde");
    Mockito.when(subscriptionDataStore.getApplicationById(1)).thenReturn(application);
}
 
Example #4
Source File: XssCsrfSkipPatternsTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Configures ESB as required for the test case.
 *
 * @throws Exception if an error occurs while configuring ESB
 */
private void changeESBConfiguration() throws Exception {

    String carbonHome = CarbonUtils.getCarbonHome();
    carbonXML = new File(
            carbonHome + File.separator + "conf" + File.separator + "carbon.xml");
    File configuredCarbonXML = new File(
            getESBResourceLocation() + File.separator + "XssCsrfSkipPatterns" + File.separator
            + "carbon-security.xml");

    catalinaXML = new File(
            carbonHome + File.separator + "conf" + File.separator + "tomcat"
            + File.separator + "catalina-server.xml");

    File configuredCatalinaXML = new File(
            getESBResourceLocation() + File.separator + "XssCsrfSkipPatterns" + File.separator
            + "catalina-server-security.xml");

    scm = new ServerConfigurationManager(context);
    scm.applyConfigurationWithoutRestart(configuredCarbonXML, carbonXML, true);
    scm.applyConfigurationWithoutRestart(configuredCatalinaXML, catalinaXML, true);
    scm.restartGracefully();
    super.init();
}
 
Example #5
Source File: XssCsrfSkipPatternsTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Resets the configuration changes done to what was there before.
 *
 * @throws Exception if an error occurs while applying previous configurations
 */
private void resetESBConfiguration() throws Exception {

    String carbonHome = CarbonUtils.getCarbonHome();
    carbonXML = new File(
            carbonHome + File.separator + "conf" + File.separator + "carbon.xml");
    File configuredCarbonXML = new File(
            getESBResourceLocation() + File.separator + "XssCsrfSkipPatterns" + File.separator
            + "carbon-default.xml");

    catalinaXML = new File(
            carbonHome + File.separator + "conf" + File.separator + "tomcat"
            + File.separator + "catalina-server.xml");
    File configuredCatalinaXML = new File(
            getESBResourceLocation() + File.separator + "XssCsrfSkipPatterns" + File.separator
            + "catalina-server-default.xml");

    scm = new ServerConfigurationManager(context);
    scm.applyConfigurationWithoutRestart(configuredCarbonXML, carbonXML, true);
    scm.applyConfigurationWithoutRestart(configuredCatalinaXML, catalinaXML, true);
    scm.restartGracefully();
}
 
Example #6
Source File: CloudServiceConfigParser.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static CloudServicesDescConfig loadCloudServicesConfiguration() throws Exception {
    if (cloudServicesDescConfig != null) {
        return cloudServicesDescConfig;
    }

    synchronized (loadlock) {
        if (cloudServicesDescConfig == null) {
            try {
                String configFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
                        StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator + CONFIG_FILENAME;
                OMElement configElement = CommonUtil.buildOMElement(new FileInputStream(configFileName));
                cloudServicesDescConfig = new CloudServicesDescConfig(configElement);
            } catch (Exception e) {
                String msg = "Error in building the cloud service configuration.";
                log.error(msg, e);
                throw new Exception(msg, e);
            }
        }
    }
    return cloudServicesDescConfig;
}
 
Example #7
Source File: FileDataPublisherTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void shutdown() throws Exception {
    String carbonHome = System.getProperty(Constants.CARBON_HOME);
    PowerMockito.mockStatic(CarbonUtils.class);
    PowerMockito.when(CarbonUtils.getCarbonHome()).thenReturn(carbonHome);
    PowerMockito.mockStatic(AgentHolder.class);
    AgentHolder agentHolder = Mockito.mock(AgentHolder.class);
    PowerMockito.when(AgentHolder.getInstance()).thenReturn(agentHolder);
    DataEndpointAgent dataEndpointAgent = Mockito.mock(DataEndpointAgent.class);
    Mockito.when(agentHolder.getDefaultDataEndpointAgent()).thenReturn(dataEndpointAgent);
    AgentConfiguration agentConfig = Mockito.mock(AgentConfiguration.class);
    Mockito.when(dataEndpointAgent.getAgentConfiguration()).thenReturn(agentConfig);
    Mockito.when(agentConfig.getQueueSize()).thenReturn(32768);
    FileDataPublisher fileDataPublisher = new FileDataPublisher();
    fileDataPublisher.shutdown();
}
 
Example #8
Source File: HostObjectUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get the running transport port
 *
 * @param transport [http/https]
 * @return port
 */
public static String getBackendPort(String transport) {
    int port;
    String backendPort;
    try {
        port = CarbonUtils.getTransportProxyPort(getConfigContext(), transport);
        if (port == -1) {
            port = CarbonUtils.getTransportPort(getConfigContext(), transport);
        }
        backendPort = Integer.toString(port);
        return backendPort;
    } catch (APIManagementException e) {
        log.error(e.getMessage());
        return null;

    }
}
 
Example #9
Source File: URLPrinterStartupHandler.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private String getServerUrl() {
    // Hostname
    String hostName = "localhost";
    try {
        hostName = NetworkUtils.getMgtHostName();
    } catch (Exception ignored) {
    }
    // HTTPS port
    String mgtConsoleTransport = CarbonUtils.getManagementTransport();
    ConfigurationContextService configContextService =
            UrlPrinterDataHolder.getInstance().getConfigurationContextService();
    int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
    int httpsProxyPort =
            CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), mgtConsoleTransport);
    if (httpsProxyPort > 0) {
        port = httpsProxyPort;
    }
    return "https://" + hostName + ":" + port + "/devicemgt";
}
 
Example #10
Source File: DeploymentSyncAxis2ConfigurationContextObserver.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
@Override
public void creatingConfigurationContext(int tenantId) {
    try {
        if (!CarbonRepositoryUtils.isSynchronizerEnabled(tenantId)) {
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("Initializing the deployment synchronizer for tenant: " + tenantId);
        }

        DeploymentSynchronizer depsync =
                CarbonRepositoryUtils.newCarbonRepositorySynchronizer(tenantId);

        if (GhostDeployerUtils.isGhostOn() && GhostDeployerUtils.isPartialUpdateEnabled()
                && CarbonUtils.isWorkerNode() && tenantId > 0) {
            depsync.syncGhostMetaArtifacts();
        } else {
            depsync.doInitialSyncUp();
        }
        //TODO: Need to sync up only the ghost metadata is ghost deployment has been enabled
    } catch (DeploymentSynchronizerException e) {
        log.error("Error while initializing the deployment synchronizer for tenant: " + tenantId);
    }
}
 
Example #11
Source File: RemoteAuthorizationManagerClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Query the remote user manager to find out whether the specified user has the
 * specified permission.
 *
 * @param user Username
 * @param permission A valid Carbon permission
 * @return true if the user has the specified permission and false otherwise
 * @throws APIManagementException If and error occurs while accessing the admin service
 */
public boolean isUserAuthorized(String user, String permission) throws APIManagementException {
    CarbonUtils.setBasicAccessSecurityHeaders(username, password, authorizationManager._getServiceClient());
    if (cookie != null) {
        authorizationManager._getServiceClient().getOptions().setProperty(HTTPConstants.COOKIE_STRING, cookie);
    }

    try {
        boolean authorized = authorizationManager.isUserAuthorized(user, permission,
                CarbonConstants.UI_PERMISSION_ACTION);
        ServiceContext serviceContext = authorizationManager.
                _getServiceClient().getLastOperationContext().getServiceContext();
        cookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);
        return authorized;
    } catch (Exception e) {
        throw new APIManagementException("Error while accessing backend services for " +
                "user permission validation", e);
    }
}
 
Example #12
Source File: EntitlementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static void addSamplePolicies(Registry registry) {

        File policyFolder = new File(CarbonUtils.getCarbonHome() + File.separator
                + "repository" + File.separator + "resources" + File.separator
                + "identity" + File.separator + "policies" + File.separator + "xacml"
                + File.separator + "default");

        File[] fileList;
        if (policyFolder.exists() && ArrayUtils.isNotEmpty(fileList = policyFolder.listFiles())) {
            for (File policyFile : fileList) {
                if (policyFile.isFile()) {
                    PolicyDTO policyDTO = new PolicyDTO();
                    try {
                        policyDTO.setPolicy(FileUtils.readFileToString(policyFile));
                        EntitlementUtil.addFilesystemPolicy(policyDTO, registry, false);
                    } catch (Exception e) {
                        // log and ignore
                        log.error("Error while adding sample XACML policies", e);
                    }
                }
            }
        }
    }
 
Example #13
Source File: DeviceManagerUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public static String getServerBaseHttpsUrl() {
    String hostName = "localhost";
    try {
        hostName = NetworkUtils.getMgtHostName();
    } catch (Exception ignored) {
    }
    String mgtConsoleTransport = CarbonUtils.getManagementTransport();
    ConfigurationContextService configContextService =
            DeviceManagementDataHolder.getInstance().getConfigurationContextService();
    int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
    int httpsProxyPort =
            CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
                    mgtConsoleTransport);
    if (httpsProxyPort > 0) {
        port = httpsProxyPort;
    }
    return "https://" + hostName + ":" + port;
}
 
Example #14
Source File: DeviceManagerUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public static String getServerBaseHttpUrl() {
    String hostName = "localhost";
    try {
        hostName = NetworkUtils.getMgtHostName();
    } catch (Exception ignored) {
    }
    ConfigurationContextService configContextService =
            DeviceManagementDataHolder.getInstance().getConfigurationContextService();
    int port = CarbonUtils.getTransportPort(configContextService, "http");
    int httpProxyPort =
            CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
                    "http");
    if (httpProxyPort > 0) {
        port = httpProxyPort;
    }
    return "http://" + hostName + ":" + port;
}
 
Example #15
Source File: UrlMapperAdminService.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public String getHttpPort () throws UrlMapperException {
    int port = 0;
    if(getConfigContext().getAxisConfiguration().getTransportIn("http") != null) {
        port = CarbonUtils.getTransportProxyPort(getConfigContext(), "http");
        if (port == -1) {
            port  = CarbonUtils.getTransportPort(getConfigContext(), "http");
        }
    }
    return Integer.toString(port);
}
 
Example #16
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private String getEnrollmentTemplateName(String deviceType) {
    String templateName = deviceType + "-enrollment-invitation";
    File template = new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator
            + "resources" + File.separator + "email-templates" + File.separator + templateName
            + ".vm");
    if (template.exists()) {
        return templateName;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("The template that is expected to use is not available. Therefore, using default template.");
        }
    }
    return DeviceManagementConstants.EmailAttributes.DEFAULT_ENROLLMENT_TEMPLATE;
}
 
Example #17
Source File: SamplesInvoker.java    From product-ei with Apache License 2.0 5 votes vote down vote up
private static void initUserAdminStub() throws Exception {
    userAdminStub = new UserAdminStub(USER_MANAGEMENT_SERVICE_URL);

    ServiceClient serviceClient = userAdminStub._getServiceClient();
    Options serviceClientOptions = serviceClient.getOptions();
    serviceClientOptions.setManageSession(true);
    CarbonUtils.setBasicAccessSecurityHeaders("admin", "admin", serviceClient);
}
 
Example #18
Source File: DeviceSchemaInitializer.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public DeviceSchemaInitializer(DataSource dataSource, String deviceType, String tenantDomain) {
	super(dataSource);
	String tenantSeperator = "";
	if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
		tenantSeperator = tenantDomain + File.separator;
	}

	setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
			+ File.separator + "cdm" + File.separator + "plugins" + File.separator + tenantSeperator
			+ deviceType + File.separator;
}
 
Example #19
Source File: ThrottlePolicyTemplateBuilder.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Generate policy for subscription level.
 * @param policy policy with level 'sub'. Multiple pipelines are not allowed. Can define more than one condition
 * as set of conditions. all these conditions should be passed as a single pipeline 
 * @return
 * @throws APITemplateException
 */
public String getThrottlePolicyForSubscriptionLevel(SubscriptionPolicy policy) throws APITemplateException {
    StringWriter writer = new StringWriter();

    if (log.isDebugEnabled()) {
        log.debug("Generating policy for subscriptionLevel :" + policy.toString());
    }

    if (!(policy instanceof SubscriptionPolicy)) {
        throw new APITemplateException("Invalid policy level :  Has to be 'sub'");
    }
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        velocityengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                CommonsLogLogChute.class.getName());
        if (!"not-defined".equalsIgnoreCase(getVelocityLogger())) {
            velocityengine.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
            velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        }
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        velocityengine.init();
        Template t = velocityengine.getTemplate(getTemplatePathForSubscription());

        VelocityContext context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
        context.put("quotaPolicy", policy.getDefaultQuotaPolicy());
        t.merge(context, writer);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }
    } catch (Exception e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }

    return writer.toString();
}
 
Example #20
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateDocArtifactContent() throws GovernanceException, APIManagementException {
    API api = getUniqueAPI();
    PowerMockito.mockStatic(CarbonUtils.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    Mockito.when(serverConfiguration.getFirstProperty("WebContextRoot")).thenReturn("/abc").thenReturn("/");
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Documentation documentation = new Documentation(DocumentationType.HOWTO, "this is a doc");
    documentation.setSourceType(Documentation.DocumentSourceType.FILE);
    documentation.setCreatedDate(new Date(System.currentTimeMillis()));
    documentation.setSummary("abcde");
    documentation.setVisibility(Documentation.DocumentVisibility.API_LEVEL);
    documentation.setSourceUrl("/abcd/def");
    documentation.setOtherTypeName("aa");
    APIUtil.createDocArtifactContent(genericArtifact, api.getId(), documentation);
    documentation.setSourceType(Documentation.DocumentSourceType.INLINE);
    APIUtil.createDocArtifactContent(genericArtifact, api.getId(), documentation);
    documentation.setSourceType(Documentation.DocumentSourceType.URL);
    APIUtil.createDocArtifactContent(genericArtifact, api.getId(), documentation);

    try {
        documentation.setSourceType(Documentation.DocumentSourceType.URL);
        Mockito.doThrow(GovernanceException.class).when(genericArtifact).setAttribute(APIConstants
                .DOC_SOURCE_URL, documentation.getSourceUrl());
        APIUtil.createDocArtifactContent(genericArtifact, api.getId(), documentation);
        Assert.fail();
    } catch (APIManagementException ex) {
        Assert.assertTrue(ex.getMessage().contains("Failed to create doc artifact content from :"));
    }
}
 
Example #21
Source File: ClaimCache.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static ClaimCache getInstance() {
    CarbonUtils.checkSecurity();
    if (instance == null) {
        synchronized (ClaimCache.class) {
            if (instance == null) {
                instance = new ClaimCache();
            }
        }
    }
    return instance;
}
 
Example #22
Source File: HostUtil.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public static String getHttpPort() throws UrlMapperException {
	DataHolder dataHolder = DataHolder.getInstance();
	try {
		return CarbonUtils.getBackendHttpPort(dataHolder.getServerConfigContext());
	} catch (Exception e) {
		log.error("Failed to retrieve the backend http port ", e);
		throw new UrlMapperException("Failed to retrieve the backend http port ", e);
	}

}
 
Example #23
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private String getEnrollmentTemplateName(String deviceType) {
    String templateName = deviceType + "-enrollment-invitation";
    File template = new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator
            + "resources" + File.separator + "email-templates" + File.separator + templateName
            + ".vm");
    if (template.exists()) {
        return templateName;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("The template that is expected to use is not available. Therefore, using default template.");
        }
    }
    return DeviceManagementConstants.EmailAttributes.DEFAULT_ENROLLMENT_TEMPLATE;
}
 
Example #24
Source File: RegistryConfiguratorTestCase.java    From product-es with Apache License 2.0 5 votes vote down vote up
public static OMElement getRegistryXmlOmElement()
        throws FileNotFoundException, XMLStreamException {

    String registryXmlPath = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator
            + "conf" + File.separator + "registry.xml";
    File registryFile = new File(registryXmlPath);
    FileInputStream inputStream = new FileInputStream(registryFile);
    XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
    StAXOMBuilder builder = new StAXOMBuilder(parser);
    return builder.getDocumentElement();

}
 
Example #25
Source File: EntitlementServiceComponent.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Read the port from identity.xml which is overridden by carbon.xml to facilitating
 * multiple servers at a time.
 */
private int readThriftReceivePort() {
    int port = -1;
    String portValue = IdentityUtil.getProperty(ThriftConfigConstants.PARAM_RECEIVE_PORT);
    //if the port contains a template string that refers to carbon.xml
    if ((portValue.contains("${")) && (portValue.contains("}"))) {
        port = (CarbonUtils.getPortFromServerConfig(portValue));
    } else { //if port directly mentioned in identity.xml
        port = Integer.parseInt(portValue);
    }
    return port;
}
 
Example #26
Source File: ServerStartupListener.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public static void waitAndInitialize() {
    try {
        String mgtTransport = CarbonUtils.getManagementTransport();
        AxisConfiguration axisConfiguration = ServiceReferenceHolder
                .getContextService().getServerConfigContext().getAxisConfiguration();
        int mgtTransportPort = CarbonUtils.getTransportProxyPort(axisConfiguration, mgtTransport);
        if (mgtTransportPort <= 0) {
            mgtTransportPort = CarbonUtils.getTransportPort(axisConfiguration, mgtTransport);
        }
        // Using localhost as the hostname since this is always an internal admin service call.
        // Hostnames that can be retrieved using other approaches does not work in this context.
        url = mgtTransport + "://" + TenantInitializationConstants.LOCAL_HOST_NAME + ":" + mgtTransportPort
                + "/services/";
        adminName = ServiceDataHolder.getInstance().getRealmService()
                .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration()
                .getAdminUserName();
        adminPwd = ServiceDataHolder.getInstance().getRealmService()
                .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration()
                .getAdminPassword().toCharArray();
        executor = new ScheduledThreadPoolExecutor(1);
        executor.scheduleAtFixedRate(new ScheduledThreadPoolExecutorImpl(),
                TenantInitializationConstants.DEFAULT_WAIT_DURATION,
                TenantInitializationConstants.DEFAULT_WAIT_DURATION, TimeUnit.SECONDS);
    } catch (UserStoreException e) {
        log.error("An error occurred while retrieving admin credentials for initializing on-premise " +
                "gateway configuration.", e);
    }
}
 
Example #27
Source File: UserStoreConfigComponent.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This method invoked when the bundle get activated, it touches the super-tenants user store
 * configuration with latest time stamp. This invokes undeploy and deploy method
 */
private void triggerDeployerForSuperTenantSecondaryUserStores() {

    String repositoryPath = CarbonUtils.getCarbonRepository();
    int repoLength = repositoryPath.length();

    /**
     * This operation is done to make sure if the getCarbonRepository method doesn't return a
     * file path with File.Separator at the end, this will add it
     * If repositoryPath is ,<CARBON_HOME>/repository/deployment this method will add
     * File.separator at the end. If not this will exit
     */
    String fSeperator = repositoryPath.substring(repoLength - 1, repoLength);
    if (!fSeperator.equals(File.separator)) {
        repositoryPath += File.separator;
    }
    String superTenantUserStorePath = repositoryPath + "userstores" + File.separator;

    File folder = new File(superTenantUserStorePath);
    File[] listOfFiles = folder.listFiles();

    if (listOfFiles != null) {
        for (File file : listOfFiles) {
            if (file != null) {
                String ext = FilenameUtils.getExtension(file.getAbsolutePath());
                if (isValidExtension(ext)) {
                    try {
                        FileUtils.touch(new File(file.getAbsolutePath()));
                    } catch (IOException e) {
                        String errMsg = "Error occurred while trying to touch " + file.getName() +
                                ". Passwords will continue to remain in plaintext";
                        log.error(errMsg, e);
                        // continuing here since user stores are still functional
                        // except the passwords are in plain text
                    }
                }
            }
        }
    }
}
 
Example #28
Source File: RegistryConfiguratorTestCase.java    From product-es with Apache License 2.0 5 votes vote down vote up
public static OMElement getAxis2XmlOmElement()
        throws FileNotFoundException, XMLStreamException {
    String axis2XmlPath = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator
            + "conf" + File.separator + "axis2" + File.separator + "axis2_client.xml";

    File axis2File = new File(axis2XmlPath);

    FileInputStream inputStream = new FileInputStream(axis2File);
    XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
    StAXOMBuilder builder = new StAXOMBuilder(parser);

    return builder.getDocumentElement();
}
 
Example #29
Source File: ThrottlePolicyTemplateBuilder.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Generate application level policy.
 * 
 * @param policy policy with level 'app'. Multiple pipelines are not allowed. Can define more than one condition
 *            as set of conditions. all these conditions should be passed as a single pipeline
 * @return
 * @throws APITemplateException
 */
public String getThrottlePolicyForAppLevel(ApplicationPolicy policy) throws APITemplateException {
    StringWriter writer = new StringWriter();

    if (log.isDebugEnabled()) {
        log.debug("Generating policy for appLevel :" + policy.toString());
    }

    if (!(policy instanceof ApplicationPolicy)) {
        throw new APITemplateException("Invalid policy level : Has to be 'app'");
    }
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        velocityengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                CommonsLogLogChute.class.getName());
        if (!"not-defined".equalsIgnoreCase(getVelocityLogger())) {
            velocityengine.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
            velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        }
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        velocityengine.init();
        Template template = velocityengine.getTemplate(getTemplatePathForApplication());

        VelocityContext context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
        context.put("quotaPolicy", policy.getDefaultQuotaPolicy());
        template.merge(context, writer);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }

    } catch (Exception e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }
    String str = writer.toString();
    return writer.toString();
}
 
Example #30
Source File: CartridgeSubscriptionDataPublisher.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private static void createDataPublisher() throws StratosManagerException {
    // creating the agent
    ServerConfiguration serverConfig = CarbonUtils.getServerConfiguration();
    String trustStorePath = serverConfig.getFirstProperty("Security.TrustStore.Location");
    String trustStorePassword = serverConfig.getFirstProperty("Security.TrustStore.Password");

    //value is in the carbon.xml file and should be set to the thrift port of BAM
    String bamServerUrl = serverConfig.getFirstProperty("BamServerURL");

    //getting the BAM related values from cartridge-config.properties
    String adminUsername = System.getProperty(CartridgeConstants.BAM_ADMIN_USERNAME);
    String adminPassword = System.getProperty(CartridgeConstants.BAM_ADMIN_PASSWORD);

    System.setProperty("javax.net.ssl.trustStore", trustStorePath);
    System.setProperty("javax.net.ssl.trustStorePassword",
            trustStorePassword);

    try {
        dataPublisher = new AsyncDataPublisher(
                "tcp://" + bamServerUrl + "", adminUsername, adminPassword);
        initializeStream();
        dataPublisher.addStreamDefinition(streamDefinition);
    } catch (Exception e) {
        String msg = "Unable to create a data publisher to " + bamServerUrl;
        log.error(msg, e);
        throw new StratosManagerException(msg, e);
    }
}