Java Code Examples for org.wso2.carbon.base.ServerConfiguration

The following examples show how to use org.wso2.carbon.base.ServerConfiguration. These examples are extracted from open source projects. 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
private void createKeyStore(Class realClass, WithKeyStore withKeyStore) {

        try {
            RegistryService registryService = createRegistryService(realClass, withKeyStore.tenantId(),
                                                                    withKeyStore.tenantDomain());
            ServerConfiguration serverConfigurationService = ServerConfiguration.getInstance();
            serverConfigurationService.init(realClass.getResourceAsStream("/repository/conf/carbon.xml"));
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(withKeyStore.tenantId(),
                                                                          serverConfigurationService,
                                                                          registryService);
            if (!Proxy.isProxyClass(keyStoreManager.getClass()) &&
                    !keyStoreManager.getClass().getName().contains("EnhancerByMockitoWithCGLIB")  ) {
                KeyStore keyStore = ReadCertStoreSampleUtil.createKeyStore(getClass());
                org.wso2.carbon.identity.testutil.Whitebox.setInternalState(keyStoreManager, "primaryKeyStore",
                                                                            keyStore);
                org.wso2.carbon.identity.testutil.Whitebox.setInternalState(keyStoreManager, "registryKeyStore",
                                                                            keyStore);
            }
            CarbonCoreDataHolder.getInstance().setRegistryService(registryService);
            CarbonCoreDataHolder.getInstance().setServerConfigurationService(serverConfigurationService);
        } catch (Exception e) {
            throw new TestCreationException(
                    "Unhandled error while reading cert for test class:  " + realClass.getName(), e);
        }
    }
 
Example 2
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {

    JSch def = super.createDefaultJSch(fs);
    String keyName = ServerConfiguration.getInstance().
            getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_NAME);
    String keyPath = ServerConfiguration.getInstance().
            getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_PATH);

    if (keyName == null || keyName.isEmpty())
        keyName = GitDeploymentSynchronizerConstants.SSH_KEY;

    if (keyPath == null || keyPath.isEmpty())
        keyPath = System.getProperty("user.home") + "/" + GitDeploymentSynchronizerConstants.SSH_KEY_DIRECTORY;

    if (keyPath.endsWith("/"))
        def.addIdentity(keyPath + keyName);
    else
        def.addIdentity(keyPath + "/" + keyName);

    return def;
}
 
