org.apache.axis2.util.JavaUtils Java Examples

The following examples show how to use org.apache.axis2.util.JavaUtils. 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: JavaAnalyzer.java    From coderadar with MIT License 6 votes vote down vote up
/**
 * Get fully classified dependencies and same package dependencies from a line. Possibilities for
 * there to be more than one dependency in one line: class A extends B, interface A extends B,
 * class A implements B, C, A a = new B(), A a = B.get(), private A a; B b; private A a =
 * B.get(C.create()); private A a = (B) C; method() throws ExceptionA catch (ExceptionB |
 * ExceptionC c) throw new ExceptionD C test = (D.isEmpty || E.isEmpty) ? A.get() : B.get()
 *
 * @param line line to check.
 * @return list of dependency Strings.
 */
public List<String> getDependenciesFromLine(String line) {
  List<String> foundDependencies = new ArrayList<>();
  String lineString = line;
  String separator = getFirstSeparator(lineString);
  while (separator != null) {
    Matcher fullyClassifiedMatcher = fullyClassifiedPattern.matcher(lineString);
    if (fullyClassifiedMatcher.find()
        && !JavaUtils.isJavaKeyword(fullyClassifiedMatcher.group())) {
      if (!foundDependencies.contains(fullyClassifiedMatcher.group())) {
        foundDependencies.add(fullyClassifiedMatcher.group());
      }
    }
    // split lineString at first found position of found separator
    lineString = lineString.substring(lineString.indexOf(separator) + separator.length());
    Matcher skipMatcher = skipPattern.matcher(lineString);
    if (skipMatcher.find()) {
      separator = getFirstSeparator(lineString);
    } else {
      separator = null;
    }
  }
  return foundDependencies;
}
 
Example #2
Source File: AbstractClientAuthHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean authenticateClient(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();

    //Skipping credential validation for saml2 bearer if not configured as needed
    if (StringUtils.isEmpty(oAuth2AccessTokenReqDTO.getClientSecret()) && org.wso2.carbon.identity.oauth.common
            .GrantType.SAML20_BEARER.toString().equals(oAuth2AccessTokenReqDTO.getGrantType()) && JavaUtils
            .isFalseExplicitly(authConfig)) {
        if (log.isDebugEnabled()) {
            log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType() + " " +
                    "Strict client validation set to : " + authConfig + " Authenticating without client secret");
        }
        return true;
    }

    if (log.isDebugEnabled()) {
        log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType() + " " +
                "Strict client validation set to : " + authConfig);
    }
    return false;
}
 
Example #3
Source File: ServerStartupListener.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public void completedServerStartup() {

    copyToExtensions();

    APIManagerConfiguration apiManagerConfiguration =
            ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    if (apiManagerConfiguration != null) {
        String defaultKeyManagerRegistration =
                apiManagerConfiguration.getFirstProperty(APIConstants.ENABLE_DEFAULT_KEY_MANAGER_REGISTRATION);
        if (StringUtils.isNotEmpty(defaultKeyManagerRegistration) &&
                JavaUtils.isTrueExplicitly(defaultKeyManagerRegistration)) {
            try {
                KeyMgtRegistrationService.registerDefaultKeyManager(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
            } catch (APIManagementException e) {
                log.error("Error while registering Default Key Manager for SuperTenant", e);
            }
        }
        String enableKeyManagerRetrieval =
                apiManagerConfiguration.getFirstProperty(APIConstants.ENABLE_KEY_MANAGER_RETRIVAL);
        if (JavaUtils.isTrueExplicitly(enableKeyManagerRetrieval)) {
            startConfigureKeyManagerConfigurations();
        }
    }
}
 
Example #4
Source File: RequestProcessorUtil.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether exposing the WSDL & WSDL elements such as schema & policy have been allowed
 *
 * @param service The AxisService which needs to be verified
 * @return true - if service metadata can be exposed, false - otherwise
 * @throws IOException If exposing WSDL & WSDL elements has been restricted.
 */
public static boolean canExposeServiceMetadata(AxisService service) throws IOException {
    Parameter exposeServiceMetadata = service.getParameter("exposeServiceMetadata");
    if (exposeServiceMetadata != null &&
        JavaUtils.isFalseExplicitly(exposeServiceMetadata.getValue())) {
        return false;
    }
    return true;
}
 
Example #5
Source File: AbstractClientAuthHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canAuthenticate(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();

    if (StringUtils.isNotEmpty(oAuth2AccessTokenReqDTO.getClientId()) &&
            StringUtils.isNotEmpty(oAuth2AccessTokenReqDTO.getClientSecret())) {
        if (log.isDebugEnabled()) {
            log.debug("Can authenticate with client ID and Secret." +
                    " Client ID: "+ oAuth2AccessTokenReqDTO.getClientId());
        }
        return true;

    } else {
        if (org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString().equals(
                oAuth2AccessTokenReqDTO.getGrantType())) {

            //Getting configured value for client credential validation requirements
            authConfig = properties.getProperty(
                    OAuthConstants.CLIENT_AUTH_CREDENTIAL_VALIDATION);

            if (log.isDebugEnabled()) {
                log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType());
            }

            //If user has set strict validation to false, can authenticate without credentials
            if (StringUtils.isNotEmpty(authConfig) && JavaUtils.isFalseExplicitly(authConfig)) {
                if (log.isDebugEnabled()) {
                    log.debug("Client auth credential validation set to : " + authConfig + ". " +
                            "can authenticate without client secret");
                }
                return true;
            }
        }
    }
    return false;
}
 
