Java Code Examples for org.wso2.carbon.utils.CarbonUtils

The following examples show how to use org.wso2.carbon.utils.CarbonUtils. 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
Source Project: carbon-identity-framework   Source File: EntitlementUtil.java    License: 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 2
@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 3
@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 4
Source Project: carbon-apimgt   Source File: HostObjectUtils.java    License: 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 5
Source Project: product-ei   Source File: XssCsrfSkipPatternsTestCase.java    License: 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 6
Source Project: product-ei   Source File: XssCsrfSkipPatternsTestCase.java    License: 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 7
Source Project: carbon-apimgt   Source File: FileDataPublisherTest.java    License: 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 Project: carbon-apimgt   Source File: FileDataPublisherTest.java    License: 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 9
Source Project: carbon-device-mgt   Source File: DeviceManagerUtil.java    License: 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 10
Source Project: carbon-device-mgt   Source File: DeviceManagerUtil.java    License: 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 11
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 12
/**
 * 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 13
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 14
Source Project: carbon-commons   Source File: CloudServiceConfigParser.java    License: 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 15
Source Project: carbon-apimgt   Source File: APIGatewayAdminClient.java    License: Apache License 2.0 5 votes vote down vote up
public APIGatewayAdminClient(Environment environment) throws AxisFault {
    //String qualifiedName = apiId.getProviderName() + "--" + apiId.getApiName() + ":v" + apiId.getVersion();
    //String qualifiedDefaultApiName = apiId.getProviderName() + "--" + apiId.getApiName();
    //String providerDomain = apiId.getProviderName();
    //providerDomain = APIUtil.replaceEmailDomainBack(providerDomain);
    ConfigurationContext ctx = ServiceReferenceHolder.getInstance().getAxis2ConfigurationContext();
    apiGatewayAdminStub = new APIGatewayAdminStub(ctx, environment.getServerURL() + "APIGatewayAdmin");
    setup(apiGatewayAdminStub, environment);

    CarbonUtils.setBasicAccessSecurityHeaders(environment.getUserName(), environment.getPassword(),
            apiGatewayAdminStub._getServiceClient());
}
 
Example 16
Source Project: carbon-apimgt   Source File: EntitlementServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method will initiate entitlement service client which calls PDP
 *
 * @throws Exception whenever if failed to initiate client properly.
 */
public EntitlementServiceClient() throws Exception {
    ConfigurationContext configContext;
    try {
        String repositoryBasePath = CarbonUtils.getCarbonHome() + File.separator + "repository";
        String clientRepo = repositoryBasePath +
                File.separator + "deployment" + File.separator + "client";
        String clientAxisConf = repositoryBasePath +
                File.separator + "conf" + File.separator + "axis2" + File.separator + "axis2_client.xml";

        configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(clientRepo, clientAxisConf);
        String serviceEndPoint = EntitlementClientUtils.getServerUrl() + "EntitlementService";
        entitlementServiceStub =
                new EntitlementServiceStub(configContext, serviceEndPoint);
        ServiceClient client = entitlementServiceStub._getServiceClient();
        Options option = client.getOptions();
        option.setProperty(HTTPConstants.COOKIE_STRING, null);
        HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
        auth.setUsername(EntitlementClientUtils.getServerUsername());
        auth.setPassword(EntitlementClientUtils.getServerPassword());
        auth.setPreemptiveAuthentication(true);
        option.setProperty(HTTPConstants.AUTHENTICATE, auth);
        option.setManageSession(true);
    } catch (Exception e) {
        logger.error("Error while initiating entitlement service client ", e);
    }
}
 
Example 17
/**
 * Returns the Singleton of <code>ApplicationMgtSystemConfig</code>
 *
 * @return
 */
public static ApplicationMgtSystemConfig getInstance() {

    CarbonUtils.checkSecurity();
    if (instance == null) {
        synchronized (ApplicationMgtSystemConfig.class) {
            if (instance == null) {
                instance = new ApplicationMgtSystemConfig();
            }
        }
    }
    return instance;
}
 
Example 18
private Integer fetchPort() {

        String mgtTransport = CarbonUtils.getManagementTransport();
        AxisConfiguration axisConfiguration = IdentityCoreServiceComponent.getConfigurationContextService().
                getServerConfigContext().getAxisConfiguration();
        int port = CarbonUtils.getTransportProxyPort(axisConfiguration, mgtTransport);
        if (port <= 0) {
            port = CarbonUtils.getTransportPort(axisConfiguration, mgtTransport);
        }
        return port;
    }
 
Example 19
/**
 * Sets the current used KeyStoreManagerExtension with the new extension.
 *
 * Care must be taken not to set KeyStoreManagerExtension to null as it throws a NullPointerException.
 * 
 * @param keyStoreManagerExtension the new KeyStoreManagerExtension, can not be set to null,
 *                                 it has to be valid KeyStoreManagerExtension reference..
 */