Example 3
Source Project: carbon-identity-framework   Source File: KeyStoreAdmin.java    License: Apache License 2.0 6 votes vote down vote up
public Key getPrivateKey(String alias, boolean isSuperTenant) throws SecurityConfigException {
    KeyStoreData[] keystores = getKeyStores(isSuperTenant);
    KeyStore keyStore = null;
    String privateKeyPassowrd = null;

    try {

        for (int i = 0; i < keystores.length; i++) {
            if (KeyStoreUtil.isPrimaryStore(keystores[i].getKeyStoreName())) {
                KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
                keyStore = keyMan.getPrimaryKeyStore();
                ServerConfiguration serverConfig = ServerConfiguration.getInstance();
                privateKeyPassowrd = serverConfig
                        .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
                return keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
            }
        }
    } catch (Exception e) {
        String msg = "Error has encounted while loading the key for the given alias " + alias;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
    return null;
}
 
Example 4
@Test
public void testGetPaginatedKeystoreInfo() throws Exception {

    mockStatic(ServerConfiguration.class);
    when(ServerConfiguration.getInstance()).thenReturn(serverConfiguration);

    mockStatic(KeyStoreManager.class);
    when(KeyStoreManager.getInstance(anyInt())).thenReturn(keyStoreManager);
    when(keyStoreManager.getKeyStore("wso2carbon.jks")).thenReturn(getKeyStoreFromFile("wso2carbon.jks",
            "wso2carbon"));
    when(serverConfiguration.getFirstProperty(SERVER_TRUSTSTORE_FILE)).thenReturn(createPath("wso2carbon.jks").toString());
    when(serverConfiguration.getFirstProperty(SERVER_TRUSTSTORE_PASSWORD)).thenReturn("wso2carbon");

    mockStatic(KeyStoreUtil.class);
    when(KeyStoreUtil.isPrimaryStore(any())).thenReturn(true);

    mockStatic(KeyStoreManager.class);
    when(KeyStoreManager.getInstance(tenantID)).thenReturn(keyStoreManager);
    when(keyStoreManager.getPrimaryKeyStore()).thenReturn(getKeyStoreFromFile("wso2carbon.jks", "wso2carbon"));

    keyStoreAdmin = new KeyStoreAdmin(tenantID, registry);
    PaginatedKeyStoreData result = keyStoreAdmin.getPaginatedKeystoreInfo("wso2carbon.jks", 10);
    int actualKeysNo = findCertDataSetSize(result.getPaginatedKeyData().getCertDataSet());
    assertEquals(actualKeysNo, 3, "Incorrect key numbers");

}
 
Example 5
/**
 * Returns a ServiceURL with the protocol, hostname, port, proxy context path, a web context
 * root and the tenant domain (appended if required).
 *
 * @return {@link ServiceURL}.
 * @throws URLBuilderException If error occurred while constructing the URL.
 */
@Override
public ServiceURL build() throws URLBuilderException {

    String protocol = fetchProtocol();
    String proxyHostName = fetchProxyHostName();
    String internalHostName = fetchInternalHostName();
    int port = fetchPort();
    String tenantDomain = resolveTenantDomain();
    String proxyContextPath = ServerConfiguration.getInstance().getFirstProperty(PROXY_CONTEXT_PATH);
    String resolvedFragment = buildFragment(fragment, fragmentParams);
    String urlPath = getResolvedUrlPath(tenantDomain);

    return new ServiceURLImpl(protocol, proxyHostName, internalHostName, port, tenantDomain, proxyContextPath, urlPath,
            parameters, resolvedFragment);
}
 
Example 6
@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 7
@Test(dataProvider = "getRelativePublicURLData")
public void testGetRelativePublicURL(String protocol, String hostName, int port, String proxyContextPath,
                                     String tenantNameFromContext, boolean enableTenantURLSupport,
                                     String expected, String urlPath) {

    when(CarbonUtils.getManagementTransport()).thenReturn(protocol);
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME)).thenReturn(hostName);
    when(CarbonUtils.getTransportProxyPort(mockAxisConfiguration, protocol)).thenReturn(port);
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants
            .PROXY_CONTEXT_PATH)).thenReturn(proxyContextPath);
    when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(enableTenantURLSupport);
    when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantNameFromContext);
    when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()).thenReturn("carbon.super");

    String relativePublicUrl = null;
    try {
        relativePublicUrl = ServiceURLBuilder.create().addPath(urlPath).build().getRelativePublicURL();
    } catch (URLBuilderException e) {
        //Mock behaviour, hence ignored
    }
    assertEquals(relativePublicUrl, expected);
}
 
Example 8
@Test(dataProvider = "getRelativeInternalURLData")
public void testGetRelativeInternalURL(String protocol, String hostName, int port, String proxyContextPath,
                                       String tenantNameFromContext, boolean enableTenantURLSupport,
                                       String expected, String urlPath) {

    when(CarbonUtils.getManagementTransport()).thenReturn(protocol);
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME)).thenReturn(hostName);
    when(CarbonUtils.getTransportProxyPort(mockAxisConfiguration, protocol)).thenReturn(port);
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants
            .PROXY_CONTEXT_PATH)).thenReturn(proxyContextPath);
    when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(enableTenantURLSupport);
    when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantNameFromContext);
    when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()).thenReturn("carbon.super");

    String relativeInternalUrl = null;
    try {
        relativeInternalUrl = ServiceURLBuilder.create().addPath(urlPath).build().getRelativeInternalURL();
    } catch (URLBuilderException e) {
        //Mock behaviour, hence ignored
    }
    assertEquals(relativeInternalUrl, expected);
}
 