Example #6
Source File: APIMgtGoogleAnalyticsUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public GoogleAnalyticsConfig(OMElement config) {
    googleAnalyticsTrackingID = config
            .getFirstChildWithName(new QName(APIMgtUsagePublisherConstants.API_GOOGLE_ANALYTICS_TRACKING_ID))
            .getText();
    String googleAnalyticsEnabledStr = config.getFirstChildWithName(
            new QName(APIMgtUsagePublisherConstants.API_GOOGLE_ANALYTICS_TRACKING_ENABLED)).getText();
    enabled = googleAnalyticsEnabledStr != null && JavaUtils.isTrueExplicitly(googleAnalyticsEnabledStr);
}
 
Example #7
Source File: APIMgtGoogleAnalyticsTrackingHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public GoogleAnalyticsConfig(OMElement config) {
	googleAnalyticsTrackingID = config.getFirstChildWithName(new QName(
			APIMgtUsagePublisherConstants.API_GOOGLE_ANALYTICS_TRACKING_ID)).getText();
          String googleAnalyticsEnabledStr = config.getFirstChildWithName(new QName(
          		APIMgtUsagePublisherConstants.API_GOOGLE_ANALYTICS_TRACKING_ENABLED)).getText();
          enabled =  googleAnalyticsEnabledStr != null && JavaUtils.isTrueExplicitly(googleAnalyticsEnabledStr);
}
 
Example #8
Source File: MessageSender.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
private boolean isDiscoverable(AxisService service) {
    boolean isAdminService = JavaUtils.isTrueExplicitly(
            service.getParameterValue("adminService"));
    boolean isHiddenService = JavaUtils.isTrueExplicitly(
            service.getParameterValue("hiddenService"));
    boolean isUndiscoverableService = JavaUtils.isTrueExplicitly(
            service.getParameterValue(DiscoveryConstants.UNDISCOVERABLE_SERVICE));

    // do not sent the notifications for either hidden or admin services
    if (isAdminService || isHiddenService ||
            isUndiscoverableService || service.isClientSide()){
        return false;
    }
    return true;
}
 
Example #9
Source File: DiscoveryMgtUtils.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether service discovery is enabled in the configuration. This method first checks
 * whether the DiscoveryConstants.DISCOVERY_PROXY parameter is set in the given AxisConfiguration.
 * If not it checks whether service discovery status is set to 'true' in the configuration
 * registry. If discovery is enabled in the registry configuration, this method will also
 * add the corresponding parameter to AxisConfiguration.
 *
 * @param axisConfig AxisConfiguration
 * @return service discovery status
 * @throws RegistryException if an error occurs while accessing the registry
 */