protected void setKeyStoreManagerExtension(KeyStoreManagerExtension keyStoreManagerExtension) {
    CarbonUtils.checkSecurity();
    if (log.isDebugEnabled()) {
        log.debug("Setting the current KeyStoreManagerExtension with new KeyStoreManagerExtension : "
                + keyStoreManagerExtension);
    }
    if (keyStoreManagerExtension == null) {
        throw new NullPointerException(
                "The " + DefaultKeyProviderService.class.getName() + " can not be set with null "
                        + KeyStoreManagerExtension.class.getName());
    }
    this.keyStoreManagerExtension = keyStoreManagerExtension;
}
 
Example 20
Source Project: carbon-apimgt   Source File: APIManagerComponent.java    License: Apache License 2.0 5 votes vote down vote up
private void addTierPolicies() throws APIManagementException {
    String apiTierFilePath = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "default-tiers" + File.separator + APIConstants.DEFAULT_API_TIER_FILE_NAME;
    String appTierFilePath = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "default-tiers" + File.separator + APIConstants.DEFAULT_APP_TIER_FILE_NAME;
    String resTierFilePath = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "default-tiers" + File.separator + APIConstants.DEFAULT_RES_TIER_FILE_NAME;
    addTierPolicy(APIConstants.API_TIER_LOCATION, apiTierFilePath);
    addTierPolicy(APIConstants.APP_TIER_LOCATION, appTierFilePath);
    addTierPolicy(APIConstants.RES_TIER_LOCATION, resTierFilePath);
}
 
Example 21
Source Project: attic-stratos   Source File: CommonUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the configurations from the stratos configuration file.
 *
 * @return stratos configurations
 */
public static StratosConfiguration loadStratosConfiguration() {
    // gets the configuration file name from the StratosConstants.
    String StratosConfigFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator +
            StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
            StratosConstants.STRATOS_CONF_FILE;
    return loadStratosConfiguration(StratosConfigFileName);
}
 
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
@Test
public void testAddPath() {

    String testPath = "/testPath";
    String urlPath = null;
    when(CarbonUtils.getManagementTransport()).thenReturn("https");
    try {
        urlPath = ServiceURLBuilder.create().addPath(testPath).build().getPath();
    } catch (URLBuilderException e) {
        // Mock behaviour, hence ignored
    }

    assertEquals(urlPath, testPath);
}
 
Example 24
/**
 * Initialize the validator with the synapse environment.
 *
 * @throws APISecurityException If an authentication failure or some other error occurs
 */
BasicAuthCredentialValidator() throws APISecurityException {
    this.gatewayKeyCacheEnabled = isGatewayTokenCacheEnabled();
    this.getGatewayUsernameCache();

    ConfigurationContext configurationContext = ServiceReferenceHolder.getInstance().getAxis2ConfigurationContext();
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfiguration();
    String username = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME);
    String password = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD);
    String url = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_URL);
    if (url == null) {
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                "API key manager URL unspecified");
    }

    try {
        apiKeyMgtRemoteUserStoreMgtServiceStub = new APIKeyMgtRemoteUserStoreMgtServiceStub(configurationContext, url +
                "APIKeyMgtRemoteUserStoreMgtService");
        ServiceClient client = apiKeyMgtRemoteUserStoreMgtServiceStub._getServiceClient();
        Options options = client.getOptions();
        options.setCallTransportCleanup(true);
        options.setManageSession(true);
        CarbonUtils.setBasicAccessSecurityHeaders(username, password, client);
    } catch (AxisFault axisFault) {
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, axisFault.getMessage(), axisFault);
    }
}
 
Example 25
@Test
public void testAddParameter() {

    String parameterValue = null;
    when(CarbonUtils.getManagementTransport()).thenReturn("https");
    try {
        parameterValue = ServiceURLBuilder.create().addParameter("key", "value").build().getParameter("key");
    } catch (URLBuilderException e) {
        // Mock behaviour, hence ignored
    }

    assertEquals(parameterValue, "value");
}
 
Example 26
@Test
public void testSetFragment() {

    when(CarbonUtils.getManagementTransport()).thenReturn("https");
    String fragment = null;
    try {
        fragment = ServiceURLBuilder.create().setFragment("fragment").build().getFragment();
    } catch (URLBuilderException e) {
        // Mock behaviour, hence ignored
    }

    assertEquals(fragment, "fragment");
}
 
Example 27
@Test
public void testAddFragmentParameter() {

    String fragment = null;
    when(CarbonUtils.getManagementTransport()).thenReturn("https");
    try {
        fragment =
                ServiceURLBuilder.create().addFragmentParameter("key1", "value1").addFragmentParameter("key2",
                        "value2").build().getFragment();
    } catch (URLBuilderException e) {
        // Mock behaviour, hence ignored
    }

    assertEquals(fragment, "key1=value1&key2=value2");
}
 
Example 28
@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 29
Source Project: attic-stratos   Source File: ValidationServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
public ValidationServiceClient(String backendServerURL, String username, String password) throws Exception {
    String serviceURL = backendServerURL + "OAuth2TokenValidationService";
    try {
        stub = new OAuth2TokenValidationServiceStub(serviceURL);
        CarbonUtils.setBasicAccessSecurityHeaders(username, password, true, stub._getServiceClient());
    } catch (AxisFault e) {
        log.error("Error initializing OAuth2 Client");
        throw new Exception("Error initializing OAuth Client", e);
    }
}
 
Example 30
@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");
}