Example 9
@Activate
protected void activate(ComponentContext context) {
    BundleContext bundleContext = context.getBundleContext();
    WorkflowManagementService workflowService = new WorkflowManagementServiceImpl();
    bundleContext.registerService(WorkflowManagementService.class, workflowService, null);
    WorkflowServiceDataHolder.getInstance().setWorkflowService(workflowService);
    WorkflowServiceDataHolder.getInstance().setBundleContext(bundleContext);
    ServiceRegistration serviceRegistration = context.getBundleContext().registerService(WorkflowListener.class.getName(), new WorkflowAuditLogger(), null);
    context.getBundleContext().registerService(WorkflowExecutorManagerListener.class.getName(), new WorkflowExecutorAuditLogger(), null);
    if (serviceRegistration != null) {
        if (log.isDebugEnabled()) {
            log.debug("WorkflowAuditLogger registered.");
        }
    } else {
        log.error("Workflow Audit Logger could not be registered.");
    }
    if (System.getProperty(WFConstant.KEYSTORE_SYSTEM_PROPERTY_ID) == null) {
        System.setProperty(WFConstant.KEYSTORE_SYSTEM_PROPERTY_ID, ServerConfiguration.getInstance().getFirstProperty(WFConstant.KEYSTORE_CARBON_CONFIG_PATH));
    }
    if (System.getProperty(WFConstant.KEYSTORE_PASSWORD_SYSTEM_PROPERTY_ID) == null) {
        System.setProperty(WFConstant.KEYSTORE_PASSWORD_SYSTEM_PROPERTY_ID, ServerConfiguration.getInstance().getFirstProperty(WFConstant.KEYSTORE_PASSWORD_CARBON_CONFIG_PATH));
    }
}
 
Example 10
Source Project: carbon-device-mgt   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
private static SSLSocketFactory getTrustedSSLSocketFactory() {
    try {
        String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
        String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
        String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
                "Security.TrustStore.Password");
        String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
                "Security.TrustStore.Location");
        KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,KEY_STORE_TYPE);
        KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword);

        return initSSLConnection(keyStore,keyStorePassword,trustStore);
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            |CertificateException | IOException | UnrecoverableKeyException e) {
        log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e);
        return null;
    }

}
 
Example 11
Source Project: carbon-identity   Source File: SignKeyDataHolder.java    License: Apache License 2.0 6 votes vote down vote up
public SignKeyDataHolder() throws Exception {
    try {
        String keyAlias = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.KeyAlias");
        KeyStoreManager keyMan = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
        Certificate[] certificates = keyMan.getPrimaryKeyStore().getCertificateChain(keyAlias);
        issuerPK = keyMan.getDefaultPrivateKey();
        issuerCerts = new X509Certificate[certificates.length];
        int i = 0;
        for (Certificate certificate : certificates) {
            issuerCerts[i++] = (X509Certificate) certificate;
        }
        signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA;
        String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
        }

    } catch (Exception e) {
        throw new Exception("Error while reading the key", e);
    }

}
 
Example 12
protected void activate(ComponentContext ctxt) {
    try {
        ConfigurationContext mainConfigCtx = configContextService.getServerConfigContext();
        AxisConfiguration mainAxisConfig = mainConfigCtx.getAxisConfiguration();
        BundleContext bundleCtx = ctxt.getBundleContext();
        String enablePoxSecurity = ServerConfiguration.getInstance()
                .getFirstProperty("EnablePoxSecurity");
        if (enablePoxSecurity == null || "true".equals(enablePoxSecurity)) {
            mainAxisConfig.engageModule(POX_SECURITY_MODULE);
        } else {
            log.info("POX Security Disabled");
        }

        bundleCtx.registerService(SecurityConfigAdmin.class.getName(),
                new SecurityConfigAdmin(mainAxisConfig,
                        registryService.getConfigSystemRegistry(),
                        null),
                null);
        bundleCtx.registerService(Axis2ConfigurationContextObserver.class.getName(),
                new SecurityAxis2ConfigurationContextObserver(),
                null);
        log.debug("Security Mgt bundle is activated");
    } catch (Throwable e) {
        log.error("Failed to activate SecurityMgtServiceComponent", e);
    }
}
 