public static boolean isServiceDiscoveryEnabled(AxisConfiguration axisConfig) throws RegistryException {
    Parameter parameter = getDiscoveryParam(axisConfig);
    if (parameter != null) {
        return true;
    }

    String path = DISCOVERY_CONFIG_ROOT + DISCOVERY_PUBLISHER_CONFIG;

    Registry registry = PrivilegedCarbonContext.getThreadLocalCarbonContext().
            getRegistry(RegistryType.SYSTEM_CONFIGURATION);
    if (registry.resourceExists(path)) {
        Resource publisherConfig = registry.get(path);
        String status = publisherConfig.getProperty(DISCOVERY_PUBLISHER_STATUS);
        publisherConfig.discard();
        boolean enabled = JavaUtils.isTrueExplicitly(status);

        if (enabled) {
            String discoveryProxyURL = getDiscoveryProxyURL(registry);
            try {
                Parameter discoveryProxyParam =
                        ParameterUtil.createParameter(DiscoveryConstants.DISCOVERY_PROXY,
                                                      discoveryProxyURL);
                axisConfig.addParameter(discoveryProxyParam);
            } catch (AxisFault axisFault) {
                axisFault.printStackTrace();  //TODO
            }
        }
        return enabled;
    }

    return false;
}
 
Example #10
Source File: APIManagerConfiguration.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private void setRuntimeArtifactsSyncPublisherConfig (OMElement omElement){

        OMElement enableElement = omElement
                .getFirstChildWithName(new QName(APIConstants.GatewayArtifactSynchronizer.ENABLE_CONFIG));
        if (enableElement != null) {
            gatewayArtifactSynchronizerProperties.setSaveArtifactsEnabled(
                    JavaUtils.isTrueExplicitly(enableElement.getText()));
        } else {
            log.debug("Save to storage is not set. Set to default false");
        }

        OMElement saverElement = omElement.getFirstChildWithName(
                new QName(APIConstants.GatewayArtifactSynchronizer.SAVER_CONFIG));
        if (saverElement != null) {
            String artifactSaver = saverElement.getText();
            gatewayArtifactSynchronizerProperties.setSaverName(artifactSaver);
        } else {
            log.debug("Artifact saver Element is not set. Set to default DB Saver");
        }

        OMElement publishDirectlyToGatewayElement = omElement
                .getFirstChildWithName(new QName(APIConstants.GatewayArtifactSynchronizer.PUBLISH_DIRECTLY_TO_GW_CONFIG));
        if (publishDirectlyToGatewayElement != null) {
            gatewayArtifactSynchronizerProperties.setPublishDirectlyToGatewayEnabled(
                    JavaUtils.isTrueExplicitly(publishDirectlyToGatewayElement.getText()));
        } else {
            log.debug("Publish directly to gateway is not set. Set to default true");
        }

    }
 
Example #11
Source File: APIManagerConfiguration.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private void setRuntimeArtifactsSyncGatewayConfig (OMElement omElement){

        OMElement enableElement = omElement
                .getFirstChildWithName(new QName(APIConstants.GatewayArtifactSynchronizer.ENABLE_CONFIG));
        if (enableElement != null) {
            gatewayArtifactSynchronizerProperties.setRetrieveFromStorageEnabled(
                    JavaUtils.isTrueExplicitly(enableElement.getText()));
        } else {
            log.debug("Retrieve from storage is not set. Set to default false");
        }

        OMElement retrieverElement = omElement.getFirstChildWithName(
                new QName(APIConstants.GatewayArtifactSynchronizer.RETRIEVER_CONFIG));
        if (retrieverElement != null) {
            String artifactRetriever = retrieverElement.getText();
            gatewayArtifactSynchronizerProperties.setRetrieverName(artifactRetriever);
        } else {
            log.debug("Artifact retriever Element is not set. Set to default DB Retriever");
        }

        OMElement gatewayLabelElement = omElement
                .getFirstChildWithName(new QName(APIConstants.GatewayArtifactSynchronizer.GATEWAY_LABELS_CONFIG));
        if (gatewayLabelElement != null) {
            Iterator labelsIterator = gatewayLabelElement
                    .getChildrenWithLocalName(APIConstants.GatewayArtifactSynchronizer.LABEL_CONFIG);
            while (labelsIterator.hasNext()) {
                OMElement labelElement = (OMElement) labelsIterator.next();
                if (labelElement != null) {
                    gatewayArtifactSynchronizerProperties.getGatewayLabels().add(labelElement.getText());
                }
            }
        }
    }
 
Example #12
Source File: SystemStatisticsDeploymentInterceptor.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
public void serviceUpdate(AxisEvent axisEvent, AxisService axisService) {

        if (SystemFilter.isFilteredOutService(axisService.getAxisServiceGroup()) || axisService.isClientSide()) {
            return;
        }
        if (axisEvent.getEventType() == AxisEvent.SERVICE_DEPLOY) {
            for (Iterator iter = axisService.getOperations(); iter.hasNext(); ) {
                AxisOperation op = (AxisOperation) iter.next();
                setCountersAndProcessors(op);
            }
            // see ESBJAVA-2327
            if (JavaUtils.isTrueExplicitly(axisService.getParameterValue("disableOperationValidation"))) {
                AxisOperation defaultOp = (AxisOperation) axisService.getParameterValue("_default_mediate_operation_");
                if (defaultOp != null) {
                    setCountersAndProcessors(defaultOp);
                }
            }
            // Service response time processor
            Parameter responseTimeProcessor = new Parameter();
            responseTimeProcessor.setName(StatisticsConstants.SERVICE_RESPONSE_TIME_PROCESSOR);
            responseTimeProcessor.setValue(new ResponseTimeProcessor());
            try {
                axisService.addParameter(responseTimeProcessor);
            } catch (AxisFault axisFault) {
                // will not occur
            }
        }
    }
 
Example #13
Source File: JMSListenerStartupShutdownListener.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public void completedServerStartup() {

    APIManagerConfiguration apimConfiguration = ServiceReferenceHolder.getInstance().getAPIMConfiguration();
    if (apimConfiguration != null) {
        String enableKeyManagerRetrieval =
                apimConfiguration.getFirstProperty(APIConstants.ENABLE_KEY_MANAGER_RETRIVAL);
        if (JavaUtils.isTrueExplicitly(enableKeyManagerRetrieval)) {
            jmsTransportHandlerForEventHub
                    .subscribeForJmsEvents(JMSConstants.TOPIC_KEY_MANAGER, new KeyManagerJMSMessageListener());
        }
    }
}
 
Example #14
Source File: CarbonRepositoryUtils.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Load the deployment synchronizer configuration from the global ServerConfiguration
 * of Carbon.
 *
 * @return a DeploymentSynchronizerConfiguration instance
 * @throws org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizerException on error
 */
public static DeploymentSynchronizerConfiguration getDeploymentSyncConfigurationFromConf() throws DeploymentSynchronizerException{

    DeploymentSynchronizerConfiguration config = new DeploymentSynchronizerConfiguration();
    ServerConfiguration serverConfig = ServerConfiguration.getInstance();

    String value = serverConfig.getFirstProperty(DeploymentSynchronizerConstants.ENABLED);
    //If Deployment Synchronizer Configuration is not found in carbon.xml
    if (value == null) {
        return null;
    }
    config.setEnabled(JavaUtils.isTrueExplicitly(value));

    if (config.isEnabled()) {
        value = serverConfig.getFirstProperty(DeploymentSynchronizerConstants.AUTO_CHECKOUT_MODE);
        config.setAutoCheckout(value != null && JavaUtils.isTrueExplicitly(value));

        value = serverConfig.getFirstProperty(DeploymentSynchronizerConstants.AUTO_COMMIT_MODE);
        config.setAutoCommit(value != null && JavaUtils.isTrueExplicitly(value));

        value = serverConfig.getFirstProperty(DeploymentSynchronizerConstants.USE_EVENTING);
        config.setUseEventing(value != null && JavaUtils.isTrueExplicitly(value));

        value = serverConfig.getFirstProperty(DeploymentSynchronizerConstants.AUTO_SYNC_PERIOD);
        if (value != null) {
            config.setPeriod(Long.parseLong(value));
        } else {
            config.setPeriod(DeploymentSynchronizerConstants.DEFAULT_AUTO_SYNC_PERIOD);
        }

        value = serverConfig.getFirstProperty(DeploymentSynchronizerConstants.REPOSITORY_TYPE);
        if (value != null) {
            config.setRepositoryType(value);
        } else {
            config.setRepositoryType(DeploymentSynchronizerConstants.DEFAULT_REPOSITORY_TYPE);
        }

        ArtifactRepository repository =
                RepositoryReferenceHolder.getInstance().getRepositoryByType(config.getRepositoryType());
        if (repository == null) {
            throw new DeploymentSynchronizerException("No Repository found for type " + config.getRepositoryType());
        }

        List<RepositoryConfigParameter> parameters = repository.getParameters();

        //If repository specific configuration parameters are found.
        if (parameters != null) {
            //Find the 'value' of each parameter from the server config by parameter 'name' and attach to parameter
            for (RepositoryConfigParameter parameter : parameters) {
                parameter.setValue(serverConfig.getFirstProperty(parameter.getName()));
            }

            //Attach parameter list to config object.
            config.setRepositoryConfigParameters(
                    parameters.toArray(new RepositoryConfigParameter[parameters.size()]));
        }

        return config;
    } else {
        return config;
    }
}
 