Example 13
Source Project: carbon-identity   Source File: KeyStoreAdmin.java    License: Apache License 2.0 6 votes vote down vote up
public Key getPrivateKey(String alias, boolean isSuperTenant) throws SecurityConfigException {
    KeyStoreData[] keystores = getKeyStores(isSuperTenant);
    KeyStore keyStore = null;
    String privateKeyPassowrd = null;

    try {

        for (int i = 0; i < keystores.length; i++) {
            if (KeyStoreUtil.isPrimaryStore(keystores[i].getKeyStoreName())) {
                KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
                keyStore = keyMan.getPrimaryKeyStore();
                ServerConfiguration serverConfig = ServerConfiguration.getInstance();
                privateKeyPassowrd = serverConfig
                        .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
                return keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
            }
        }
    } catch (Exception e) {
        String msg = "Error has encounted while loading the key for the given alias " + alias;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
    return null;
}
 
Example 14
public IdentityApplicationManagementServiceClient(String epr) throws AxisFault {

        XMLConfiguration conf = ConfUtil.getInstance(null).getConfiguration();
        int autosclaerSocketTimeout = conf.getInt("autoscaler.identity.clientTimeout", 180000);
        try {
            ServerConfiguration serverConfig = CarbonUtils.getServerConfiguration();
            String trustStorePath = serverConfig.getFirstProperty("Security.TrustStore.Location");
            String trustStorePassword = serverConfig.getFirstProperty("Security.TrustStore.Password");
            String type = serverConfig.getFirstProperty("Security.TrustStore.Type");

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

            stub = new IdentityApplicationManagementServiceStub(epr);
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, autosclaerSocketTimeout);
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, autosclaerSocketTimeout);
	        String username = conf.getString("autoscaler.identity.adminUser", "admin");
            Utility.setAuthHeaders(stub._getServiceClient(), username);

        } catch (AxisFault axisFault) {
            String msg = "Failed to initiate identity service client. " + axisFault.getMessage();
            log.error(msg, axisFault);
            throw new AxisFault(msg, axisFault);
        }
    }
 
Example 15
Source Project: carbon-apimgt   Source File: APIStoreHostObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHTTPsURL() throws APIManagementException {
    Context cx = Mockito.mock(Context.class);
    Scriptable thisObj = Mockito.mock(Scriptable.class);
    Function funObj = Mockito.mock(Function.class);
    Object[] args = new Object[1];
    PowerMockito.mockStatic(CarbonUtils.class);
    PowerMockito.mockStatic(HostObjectUtils.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    PowerMockito.when(HostObjectUtils.getBackendPort("https")).thenReturn("9443");

    //when hostName is not set and when hostName is set in system property
    System.setProperty("carbon.local.ip", "127.0.0.1");
    Assert.assertEquals("https://127.0.0.1:9443", APIStoreHostObject.jsFunction_getHTTPsURL(cx, thisObj, args, funObj));

    //when hostName is not set and when hostName is set in carbon.xml
    Mockito.when(serverConfiguration.getFirstProperty("HostName")).thenReturn("localhost");
    Assert.assertEquals("https://localhost:9443", APIStoreHostObject.jsFunction_getHTTPsURL(cx, thisObj, args, funObj));

    //when hostName is set to a valid host
    args[0] = "https://localhost:9443/store/";
    Assert.assertEquals("https://localhost:9443", APIStoreHostObject.jsFunction_getHTTPsURL(cx, thisObj, args, funObj));

}
 
Example 16
Source Project: carbon-apimgt   Source File: DataPublisherUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String getHostAddress() {

        if (hostAddress != null) {
            return hostAddress;
        }
        hostAddress =   ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);
        if(null == hostAddress){
        	if (getLocalAddress() != null) {
        		hostAddress = getLocalAddress().getHostName();
        	}
            if (hostAddress == null) {
                hostAddress = UNKNOWN_HOST;
            }
            return hostAddress;
        }else {
            return hostAddress;
        }
    }
 
Example 17
Source Project: carbon-apimgt   Source File: TokenGenTest.java    License: 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 18
/**
 * This method is used internally to do the pagination purposes.
 *
 * @param pageNumber page Number
 * @param policySet  set of policies
 * @return PaginatedPolicySetDTO object containing the number of pages and the set of policies
 * that reside in the given page.
 */