Example #15
Source File: PassThroughNHttpGetProcessor.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the HTML text for the list of services deployed.
 * This can be delegated to another Class as well
 * where it will handle more options of GET messages.
 *
 * @param prefix to be used for the Service names
 * @return the HTML to be displayed as a String
 */
protected String getServicesHTML(String prefix) {

    Map services = cfgCtx.getAxisConfiguration().getServices();
    Hashtable erroneousServices = cfgCtx.getAxisConfiguration().getFaultyServices();
    boolean servicesFound = false;

    StringBuffer resultBuf = new StringBuffer();
    resultBuf.append("<html><head><title>Axis2: Services</title></head>" + "<body>");

    if ((services != null) && !services.isEmpty()) {

        servicesFound = true;
        resultBuf.append("<h2>" + "Deployed services" + "</h2>");

        for (Object service : services.values()) {

            AxisService axisService = (AxisService) service;
            Parameter isHiddenService = axisService.getParameter(
                    NhttpConstants.HIDDEN_SERVICE_PARAM_NAME);
            Parameter isAdminService = axisService.getParameter("adminService");
            boolean isClientSide = axisService.isClientSide();

            boolean isSkippedService = (isHiddenService != null &&
                    JavaUtils.isTrueExplicitly(isHiddenService.getValue())) || (isAdminService != null &&
                    JavaUtils.isTrueExplicitly(isAdminService.getValue())) || isClientSide;
            if (axisService.getName().startsWith("__") || isSkippedService) {
                continue;    // skip private services
            }

            Iterator iterator = axisService.getOperations();
            resultBuf.append("<h3><a href=\"").append(prefix).append(axisService.getName()).append(
                    "?wsdl\">").append(axisService.getName()).append("</a></h3>");

            if (iterator.hasNext()) {
                resultBuf.append("Available operations <ul>");

                for (; iterator.hasNext();) {
                    AxisOperation axisOperation = (AxisOperation) iterator.next();
                    resultBuf.append("<li>").append(
                            axisOperation.getName().getLocalPart()).append("</li>");
                }
                resultBuf.append("</ul>");
            } else {
                resultBuf.append("No operations specified for this service");
            }
        }
    }

    if ((erroneousServices != null) && !erroneousServices.isEmpty()) {
        servicesFound = true;
        resultBuf.append("<hr><h2><font color=\"blue\">Faulty Services</font></h2>");
        Enumeration faultyservices = erroneousServices.keys();

        while (faultyservices.hasMoreElements()) {
            String faultyserviceName = (String) faultyservices.nextElement();
            resultBuf.append("<h3><font color=\"blue\">").append(
                    faultyserviceName).append("</font></h3>");
        }
    }

    if (!servicesFound) {
        resultBuf.append("<h2>There are no services deployed</h2>");
    }

    resultBuf.append("</body></html>");
    return resultBuf.toString();
}
 
Example #16
Source File: APIManagerAnalyticsConfiguration.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public void setAPIManagerConfiguration(APIManagerConfiguration config){
    String usageEnabled = config.getFirstProperty(APIConstants.API_USAGE_ENABLED);
    analyticsEnabled = JavaUtils.isTrueExplicitly(usageEnabled);
    if (analyticsEnabled){
        String skipEventReceiverConnStr = config.getFirstProperty(APIConstants.API_USAGE_SKIP_EVENT_RECEIVER_CONN);
        skipEventReceiverConnection = skipEventReceiverConnStr != null && JavaUtils.isTrueExplicitly
                (skipEventReceiverConnStr);
        String skipWorkflowDataPublisherStr = config
                .getFirstProperty(APIConstants.API_USAGE_SKIP_WORKFLOW_EVENT_RECEIVER_CONN);
        skipWorkFlowEventReceiverConnection =
                skipWorkflowDataPublisherStr != null && JavaUtils.isTrueExplicitly(skipWorkflowDataPublisherStr);
        publisherClass = config.getFirstProperty(APIConstants.API_USAGE_PUBLISHER_CLASS);
        requestStreamName = config.getFirstProperty(APIConstants.API_REQUEST_STREAM_NAME);
        requestStreamVersion = config.getFirstProperty(APIConstants.API_REQUEST_STREAM_VERSION);
        if (requestStreamName == null || requestStreamVersion == null) {
            log.error("Request stream name or version is null. Check api-manager.xml");
        }
        botDataStreamName = config.getFirstProperty("Analytics.Streams.botData.Name");
        botDataStreamVersion = config.getFirstProperty("Analytics.Streams.botData.Version");

        responseStreamName = config.getFirstProperty(APIConstants.API_RESPONSE_STREAM_NAME);
        responseStreamVersion = config.getFirstProperty(APIConstants.API_RESPONSE_STREAM_VERSION);

        faultStreamName = config.getFirstProperty(APIConstants.API_FAULT_STREAM_NAME);
        faultStreamVersion = config.getFirstProperty(APIConstants.API_FAULT_STREAM_VERSION);
        if (faultStreamName == null || faultStreamVersion == null) {
            log.error("Fault stream name or version is null. Check api-manager.xml");
        }
        throttleStreamName = config.getFirstProperty(APIConstants.API_THROTTLE_STREAM_NAME);
        throttleStreamVersion = config.getFirstProperty(APIConstants.API_THRORRLE_STREAM_VERSION);
        if (throttleStreamName == null || throttleStreamVersion == null) {
            log.error("Throttle stream name or version is null. Check api-manager.xml");
        }
        executionTimeStreamName = config.getFirstProperty(APIConstants.API_EXECUTION_TIME_STREAM_NAME);
        executionTimeStreamVersion = config.getFirstProperty(APIConstants.API_EXECUTION_TIME_STREAM_VERSION);

        alertTypeStreamName = config.getFirstProperty(APIConstants.API_ALERT_TYPES_STREAM_NAME);
        alertTypeStreamVersion = config.getFirstProperty(APIConstants.API_ALERT_TYPES_STREAM_VERSION);
        if (alertTypeStreamName == null || alertTypeStreamVersion == null) {
            log.error("Execution Time stream name or version is null. Check api-manager.xml");
        }

        dasReceiverUrlGroups = config.getFirstProperty(APIConstants.API_USAGE_BAM_SERVER_URL_GROUPS);
        dasReceiverAuthUrlGroups = config.getFirstProperty(APIConstants.API_USAGE_BAM_SERVER_AUTH_URL_GROUPS);
        dasReceiverServerUser = config.getFirstProperty(APIConstants.API_USAGE_BAM_SERVER_USER);
        dasReceiverServerPassword = config.getFirstProperty(APIConstants.API_USAGE_BAM_SERVER_PASSWORD);

        dasServerUrl = config.getFirstProperty(APIConstants.API_USAGE_DAS_REST_API_URL);
        dasServerUser = config.getFirstProperty(APIConstants.API_USAGE_DAS_REST_API_USER);
        dasServerPassword = config.getFirstProperty(APIConstants.API_USAGE_DAS_REST_API_PASSWORD);
        String build = config.getFirstProperty(APIConstants.API_USAGE_BUILD_MSG);
        buildMsg = build != null && JavaUtils.isTrueExplicitly(build);
        datacenterId = System.getProperty("datacenterId");
    }
}
 
Example #17
Source File: APIManagerConfiguration.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * To populate recommendation related configurations
 *
 * @param element
 */