private PaginatedPolicySetDTO doPaging(int pageNumber, PolicyDTO[] policySet) {

    PaginatedPolicySetDTO paginatedPolicySet = new PaginatedPolicySetDTO();
    if (policySet.length == 0) {
        paginatedPolicySet.setPolicySet(new PolicyDTO[0]);
        return paginatedPolicySet;
    }
    String itemsPerPage = EntitlementServiceComponent.getEntitlementConfig().
            getEngineProperties().getProperty(PDPConstants.ENTITLEMENT_ITEMS_PER_PAGE);
    if (itemsPerPage != null) {
        itemsPerPage = ServerConfiguration.getInstance().getFirstProperty("ItemsPerPage");
    }
    int itemsPerPageInt = PDPConstants.DEFAULT_ITEMS_PER_PAGE;
    if (itemsPerPage != null) {
        itemsPerPageInt = Integer.parseInt(itemsPerPage);
    }
    int numberOfPages = (int) Math.ceil((double) policySet.length / itemsPerPageInt);
    if (pageNumber > numberOfPages - 1) {
        pageNumber = numberOfPages - 1;
    }
    int startIndex = pageNumber * itemsPerPageInt;
    int endIndex = (pageNumber + 1) * itemsPerPageInt;
    PolicyDTO[] returnedPolicySet = new PolicyDTO[itemsPerPageInt];

    for (int i = startIndex, j = 0; i < endIndex && i < policySet.length; i++, j++) {
        returnedPolicySet[j] = policySet[i];
    }

    paginatedPolicySet.setPolicySet(returnedPolicySet);
    paginatedPolicySet.setNumberOfPages(numberOfPages);

    return paginatedPolicySet;
}
 
Example 19
/**
 * This method is used internally to do the pagination purposes.
 *
 * @param pageNumber    page Number
 * @param statusHolders <code>StatusHolder</code>
 * @return PaginatedPolicySetDTO object containing the number of pages and the set of policies
 * that reside in the given page.
 */
private PaginatedStatusHolder doPaging(int pageNumber, StatusHolder[] statusHolders) {

    PaginatedStatusHolder paginatedStatusHolder = new PaginatedStatusHolder();
    if (statusHolders.length == 0) {
        paginatedStatusHolder.setStatusHolders(new StatusHolder[0]);
        return paginatedStatusHolder;
    }
    String itemsPerPage = EntitlementServiceComponent.getEntitlementConfig().
            getEngineProperties().getProperty(PDPConstants.ENTITLEMENT_ITEMS_PER_PAGE);
    if (itemsPerPage != null) {
        itemsPerPage = ServerConfiguration.getInstance().getFirstProperty("ItemsPerPage");
    }
    int itemsPerPageInt = PDPConstants.DEFAULT_ITEMS_PER_PAGE;
    if (itemsPerPage != null) {
        itemsPerPageInt = Integer.parseInt(itemsPerPage);
    }
    int numberOfPages = (int) Math.ceil((double) statusHolders.length / itemsPerPageInt);
    if (pageNumber > numberOfPages - 1) {
        pageNumber = numberOfPages - 1;
    }
    int startIndex = pageNumber * itemsPerPageInt;
    int endIndex = (pageNumber + 1) * itemsPerPageInt;
    StatusHolder[] returnedHolders = new StatusHolder[itemsPerPageInt];

    for (int i = startIndex, j = 0; i < endIndex && i < statusHolders.length; i++, j++) {
        returnedHolders[j] = statusHolders[i];
    }

    paginatedStatusHolder.setStatusHolders(returnedHolders);
    paginatedStatusHolder.setNumberOfPages(numberOfPages);

    return paginatedStatusHolder;
}
 
Example 20
/**
 * This method is used internally to do the pagination purposes.
 *
 * @param pageNumber page Number
 * @param ids        <code>String</code>
 * @return PaginatedStringDTO object containing the number of pages and the set of policies
 * that reside in the given page.
 */
private PaginatedStringDTO doPagingString(int pageNumber, String[] ids) {

    PaginatedStringDTO paginatedStatusHolder = new PaginatedStringDTO();
    if (ids.length == 0) {
        paginatedStatusHolder.setStatusHolders(new String[0]);
        return paginatedStatusHolder;
    }

    String itemsPerPage = EntitlementServiceComponent.getEntitlementConfig().
            getEngineProperties().getProperty(PDPConstants.ENTITLEMENT_ITEMS_PER_PAGE);
    if (itemsPerPage != null) {
        itemsPerPage = ServerConfiguration.getInstance().getFirstProperty("ItemsPerPage");
    }
    int itemsPerPageInt = PDPConstants.DEFAULT_ITEMS_PER_PAGE;
    if (itemsPerPage != null) {
        itemsPerPageInt = Integer.parseInt(itemsPerPage);
    }
    int numberOfPages = (int) Math.ceil((double) ids.length / itemsPerPageInt);
    if (pageNumber > numberOfPages - 1) {
        pageNumber = numberOfPages - 1;
    }
    int startIndex = pageNumber * itemsPerPageInt;
    int endIndex = (pageNumber + 1) * itemsPerPageInt;
    String[] returnedHolders = new String[itemsPerPageInt];

    for (int i = startIndex, j = 0; i < endIndex && i < ids.length; i++, j++) {
        returnedHolders[j] = ids[i];
    }

    paginatedStatusHolder.setStatusHolders(returnedHolders);
    paginatedStatusHolder.setNumberOfPages(numberOfPages);

    return paginatedStatusHolder;
}
 