private void setRecommendationConfigurations(OMElement element) {

    OMElement recommendationSeverEndpointElement = element.getFirstChildWithName(
            new QName(APIConstants.RECOMMENDATION_ENDPOINT));
    if (recommendationSeverEndpointElement != null) {
        recommendationEnvironment = new RecommendationEnvironment();
        String recommendationSeverEndpoint = recommendationSeverEndpointElement.getText();
        recommendationEnvironment.setRecommendationServerURL(recommendationSeverEndpoint);

        OMElement consumerKeyElement = element
                .getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_API_CONSUMER_KEY));
        if (consumerKeyElement != null) {
            if (secretResolver.isInitialized()
                    && secretResolver.isTokenProtected("APIManager.Recommendations.ConsumerKey")) {
                recommendationEnvironment.setConsumerKey(secretResolver
                        .resolve("APIManager.Recommendations.ConsumerKey"));
            } else {
                recommendationEnvironment.setConsumerKey(consumerKeyElement.getText());
            }

            OMElement consumerSecretElement = element
                    .getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_API_CONSUMER_SECRET));
            if (consumerSecretElement != null) {
                if (secretResolver.isInitialized()
                        && secretResolver.isTokenProtected("APIManager.Recommendations.ConsumerSecret")) {
                    recommendationEnvironment.setConsumerSecret(secretResolver
                            .resolve("APIManager.Recommendations.ConsumerSecret"));
                } else {
                    recommendationEnvironment.setConsumerSecret(consumerSecretElement.getText());
                }

                OMElement oauthEndpointElement = element
                        .getFirstChildWithName(new QName(APIConstants.AUTHENTICATION_ENDPOINT));
                String oauthEndpoint = null;
                if (oauthEndpointElement != null) {
                    oauthEndpoint = oauthEndpointElement.getText();
                } else {
                    try {
                        URL endpointURL = new URL(recommendationSeverEndpoint);
                        oauthEndpoint = endpointURL.getProtocol() + "://" + endpointURL.getHost() + ":"
                                + endpointURL.getPort();
                    } catch (MalformedURLException e) {
                        log.error("Error when reading the recommendationServer Endpoint", e);
                    }
                }
                recommendationEnvironment.setOauthURL(oauthEndpoint); //Oauth URL is set only if both consumer key
                // and consumer secrets are correctly defined
            }
        }

        OMElement applyForAllTenantsElement = element
                .getFirstChildWithName(new QName(APIConstants.APPLY_RECOMMENDATIONS_FOR_ALL_APIS));
        if (applyForAllTenantsElement != null) {
            recommendationEnvironment.setApplyForAllTenants(JavaUtils.isTrueExplicitly(applyForAllTenantsElement
                    .getText()));
        } else {
            log.debug("Apply For All Tenants Element is not set. Set to default true");
        }
        OMElement maxRecommendationsElement = element
                .getFirstChildWithName(new QName(APIConstants.MAX_RECOMMENDATIONS));
        if (maxRecommendationsElement != null) {
            recommendationEnvironment.setMaxRecommendations(Integer.parseInt(maxRecommendationsElement.getText()));
        } else {
            log.debug("Max recommendations is not set. Set to default 5");
        }
        OMElement userNameElement = element
                .getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_USERNAME));
        if (userNameElement != null) {
            recommendationEnvironment.setUserName(userNameElement.getText());
            log.debug("Basic OAuth used for recommendation server");
        }
        OMElement passwordElement = element
                .getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_PASSWORD));
        if (passwordElement != null) {
            if (secretResolver.isInitialized()
                    && secretResolver.isTokenProtected("APIManager.Recommendations.password")) {
                recommendationEnvironment.setPassword(secretResolver
                        .resolve("APIManager.Recommendations.password"));
            } else {
                recommendationEnvironment.setPassword(passwordElement.getText());
            }
        }
        OMElement waitDurationElement = element
                .getFirstChildWithName(new QName(APIConstants.WAIT_DURATION));
        if (waitDurationElement != null) {
            recommendationEnvironment.setWaitDuration(Long.parseLong(waitDurationElement.getText()));
        } else {
            log.debug("Max recommendations is not set. Set to default 5");
        }
    }
}
 
Example #18
Source File: APIManagerConfiguration.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * set workflow related configurations
 *
 * @param element
 */
private void setWorkflowProperties(OMElement element) {

    OMElement workflowConfigurationElement = element
            .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW));
    if (workflowConfigurationElement != null) {
        OMElement enableWorkflowElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_ENABLED));
        if (enableWorkflowElement != null) {
            workflowProperties.setEnabled(JavaUtils.isTrueExplicitly(enableWorkflowElement.getText()));
        }
        OMElement workflowServerUrlElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_SERVER_URL));
        if (workflowServerUrlElement != null) {
            workflowProperties.setServerUrl(APIUtil.replaceSystemProperty(workflowServerUrlElement.getText()));
        }
        OMElement workflowServerUserElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_SERVER_USER));
        if (workflowServerUserElement != null) {
            workflowProperties.setServerUser(APIUtil.replaceSystemProperty(workflowServerUserElement.getText()));
        }
        OMElement workflowDCRUserElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_DCR_EP_USER));
        if (workflowDCRUserElement != null) {
            workflowProperties.setdCREndpointUser(APIUtil.replaceSystemProperty(workflowDCRUserElement.getText()));
        }
        OMElement workflowCallbackElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_CALLBACK));
        if (workflowCallbackElement != null) {
            workflowProperties
                    .setWorkflowCallbackAPI(APIUtil.replaceSystemProperty(workflowCallbackElement.getText()));
        }

        OMElement workflowDCREPElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_DCR_EP));
        if (workflowDCREPElement != null) {
            workflowProperties.setdCREndPoint(APIUtil.replaceSystemProperty(workflowDCREPElement.getText()));
        }

        OMElement workflowTokenEpElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_TOKEN_EP));
        if (workflowTokenEpElement != null) {
            workflowProperties.setTokenEndPoint(APIUtil.replaceSystemProperty(workflowTokenEpElement.getText()));
        }
        OMElement workflowServerPasswordOmElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_SERVER_PASSWORD));
        String workflowServerPassword = MiscellaneousUtil.resolve(workflowServerPasswordOmElement, secretResolver);
        workflowServerPassword = APIUtil.replaceSystemProperty(workflowServerPassword);
        workflowProperties.setServerPassword(workflowServerPassword);

        OMElement dcrEPPasswordOmElement = workflowConfigurationElement
                .getFirstChildWithName(new QName(APIConstants.WorkflowConfigConstants.WORKFLOW_DCR_EP_PASSWORD));
        String dcrEPPassword = MiscellaneousUtil.resolve(dcrEPPasswordOmElement, secretResolver);
        dcrEPPassword = APIUtil.replaceSystemProperty(dcrEPPassword);
        workflowProperties.setdCREndpointPassword(dcrEPPassword);

    }
}
 
Example #19
Source File: OAuthServerConfiguration.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private void parseAuthorizationContextTokenGeneratorConfig(OMElement oauthConfigElem) {
    OMElement authContextTokGenConfigElem =
            oauthConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.AUTHORIZATION_CONTEXT_TOKEN_GENERATION));
    if (authContextTokGenConfigElem != null) {
        OMElement enableJWTGenerationConfigElem =
                authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.ENABLED));
        if (enableJWTGenerationConfigElem != null) {
            String enableJWTGeneration = enableJWTGenerationConfigElem.getText().trim();
            if (enableJWTGeneration != null && JavaUtils.isTrueExplicitly(enableJWTGeneration)) {
                isAuthContextTokGenEnabled = true;
                if (authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.TOKEN_GENERATOR_IMPL_CLASS)) != null) {
                    tokenGeneratorImplClass =
                            authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.TOKEN_GENERATOR_IMPL_CLASS))
                                    .getText().trim();
                }
                if (authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.CLAIMS_RETRIEVER_IMPL_CLASS)) != null) {
                    claimsRetrieverImplClass =
                            authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.CLAIMS_RETRIEVER_IMPL_CLASS))
                                    .getText().trim();
                }
                if (authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.CONSUMER_DIALECT_URI)) != null) {
                    consumerDialectURI =
                            authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.CONSUMER_DIALECT_URI))
                                    .getText().trim();
                }
                if (authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.SIGNATURE_ALGORITHM)) != null) {
                    signatureAlgorithm =
                            authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.SIGNATURE_ALGORITHM))
                                    .getText().trim();
                }
                if (authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.SECURITY_CONTEXT_TTL)) != null) {
                    authContextTTL =
                            authContextTokGenConfigElem.getFirstChildWithName(getQNameWithIdentityNS(ConfigElements.SECURITY_CONTEXT_TTL))
                                    .getText().trim();
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        if (isAuthContextTokGenEnabled) {
            log.debug("JWT Generation is enabled");
        } else {
            log.debug("JWT Generation is disabled");
        }
    }
}