Example 21
Source Project: carbon-identity-framework   Source File: KeyStoreAdmin.java    License: Apache License 2.0 5 votes vote down vote up
public KeyStoreAdmin(int tenantId, Registry registry) {

        ServerConfiguration config = ServerConfiguration.getInstance();
        TRUST_STORE_LOCATION = config.getFirstProperty("Security.TrustStore.Location");
        TRUST_STORE_PASSWORD = config.getFirstProperty("Security.TrustStore.Password");
        this.registry = registry;
        this.tenantId = tenantId;
    }
 
Example 22
Source Project: carbon-identity-framework   Source File: IdentityUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to return a URL with a proxy context path, a web context root and the tenant domain (If
 * required) when provided with a URL context.
 *
 * @param endpoint            Endpoint.
 * @param addProxyContextPath Add proxy context path to the URL.
 * @param addWebContextRoot   Add web context path to the URL.
 * @return Complete URL for the given URL context.
 * @throws IdentityRuntimeException If error occurred while constructing the URL
 */
public static String getServerURL(String endpoint, boolean addProxyContextPath, boolean addWebContextRoot)
        throws IdentityRuntimeException {

    String hostName = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME);

    try {
        if (hostName == null) {
            hostName = NetworkUtils.getLocalHostname();
        }
    } catch (SocketException e) {
        throw IdentityRuntimeException.error("Error while trying to read hostname.", e);
    }

    String mgtTransport = CarbonUtils.getManagementTransport();
    AxisConfiguration axisConfiguration = IdentityCoreServiceComponent.getConfigurationContextService().
            getServerConfigContext().getAxisConfiguration();
    int mgtTransportPort = CarbonUtils.getTransportProxyPort(axisConfiguration, mgtTransport);
    if (mgtTransportPort <= 0) {
        mgtTransportPort = CarbonUtils.getTransportPort(axisConfiguration, mgtTransport);
    }
    if (hostName.endsWith("/")) {
        hostName = hostName.substring(0, hostName.length() - 1);
    }
    StringBuilder serverUrl = new StringBuilder(mgtTransport).append("://").append(hostName.toLowerCase());
    // If it's well known HTTPS port, skip adding port
    if (mgtTransportPort != IdentityCoreConstants.DEFAULT_HTTPS_PORT) {
        serverUrl.append(":").append(mgtTransportPort);
    }

    appendContextToUri(endpoint, addProxyContextPath, addWebContextRoot, serverUrl);
    return serverUrl.toString();
}
 
Example 23
Source Project: carbon-identity-framework   Source File: IdentityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isValidFileName(String fileName) {
    String fileNameRegEx = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.FILE_NAME_REGEX);

    if (isBlank(fileNameRegEx)) {
        fileNameRegEx = DEFAULT_FILE_NAME_REGEX;
    }

    Pattern pattern = Pattern.compile(fileNameRegEx, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE |
            Pattern.COMMENTS);
    Matcher matcher = pattern.matcher(fileName);
    return matcher.matches();
}
 
Example 24
Source Project: carbon-identity-framework   Source File: IdentityUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the host name of the server.
 *
 * @return Hostname
 */
public static String getHostName() {

    String hostName = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME);
    if (hostName == null) {
        try {
            hostName = NetworkUtils.getLocalHostname();
        } catch (SocketException e) {
            throw IdentityRuntimeException.error("Error while trying to read hostname.", e);
        }
    }
    return hostName;
}
 
Example 25
@Test
public void testBuild() {

    String absoluteUrl = null;
    String testPath1 = "/testPath1";
    String testPath2 = "testPath2/";
    String testPath3 = "/testPath3/";
    String[] keysList = {"key1", "key2", "key3"};
    String[] valuesList = {"value1", "value2", "value3"};
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants
            .PROXY_CONTEXT_PATH)).thenReturn("proxyContextPath");
    when(CarbonUtils.getManagementTransport()).thenReturn("https");
    when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(true);
    when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()).thenReturn("carbon.super");

    try {
        absoluteUrl =
                ServiceURLBuilder.create().addPath(testPath1, testPath2, testPath3).addParameter(keysList[0],
                        valuesList[0]).addParameter(keysList[1], valuesList[1]).addParameter(keysList[2],
                        valuesList[2]).addFragmentParameter(keysList[0], valuesList[0])
                        .addFragmentParameter(keysList[1], valuesList[1])
                        .addFragmentParameter(keysList[2], valuesList[2]).build().getAbsolutePublicURL();
    } catch (URLBuilderException e) {
        // Mock behaviour, hence ignored
    }

    assertEquals(absoluteUrl,
            "https://localhost:0/proxyContextPath/testPath1/testPath2/testPath3?key1%3Dvalue1%26key2%3Dvalue2" +
                    "%26key3%3Dvalue3#key1%3Dvalue1%26key2%3Dvalue2%26key3%3Dvalue3");
}
 
Example 26
@BeforeMethod
public void setUp() throws Exception {
    mockStatic(CarbonUtils.class);
    mockStatic(ServerConfiguration.class);
    mockStatic(NetworkUtils.class);
    mockStatic(IdentityCoreServiceComponent.class);
    mockStatic(IdentityConfigParser.class);
    mockStatic(CarbonUtils.class);
    mockStatic(IdentityTenantUtil.class);

    when(ServerConfiguration.getInstance()).thenReturn(mockServerConfiguration);
    when(IdentityCoreServiceComponent.getConfigurationContextService()).thenReturn(mockConfigurationContextService);
    when(mockConfigurationContextService.getServerConfigContext()).thenReturn(mockConfigurationContext);
    when(mockConfigurationContext.getAxisConfiguration()).thenReturn(mockAxisConfiguration);
    when(IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService);
    when(mockRealmService.getTenantManager()).thenReturn(mockTenantManager);
    when(CarbonUtils.getCarbonHome()).thenReturn("carbon.home");
    when(mockRequest.getRemoteAddr()).thenReturn("127.0.0.1");
    when(mockUserStoreManager.getRealmConfiguration()).thenReturn(mockRealmConfiguration);
    when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockRealmConfiguration);
    when(mockUserRealm.getUserStoreManager()).thenReturn(mockUserStoreManager);
    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 27
/**
 * Initializes the SSL Context
 */
private SSLContext initSSLConnection(String tenantAdminUser)
        throws NoSuchAlgorithmException, UnrecoverableKeyException,
               KeyStoreException, KeyManagementException, IOException, CertificateException {
    String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
    String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
            "Security.TrustStore.Password");
    String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
    String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
            "Security.TrustStore.Location");

    //Call to load the keystore.
    KeyStore keyStore = loadKeyStore(keyStoreLocation, keyStorePassword.toCharArray());
    //Call to load the TrustStore.
    KeyStore trustStore = loadTrustStore(trustStoreLocation, trustStorePassword.toCharArray());

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication

    SSLContext sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
    return sslContext;
}
 
Example 28
Source Project: product-iots   Source File: DeviceTypeUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static int getPortOffset() {
    ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
    String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(
            DeviceTypeConstants.CARBON_CONFIG_PORT_OFFSET));
    try {
        if ((portOffset != null)) {
            return Integer.parseInt(portOffset.trim());
        } else {
            return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET;
        }
    } catch (NumberFormatException e) {
        return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET;
    }
}
 
Example 29
Source Project: product-iots   Source File: DeviceTypeUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static int getPortOffset() {
    ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
    String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(
            DeviceTypeConstants.CARBON_CONFIG_PORT_OFFSET));
    try {
        if ((portOffset != null)) {
            return Integer.parseInt(portOffset.trim());
        } else {
            return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET;
        }
    } catch (NumberFormatException e) {
        return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET;
    }
}
 
Example 30
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);
    }
}