text:
package org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.BlockConditionsDTO;
import org.wso2.carbon.apimgt.api.model.policy.APIPolicy;
import org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy;
import org.wso2.carbon.apimgt.api.model.policy.Policy;
import org.wso2.carbon.apimgt.api.model.policy.PolicyConstants;
import org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy;
import org.wso2.carbon.apimgt.hybrid.gateway.common.OnPremiseGatewayInitListener;
import org.wso2.carbon.apimgt.hybrid.gateway.common.config.ConfigManager;
import org.wso2.carbon.apimgt.hybrid.gateway.common.dto.AccessTokenDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.common.dto.OAuthApplicationInfoDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.common.exception.OnPremiseGatewayException;
import org.wso2.carbon.apimgt.hybrid.gateway.common.util.HttpRequestUtil;
import org.wso2.carbon.apimgt.hybrid.gateway.common.util.MicroGatewayCommonUtil;
import org.wso2.carbon.apimgt.hybrid.gateway.common.util.OnPremiseGatewayConstants;
import org.wso2.carbon.apimgt.hybrid.gateway.common.util.TokenUtil;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.AdvancedThrottlePolicyDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.AdvancedThrottlePolicyInfoDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.AdvancedThrottlePolicyListDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.ApplicationThrottlePolicyDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.ApplicationThrottlePolicyListDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.BlockingConditionDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.BlockingConditionListDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.SubscriptionThrottlePolicyDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.dto.SubscriptionThrottlePolicyListDTO;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.exception.ThrottlingSynchronizerException;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.util.ThrottlingConstants;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.util.mapping.throttling.AdvancedThrottlePolicyMappingUtil;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.util.mapping.throttling.ApplicationThrottlePolicyMappingUtil;
import org.wso2.carbon.apimgt.hybrid.gateway.throttling.synchronizer.util.mapping.throttling.SubscriptionThrottlePolicyMappingUtil;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * This class synchronizes throttling policies
 */
public class ThrottlingSynchronizer implements OnPremiseGatewayInitListener {

    private static final Log log = LogFactory.getLog(ThrottlingSynchronizer.class);
    private String applicationPolicyUrl = ThrottlingConstants.EMPTY_STRING;
    private String subscriptionPolicyUrl = ThrottlingConstants.EMPTY_STRING;
    private String advancedPolicyUrl = ThrottlingConstants.EMPTY_STRING;
    private String blockingPolicyUrl = ThrottlingConstants.EMPTY_STRING;

    @Override
    public void completedInitialization() {
        initSynchronization();
    }

    /**
     * Setup user environment to initialize Synchronization
     */
    public void initSynchronization() {
        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
                getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String username = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME);
        char[] password = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray();
        try {
            boolean isMultiTenantEnabled = ConfigManager.getConfigurationDTO().isMulti_tenant_enabled();
            if (isMultiTenantEnabled) {
                Map<String, String> multiTenantUserMap = MicroGatewayCommonUtil.getMultiTenantUserMap();
                Set<String> tenantUsernameSet = multiTenantUserMap.keySet();
                for (String tenantusername : tenantUsernameSet) {
                    synchronize(tenantusername, multiTenantUserMap.get(tenantusername).toCharArray());
                }
            } else {
                synchronize(username, password);
            }
        } catch (OnPremiseGatewayException e) {
            log.error("Error occurred while synchronizing Throttling policies", e);
        }
    }

    /**
     * Start throttle synchronizations for tenant user
     * @param username Tenant username
     * @param password Password
     */
    public void synchronize(String username, char[] password) {
        log.info("Started synchronizing policies.");
        AccessTokenDTO accessTokenDTO;
        try {
            loadTenant(username);
            username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
            //Initialize Rest API urls
            String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin();
            String apiVersion = ConfigManager.getConfigurationDTO().getApi_update_rest_api_version();
            if (apiVersion == null) {
                apiVersion = ThrottlingConstants.API_DEFAULT_VERSION;
                if (log.isDebugEnabled()) {
                    log.debug("Using default API version: " + apiVersion);
                }
            } else if (ThrottlingConstants.CLOUD_API.equals(apiVersion)) {
                apiVersion = ThrottlingConstants.EMPTY_STRING;
                if (log.isDebugEnabled()) {
                    log.debug("Cloud API doesn't have an version. Therefore, removing the version: " + apiVersion);
                }
            }
            if (apiAdminUrl == null) {
                apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL;
                if (log.isDebugEnabled()) {
                    log.debug("Using default API Admin URL." + apiAdminUrl);
                }
            }
            //Remove '//' which is created in the cloud case.
            applicationPolicyUrl = apiAdminUrl + ThrottlingConstants.APPLICATION_POLICIES_SUFFIX
                    .replace(ThrottlingConstants.API_VERSION_PARAM, apiVersion)
                    .replace("//", ThrottlingConstants.URL_PATH_SEPARATOR);

            subscriptionPolicyUrl = apiAdminUrl + ThrottlingConstants.SUBSCRIPTION_POLICIES_SUFFIX
                    .replace(ThrottlingConstants.API_VERSION_PARAM, apiVersion)
                    .replace("//", ThrottlingConstants.URL_PATH_SEPARATOR);

            advancedPolicyUrl = apiAdminUrl + ThrottlingConstants.ADVANCED_POLICIES_SUFFIX
                    .replace(ThrottlingConstants.API_VERSION_PARAM, apiVersion)
                    .replace("//", ThrottlingConstants.URL_PATH_SEPARATOR);

            blockingPolicyUrl = apiAdminUrl + ThrottlingConstants.BLOCKING_POLICIES_SUFFIX
                    .replace(ThrottlingConstants.API_VERSION_PARAM, apiVersion)
                    .replace("//", ThrottlingConstants.URL_PATH_SEPARATOR);

            //first we need to get an access token to invoke the Admin Rest API
            try {
                OAuthApplicationInfoDTO responseDto = TokenUtil.registerClient();
                String combinedScopes = ThrottlingConstants.TOKEN_TIER_VIEW_SCOPE + " "
                        + ThrottlingConstants.BLOCKING_CONDITION_VIEW_SCOPE;
                accessTokenDTO = TokenUtil.generateAccessToken(responseDto.getClientId(),
                        responseDto.getClientSecret().toCharArray(), combinedScopes, username, password);
            } catch (OnPremiseGatewayException e) {
                log.error("Error occurred while creating policies. Unable to generate Access Token.", e);
                return;
            }

            createSubscriptionPolicies(username, accessTokenDTO);
            createApplicationPolicies(username, accessTokenDTO);
            createAdvancedPolicies(username, accessTokenDTO);
        } catch (ThrottlingSynchronizerException | OnPremiseGatewayException e) {
            log.error("Error occurred while creating policies.", e);
            return;
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }

        //Blocking conditions cannot be modified in tenant flow, hence using super tenant flow
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
            createBlackListPolicies(username, accessTokenDTO);
        } catch (ThrottlingSynchronizerException e) {
            log.error("Error occurred while creating Blocking Conditions.", e);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }

        log.info("Synchronizing policies completed.");
    }

    private void createSubscriptionPolicies(String username, AccessTokenDTO accessTokenDTO)
            throws ThrottlingSynchronizerException {
        if (log.isDebugEnabled()) {
            log.debug("Creating Subscription policies.");
        }

        try {
            //Remove any default subscription policies
            APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(username);
            Policy[] policies = apiProvider.getPolicies(username, PolicyConstants.POLICY_LEVEL_SUB);
            if (log.isDebugEnabled()) {
                log.debug("Deleting existing Subscription policies.");
            }
            for (Policy policy : policies) {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting : " + policy.getPolicyName());
                }
                //Don't change the Unlimited policy
                if (!APIConstants.UNLIMITED_TIER.equals(policy.getPolicyName())) {
                    apiProvider.deletePolicy(username, PolicyConstants.POLICY_LEVEL_SUB, policy.getPolicyName());
                }
            }

            //Get the list of subscription policies calling the Admin Rest API
            SubscriptionThrottlePolicyListDTO policyListDTO = getSubscriptionPolicies(accessTokenDTO);

            //Create the subscription policies
            for (SubscriptionThrottlePolicyDTO policyDTO : policyListDTO.getList()) {
                //Don't change the Unlimited policy
                if (!APIConstants.UNLIMITED_TIER.equals(policyDTO.getPolicyName())) {
                    SubscriptionPolicy subscriptionPolicy = SubscriptionThrottlePolicyMappingUtil
                            .fromSubscriptionThrottlePolicyDTOToModel(policyDTO);
                    apiProvider.addPolicy(subscriptionPolicy);
                }
            }
        } catch (APIManagementException e) {
            throw new ThrottlingSynchronizerException("Error occurred while adding Subscription policies.", e);
        } catch (OnPremiseGatewayException | IOException e) {
            throw new ThrottlingSynchronizerException("Error occurred while adding Subscription policies." +
                    " Unable to get the Subscription policies from REST API", e);
        }
    }

    private SubscriptionThrottlePolicyListDTO getSubscriptionPolicies(AccessTokenDTO accessTokenDTO)
            throws OnPremiseGatewayException, IOException {
        if (log.isDebugEnabled()) {
            log.debug("Getting Subscription Policies using Admin REST API.");
        }
        String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin();
        if (apiAdminUrl == null) {
            apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL;
            if (log.isDebugEnabled()) {
                log.debug("Using default API Admin URL." + apiAdminUrl);
            }
        }
        URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl);
        HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol());

        HttpGet httpGet = new HttpGet(subscriptionPolicyUrl);
        String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken();
        httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue);

        String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet,
                OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT);
        if (log.isDebugEnabled()) {
            log.debug("Received response from GET Subscription Policies : " + response);
        }

        InputStream is = new ByteArrayInputStream(response.getBytes(
                Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET)));
        ObjectMapper mapper = new ObjectMapper();

        return mapper.readValue(is, SubscriptionThrottlePolicyListDTO.class);

    }

    private void createApplicationPolicies(String username, AccessTokenDTO accessTokenDTO)
            throws ThrottlingSynchronizerException {
        if (log.isDebugEnabled()) {
            log.debug("Creating Application policies.");
        }

        try {
            //Remove any default application policies
            APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(username);
            Policy[] policies = apiProvider.getPolicies(username, PolicyConstants.POLICY_LEVEL_APP);
            if (log.isDebugEnabled()) {
                log.debug("Deleting existing Application policies.");
            }
            for (Policy policy : policies) {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting : " + policy.getPolicyName());
                }
                //Don't change the Unlimited policy
                if (!APIConstants.UNLIMITED_TIER.equals(policy.getPolicyName())) {
                    apiProvider.deletePolicy(username, PolicyConstants.POLICY_LEVEL_APP, policy.getPolicyName());
                }
            }

            //Get the list of subscription policies calling the Admin Rest API
            ApplicationThrottlePolicyListDTO policyListDTO = getApplicationPolicies(accessTokenDTO);

            //Create the subscription policies
            for (ApplicationThrottlePolicyDTO policyDTO : policyListDTO.getList()) {
                //Don't change the Unlimited policy
                if (!APIConstants.UNLIMITED_TIER.equals(policyDTO.getPolicyName())) {
                    ApplicationPolicy applicationPolicy = ApplicationThrottlePolicyMappingUtil
                            .fromApplicationThrottlePolicyDTOToModel(policyDTO);
                    apiProvider.addPolicy(applicationPolicy);
                }
            }
        } catch (APIManagementException e) {
            throw new ThrottlingSynchronizerException("Error occurred while adding Application policies.", e);
        } catch (OnPremiseGatewayException | IOException e) {
            throw new ThrottlingSynchronizerException("Error occurred while adding Application policies." +
                    " Unable to get the Application policies from REST API", e);
        }
    }

    private ApplicationThrottlePolicyListDTO getApplicationPolicies(AccessTokenDTO accessTokenDTO)
            throws OnPremiseGatewayException, IOException {
        if (log.isDebugEnabled()) {
            log.debug("Getting Subscription Policies using Admin REST API.");
        }
        String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin();
        if (apiAdminUrl == null) {
            apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL;
            if (log.isDebugEnabled()) {
                log.debug("Using default API Admin URL." + apiAdminUrl);
            }
        }
        URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl);
        HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol());

        HttpGet httpGet = new HttpGet(applicationPolicyUrl);
        String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken();
        httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue);

        String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet,
                OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT);
        if (log.isDebugEnabled()) {
            log.debug("Received response from GET Application Policies : " + response);
        }

        InputStream is = new ByteArrayInputStream(response.getBytes(
                Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET)));
        ObjectMapper mapper = new ObjectMapper();

        return mapper.readValue(is, ApplicationThrottlePolicyListDTO.class);
    }

    private void createAdvancedPolicies(String username, AccessTokenDTO accessTokenDTO)
            throws ThrottlingSynchronizerException {
        if (log.isDebugEnabled()) {
            log.debug("Creating Advanced policies.");
        }

        try {
            //Remove any advanced policies
            APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(username);
            Policy[] policies = apiProvider.getPolicies(username, PolicyConstants.POLICY_LEVEL_API);
            if (log.isDebugEnabled()) {
                log.debug("Deleting existing Advanced policies.");
            }
            for (Policy policy : policies) {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting : " + policy.getPolicyName());
                }
                //Don't change the Unlimited policy
                if (!APIConstants.UNLIMITED_TIER.equals(policy.getPolicyName())) {
                    apiProvider.deletePolicy(username, PolicyConstants.POLICY_LEVEL_API, policy.getPolicyName());
                }
            }

            //Get the list of advance policies calling the Admin Rest API
            AdvancedThrottlePolicyListDTO policyListDTO = getAdvancedPolicies(accessTokenDTO);
            //Get detailed advanced policy list
            List<AdvancedThrottlePolicyDTO> policyDTOList = getAdvancedPolicyList(accessTokenDTO, policyListDTO);
            //Create the advanced policies
            for (AdvancedThrottlePolicyDTO policyDTO : policyDTOList) {
                //Don't change the Unlimited policy
                if (!APIConstants.UNLIMITED_TIER.equals(policyDTO.getPolicyName())) {
                    APIPolicy apiPolicy = AdvancedThrottlePolicyMappingUtil.fromAdvancedPolicyDTOToPolicy(policyDTO);
                    apiProvider.addPolicy(apiPolicy);
                }
            }
        } catch (APIManagementException e) {
            throw new ThrottlingSynchronizerException("Error occurred while adding Advanced policies.", e);
        } catch (OnPremiseGatewayException | IOException e) {
            throw new ThrottlingSynchronizerException("Error occurred while adding Advanced policies." +
                    " Unable to get the Advanced policies from REST API", e);
        }
    }

    private AdvancedThrottlePolicyListDTO getAdvancedPolicies(AccessTokenDTO accessTokenDTO)
            throws OnPremiseGatewayException, IOException {
        if (log.isDebugEnabled()) {
            log.debug("Getting Advanced Policies using Admin REST API.");
        }

        String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin();
        if (apiAdminUrl == null) {
            apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL;
            if (log.isDebugEnabled()) {
                log.debug("Using default API Admin URL." + apiAdminUrl);
            }
        }
        URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl);
        HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol());
        HttpGet httpGet = new HttpGet(advancedPolicyUrl);
        String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken();
        httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue);

        String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet,
                OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT);
        if (log.isDebugEnabled()) {
            log.debug("Received response from GET Advanced Policies : " + response);
        }

        InputStream is = new ByteArrayInputStream(response.getBytes(
                Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET)));
        ObjectMapper mapper = new ObjectMapper();

        return mapper.readValue(is, AdvancedThrottlePolicyListDTO.class);
    }

    private List<AdvancedThrottlePolicyDTO> getAdvancedPolicyList(AccessTokenDTO accessTokenDTO,
                                                                  AdvancedThrottlePolicyListDTO policyListDTO)
            throws OnPremiseGatewayException {
        List<AdvancedThrottlePolicyDTO> policyDTOList = new ArrayList<>();
        String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin();
        if (apiAdminUrl == null) {
            apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL;
            if (log.isDebugEnabled()) {
                log.debug("Using default API Admin URL." + apiAdminUrl);
            }
        }
        URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl);
        HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol());

        for (AdvancedThrottlePolicyInfoDTO infoDTO : policyListDTO.getList()) {
            HttpGet httpGet = new HttpGet(advancedPolicyUrl + ThrottlingConstants.URL_PATH_SEPARATOR + infoDTO.getPolicyId());
            String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken();
            httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue);

            String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet,
                    OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT);
            if (log.isDebugEnabled()) {
                log.debug("Received response from GET Advanced Policy : " + response);
            }
            InputStream is = new ByteArrayInputStream(response.getBytes(
                    Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET)));
            ObjectMapper mapper = new ObjectMapper();
            try {
                policyDTOList.add(mapper.readValue(is, AdvancedThrottlePolicyDTO.class));
            } catch (IOException e) {
                throw new OnPremiseGatewayException("Error occurred while getting Advanced Policies.", e);
            }
        }
        return policyDTOList;
    }

    private void createBlackListPolicies(String username, AccessTokenDTO accessTokenDTO)
            throws ThrottlingSynchronizerException {
        if (log.isDebugEnabled()) {
            log.debug("Creating Blacklist policies.");
        }

        try {
            //Remove any blocking conditions
            if (log.isDebugEnabled()) {
                log.debug("Deleting existing Blocking conditions.");
            }
            APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(username);
            List<BlockConditionsDTO> blockingConditionDTOList = apiProvider.getBlockConditions();
            for (BlockConditionsDTO dto : blockingConditionDTOList) {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting : " + dto.getConditionType() + ":" + dto.getConditionValue());
                }
                apiProvider.deleteBlockCondition(dto.getConditionId());
            }

            //Get blocking conditions
            BlockingConditionListDTO blockingConditionListDTO = getBlockingConditions(accessTokenDTO);
            //Add blocking conditions
            for (BlockingConditionDTO dto : blockingConditionListDTO.getList()) {
                apiProvider.addBlockCondition(dto.getConditionType(), dto.getConditionValue());
            }
        } catch (APIManagementException e) {
            throw new ThrottlingSynchronizerException("Error occurred while adding Blocking Conditions.", e);
        } catch (OnPremiseGatewayException | IOException e) {
            throw new ThrottlingSynchronizerException("Error occurred while adding Blocking Conditions." +
                    " Unable to get the Blocking Conditions from REST API", e);
        }
    }

    private BlockingConditionListDTO getBlockingConditions(AccessTokenDTO accessTokenDTO)
            throws OnPremiseGatewayException, IOException {

        if (log.isDebugEnabled()) {
            log.debug("Getting Blocking conditions using Admin REST API.");
        }
        String apiAdminUrl = ConfigManager.getConfigurationDTO().getUrl_admin();
        if (apiAdminUrl == null) {
            apiAdminUrl = ThrottlingConstants.DEFAULT_API_ADMIN_URL;
            if (log.isDebugEnabled()) {
                log.debug("Using default API Admin URL." + apiAdminUrl);
            }
        }
        URL apiAdminUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(apiAdminUrl);
        HttpClient httpClient = APIUtil.getHttpClient(apiAdminUrlValue.getPort(), apiAdminUrlValue.getProtocol());
        HttpGet httpGet = new HttpGet(blockingPolicyUrl);
        String authHeaderValue = OnPremiseGatewayConstants.AUTHORIZATION_BEARER + accessTokenDTO.getAccessToken();
        httpGet.addHeader(OnPremiseGatewayConstants.AUTHORIZATION_HEADER, authHeaderValue);

        String response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httpGet,
                OnPremiseGatewayConstants.DEFAULT_RETRY_COUNT);
        if (log.isDebugEnabled()) {
            log.debug("Received response from GET Blocking Conditions : " + response);
        }

        InputStream is = new ByteArrayInputStream(response.getBytes(
                Charset.forName(OnPremiseGatewayConstants.DEFAULT_CHARSET)));
        ObjectMapper mapper = new ObjectMapper();

        return mapper.readValue(is, BlockingConditionListDTO.class);

    }

    private void loadTenant(String username) {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            ConfigurationContext context = ServiceReferenceHolder.getInstance()
                    .getConfigContextService().getServerConfigContext();
            TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, context);
            if (log.isDebugEnabled()) {
                log.debug("Tenant was loaded into Carbon Context. Tenant : " + tenantDomain
                        + ", Username : " + username);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Skipping loading super tenant space since execution is currently in super tenant flow.");
            }
        }
    }
}


text:
{% extends 'steps/step.html' %}
{% block title %}
Programmschritt bearbeiten
{% endblock %}

{% block footer %}
{{ super() }}
<button id="deleteStep" type="button" class="btn btn-danger" style="float: left;">Entfernen</button>
{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
//
// include necessary system headers
//
#include <iostream>
#include <string>

//
// ViennaCL includes
//
#include "viennacl/ocl/backend.hpp"
#include "viennacl/vector.hpp"
#include "viennacl/matrix.hpp"
#include "viennacl/linalg/matrix_operations.hpp"
#include "viennacl/linalg/norm_2.hpp"
#include "viennacl/linalg/prod.hpp"

// Some helper functions for this tutorial:
#include "Random.hpp"

/*
*
*   Tutorial:  Use ViennaCL within user-defined OpenCL contexts
*
*/

//
// A custom compute kernel which computes an elementwise product of two vectors
// Input: v1 ... vector
//        v2 ... vector
// Output: result ... vector
//
// Algorithm: set result[i] <- v1[i] * v2[i]
//            (in MATLAB notation this is something like 'result = v1 .* v2');
//

const char * my_compute_program =
"__kernel void elementwise_prod(\n"
"          __global const float * vec1,\n"
"          __global const float * vec2, \n"
"          __global float * result,\n"
"          unsigned int size) \n"
"{ \n"
"  for (unsigned int i = get_global_id(0); i < size; i += get_global_size(0))\n"
"    result[i] = vec1[i] * vec2[i];\n"
"};\n";

int main()
{
  typedef float       ScalarType;

  /////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////// Part 1: Set up a custom context and perform a sample operation. ////////////////
  ////////////////////////         This is rather lengthy due to the OpenCL framework.     ////////////////
  ////////////////////////         The following does essentially the same as the          ////////////////
  ////////////////////////         'custom_kernels'-tutorial!                               ////////////////
  /////////////////////////////////////////////////////////////////////////////////////////////////////////

  //manually set up a custom OpenCL context:
  std::vector<cl_device_id> device_id_array;

  //get all available devices
  viennacl::ocl::platform pf;
  std::cout << "Platform info: " << pf.info() << std::endl;
  std::vector<viennacl::ocl::device> devices = pf.devices(CL_DEVICE_TYPE_DEFAULT);
  std::cout << devices[0].name() << std::endl;
  std::cout << "Number of devices for custom context: " << devices.size() << std::endl;

  //set up context using all found devices:
  for (size_t i=0; i<devices.size(); ++i)
  {
      device_id_array.push_back(devices[i].id());
  }

  std::cout << "Creating context..." << std::endl;
  cl_int err;
  cl_context my_context = clCreateContext(0, device_id_array.size(), &(device_id_array[0]), NULL, NULL, &err);
  VIENNACL_ERR_CHECK(err);

  //create two Vectors:
  unsigned int vector_size = 10;
  std::vector<ScalarType> vec1(vector_size);
  std::vector<ScalarType> vec2(vector_size);
  std::vector<ScalarType> result(vector_size);

  //
  // fill the operands vec1 and vec2:
  //
  for (unsigned int i=0; i<vector_size; ++i)
  {
    vec1[i] = static_cast<ScalarType>(i);
    vec2[i] = static_cast<ScalarType>(vector_size-i);
  }

  //
  // create memory in OpenCL context:
  //
  cl_mem mem_vec1 = clCreateBuffer(my_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, vector_size * sizeof(ScalarType), &(vec1[0]), &err);
  VIENNACL_ERR_CHECK(err);
  cl_mem mem_vec2 = clCreateBuffer(my_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, vector_size * sizeof(ScalarType), &(vec2[0]), &err);
  VIENNACL_ERR_CHECK(err);
  cl_mem mem_result = clCreateBuffer(my_context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, vector_size * sizeof(ScalarType), &(result[0]), &err);
  VIENNACL_ERR_CHECK(err);

  //
  // create a command queue for each device:
  //

  std::vector<cl_command_queue> queues(devices.size());
  for (size_t i=0; i<devices.size(); ++i)
  {
    queues[i] = clCreateCommandQueue(my_context, devices[i].id(), 0, &err);
    VIENNACL_ERR_CHECK(err);
  }

  //
  // create and build a program in the context:
  //
  size_t source_len = std::string(my_compute_program).length();
  cl_program my_prog = clCreateProgramWithSource(my_context, 1, &my_compute_program, &source_len, &err);
  err = clBuildProgram(my_prog, 0, NULL, NULL, NULL, NULL);

/*            char buffer[1024];
            cl_build_status status;
            clGetProgramBuildInfo(my_prog, devices[1].id(), CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &status, NULL);
            clGetProgramBuildInfo(my_prog, devices[1].id(), CL_PROGRAM_BUILD_LOG, sizeof(char)*1024, &buffer, NULL);
            std::cout << "Build Scalar: Err = " << err << " Status = " << status << std::endl;
            std::cout << "Log: " << buffer << std::endl;*/

  VIENNACL_ERR_CHECK(err);

  //
  // create a kernel from the program:
  //
  const char * kernel_name = "elementwise_prod";
  cl_kernel my_kernel = clCreateKernel(my_prog, kernel_name, &err);
  VIENNACL_ERR_CHECK(err);

  //
  // Execute elementwise_prod kernel on first queue: result = vec1 .* vec2;
  //
  err = clSetKernelArg(my_kernel, 0, sizeof(cl_mem), (void*)&mem_vec1);
  VIENNACL_ERR_CHECK(err);
  err = clSetKernelArg(my_kernel, 1, sizeof(cl_mem), (void*)&mem_vec2);
  VIENNACL_ERR_CHECK(err);
  err = clSetKernelArg(my_kernel, 2, sizeof(cl_mem), (void*)&mem_result);
  VIENNACL_ERR_CHECK(err);
  err = clSetKernelArg(my_kernel, 3, sizeof(unsigned int), (void*)&vector_size);
  VIENNACL_ERR_CHECK(err);
  size_t global_size = vector_size;
  size_t local_size = vector_size;
  err = clEnqueueNDRangeKernel(queues[0], my_kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL);
  VIENNACL_ERR_CHECK(err);

  //
  // Read and output result:
  //
  err = clEnqueueReadBuffer(queues[0], mem_vec1, CL_TRUE, 0, sizeof(ScalarType)*vector_size, &(vec1[0]), 0, NULL, NULL);
  VIENNACL_ERR_CHECK(err);
  err = clEnqueueReadBuffer(queues[0], mem_result, CL_TRUE, 0, sizeof(ScalarType)*vector_size, &(result[0]), 0, NULL, NULL);
  VIENNACL_ERR_CHECK(err);

  std::cout << "vec1  : ";
  for (size_t i=0; i<vec1.size(); ++i)
    std::cout << vec1[i] << " ";
  std::cout << std::endl;

  std::cout << "vec2  : ";
  for (size_t i=0; i<vec2.size(); ++i)
    std::cout << vec2[i] << " ";
  std::cout << std::endl;

  std::cout << "result: ";
  for (size_t i=0; i<result.size(); ++i)
    std::cout << result[i] << " ";
  std::cout << std::endl;

  ////////////////////////////////////////////////////////////////////////////////////////////////////////
  /////////////////////// Part 2: Let ViennaCL use the already created context: //////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////////////////////

  //Tell ViennaCL to use the previously created context.
  //This context is assigned an id '0' when using viennacl::ocl::switch_context().
  viennacl::ocl::setup_context(0, my_context, device_id_array, queues);
  viennacl::ocl::switch_context(0); //activate the new context (only mandatory with context-id not equal to zero)

  //
  // Proof that ViennaCL really uses the new context:
  //
  std::cout << "Existing context: " << my_context << std::endl;
  std::cout << "ViennaCL uses context: " << viennacl::ocl::current_context().handle().get() << std::endl;

  //
  // Wrap existing OpenCL objects into ViennaCL:
  //
  viennacl::vector<ScalarType> vcl_vec1(mem_vec1, vector_size);
  viennacl::vector<ScalarType> vcl_vec2(mem_vec2, vector_size);
  viennacl::vector<ScalarType> vcl_result(mem_result, vector_size);
  viennacl::scalar<ScalarType> vcl_s = 2.0;

  std::cout << "Standard vector operations within ViennaCL:" << std::endl;
  vcl_result = vcl_s * vcl_vec1 + vcl_vec2;

  std::cout << "vec1  : ";
  std::cout << vcl_vec1 << std::endl;

  std::cout << "vec2  : ";
  std::cout << vcl_vec2 << std::endl;

  std::cout << "result: ";
  std::cout << vcl_result << std::endl;

  //
  // We can also reuse the existing elementwise_prod kernel.
  // Therefore, we first have to make the existing program known to ViennaCL
  // For more details on the three lines, see tutorial 'custom-kernels'
  //
  std::cout << "Using existing kernel within the OpenCL backend of ViennaCL:" << std::endl;
  viennacl::ocl::program & my_vcl_prog = viennacl::ocl::current_context().add_program(my_prog, "my_compute_program");
  viennacl::ocl::kernel & my_vcl_kernel = my_vcl_prog.add_kernel("elementwise_prod");
  viennacl::ocl::enqueue(my_vcl_kernel(vcl_vec1, vcl_vec2, vcl_result, static_cast<cl_uint>(vcl_vec1.size())));  //Note that size_t might differ between host and device. Thus, a cast to cl_uint is necessary here.

  std::cout << "vec1  : ";
  std::cout << vcl_vec1 << std::endl;

  std::cout << "vec2  : ";
  std::cout << vcl_vec2 << std::endl;

  std::cout << "result: ";
  std::cout << vcl_result << std::endl;

  //
  // Since a linear piece of memory can be interpreted in several ways,
  // we will now create a 3x3 row-major matrix out of the linear memory in mem_vec1/
  // The first three entries in vcl_vec2 and vcl_result are used to carry out matrix-vector products:
  //
  viennacl::matrix<ScalarType> vcl_matrix(mem_vec1, 3, 3);

  vcl_vec2.resize(3);   //note that the resize operation leads to new memory, thus vcl_vec2 is now at a different memory location (values are copied)
  vcl_result.resize(3); //note that the resize operation leads to new memory, thus vcl_vec2 is now at a different memory location (values are copied)
  vcl_result = viennacl::linalg::prod(vcl_matrix, vcl_vec2);

  std::cout << "result of matrix-vector product: ";
  std::cout << vcl_result << std::endl;

  //
  //  That's it.
  //
  std::cout << "!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!" << std::endl;

  return 0;
}


text:
askisi4: This folder contains the entire program in one single file - webserverThreads.c

askisi4xwrismena: This folder contains the program divided into multiple files.

testFiles: This folder contains a client program for testing.


text:
using System;

namespace ColorThiefDotNet
{
    public class QuantizedColor
    {
        public QuantizedColor(Color color, int population)
        {
            Color = color;
            Population = population;
            IsDark = CalculateYiqLuma(color) < 128;
        }

        public Color Color { get; private set; }
        public int Population { get; private set; }
        public bool IsDark { get; private set; }

        public int CalculateYiqLuma(Color color)
        {
            return Convert.ToInt32(Math.Round((299 * color.R + 587 * color.G + 114 * color.B) / 1000f));
        }
    }
}


text:
package com.github.joshholl.intellij.csharp.lang.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface CSharpGotoStatement extends PsiElement {

  @Nullable
  CSharpConstantExpression getConstantExpression();

}


text:
<?php
/**
 *	Administrator settings
 *
 *	----------------------------------------------------------
 *	This file has been auto-generated. Please don't modify it!
 *	----------------------------------------------------------
 *
 *	Last change: 2013-08-27 15:02:42
 */

$admin = array();

$admin["administrators"] = array("http://matt-open.myopenid.com/", "https://www.google.com/accounts/o8/id?id=AItOawkw3OoNkrQTS1FHT-v4oHlwyOuhCu2IfJ0", "https://me.yahoo.com/a/yiWQZ5Rt0eAc65fA795yChHK4Zv0ig--", "https://www.google.com/accounts/o8/id?id=AItOawlgEmhrIotKE_jDGMIvyn6p_4jtVlVvU-I");

$admin["lmdb_sources"] = array(
array("name" => "Salzburg Research CMF Development", "username" => "admin", "password" => "pass123",	"url" => "http://connectme.salzburgresearch.at/devel/", "selected" => 1), array("name" => "Salzburg Research CMF Live", "username" => "admin", "password" => "pass123",	"url" => "http://connectme.salzburgresearch.at/production/", "selected" => 0));


text:
from __future__ import annotations

from collections import deque
import decimal
import gc
from itertools import chain
import random
import sys
from sys import getsizeof
import types

from . import config
from . import mock
from .. import inspect
from ..engine import Connection
from ..schema import Column
from ..schema import DropConstraint
from ..schema import DropTable
from ..schema import ForeignKeyConstraint
from ..schema import MetaData
from ..schema import Table
from ..sql import schema
from ..sql.sqltypes import Integer
from ..util import decorator
from ..util import defaultdict
from ..util import has_refcount_gc
from ..util import inspect_getfullargspec

if not has_refcount_gc:

    def non_refcount_gc_collect(*args):
        gc.collect()
        gc.collect()

    gc_collect = lazy_gc = non_refcount_gc_collect
else:
    # assume CPython - straight gc.collect, lazy_gc() is a pass
    gc_collect = gc.collect

    def lazy_gc():
        pass

def picklers():
    picklers = set()
    import pickle

    picklers.add(pickle)

    # yes, this thing needs this much testing
    for pickle_ in picklers:
        for protocol in range(-2, pickle.HIGHEST_PROTOCOL):
            yield pickle_.loads, lambda d: pickle_.dumps(d, protocol)

def random_choices(population, k=1):
    return random.choices(population, k=k)

def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)).to_integral(
        decimal.ROUND_FLOOR
    ) / pow(10, prec)

class RandomSet(set):
    def __iter__(self):
        l = list(set.__iter__(self))
        random.shuffle(l)
        return iter(l)

    def pop(self):
        index = random.randint(0, len(self) - 1)
        item = list(set.__iter__(self))[index]
        self.remove(item)
        return item

    def union(self, other):
        return RandomSet(set.union(self, other))

    def difference(self, other):
        return RandomSet(set.difference(self, other))

    def intersection(self, other):
        return RandomSet(set.intersection(self, other))

    def copy(self):
        return RandomSet(self)

def conforms_partial_ordering(tuples, sorted_elements):
    """True if the given sorting conforms to the given partial ordering."""

    deps = defaultdict(set)
    for parent, child in tuples:
        deps[parent].add(child)
    for i, node in enumerate(sorted_elements):
        for n in sorted_elements[i:]:
            if node in deps[n]:
                return False
    else:
        return True

def all_partial_orderings(tuples, elements):
    edges = defaultdict(set)
    for parent, child in tuples:
        edges[child].add(parent)

    def _all_orderings(elements):

        if len(elements) == 1:
            yield list(elements)
        else:
            for elem in elements:
                subset = set(elements).difference([elem])
                if not subset.intersection(edges[elem]):
                    for sub_ordering in _all_orderings(subset):
                        yield [elem] + sub_ordering

    return iter(_all_orderings(elements))

def function_named(fn, name):
    """Return a function with a given __name__.

    Will assign to __name__ and return the original function if possible on
    the Python implementation, otherwise a new function will be constructed.

    This function should be phased out as much as possible
    in favor of @decorator.   Tests that "generate" many named tests
    should be modernized.

    """
    try:
        fn.__name__ = name
    except TypeError:
        fn = types.FunctionType(
            fn.__code__, fn.__globals__, name, fn.__defaults__, fn.__closure__
        )
    return fn

def run_as_contextmanager(ctx, fn, *arg, **kw):
    """Run the given function under the given contextmanager,
    simulating the behavior of 'with' to support older
    Python versions.

    This is not necessary anymore as we have placed 2.6
    as minimum Python version, however some tests are still using
    this structure.

    """

    obj = ctx.__enter__()
    try:
        result = fn(obj, *arg, **kw)
        ctx.__exit__(None, None, None)
        return result
    except:
        exc_info = sys.exc_info()
        raise_ = ctx.__exit__(*exc_info)
        if not raise_:
            raise
        else:
            return raise_

def rowset(results):
    """Converts the results of sql execution into a plain set of column tuples.

    Useful for asserting the results of an unordered query.
    """

    return {tuple(row) for row in results}

def fail(msg):
    assert False, msg

@decorator
def provide_metadata(fn, *args, **kw):
    """Provide bound MetaData for a single test, dropping afterwards.

    Legacy; use the "metadata" pytest fixture.

    """

    from . import fixtures

    metadata = schema.MetaData()
    self = args[0]
    prev_meta = getattr(self, "metadata", None)
    self.metadata = metadata
    try:
        return fn(*args, **kw)
    finally:
        # close out some things that get in the way of dropping tables.
        # when using the "metadata" fixture, there is a set ordering
        # of things that makes sure things are cleaned up in order, however
        # the simple "decorator" nature of this legacy function means
        # we have to hardcode some of that cleanup ahead of time.

        # close ORM sessions
        fixtures._close_all_sessions()

        # integrate with the "connection" fixture as there are many
        # tests where it is used along with provide_metadata
        if fixtures._connection_fixture_connection:
            # TODO: this warning can be used to find all the places
            # this is used with connection fixture
            # warn("mixing legacy provide metadata with connection fixture")
            drop_all_tables_from_metadata(
                metadata, fixtures._connection_fixture_connection
            )
            # as the provide_metadata fixture is often used with "testing.db",
            # when we do the drop we have to commit the transaction so that
            # the DB is actually updated as the CREATE would have been
            # committed
            fixtures._connection_fixture_connection.get_transaction().commit()
        else:
            drop_all_tables_from_metadata(metadata, config.db)
        self.metadata = prev_meta

def flag_combinations(*combinations):
    """A facade around @testing.combinations() oriented towards boolean
    keyword-based arguments.

    Basically generates a nice looking identifier based on the keywords
    and also sets up the argument names.

    E.g.::

        @testing.flag_combinations(
            dict(lazy=False, passive=False),
            dict(lazy=True, passive=False),
            dict(lazy=False, passive=True),
            dict(lazy=False, passive=True, raiseload=True),
        )

    would result in::

        @testing.combinations(
            ('', False, False, False),
            ('lazy', True, False, False),
            ('lazy_passive', True, True, False),
            ('lazy_passive', True, True, True),
            id_='iaaa',
            argnames='lazy,passive,raiseload'
        )

    """

    keys = set()

    for d in combinations:
        keys.update(d)

    keys = sorted(keys)

    return config.combinations(
        *[
            ("_".join(k for k in keys if d.get(k, False)),)
            + tuple(d.get(k, False) for k in keys)
            for d in combinations
        ],
        id_="i" + ("a" * len(keys)),
        argnames=",".join(keys),
    )

def lambda_combinations(lambda_arg_sets, **kw):
    args = inspect_getfullargspec(lambda_arg_sets)

    arg_sets = lambda_arg_sets(*[mock.Mock() for arg in args[0]])

    def create_fixture(pos):
        def fixture(**kw):
            return lambda_arg_sets(**kw)[pos]

        fixture.__name__ = "fixture_%3.3d" % pos
        return fixture

    return config.combinations(
        *[(create_fixture(i),) for i in range(len(arg_sets))], **kw
    )

def resolve_lambda(__fn, **kw):
    """Given a no-arg lambda and a namespace, return a new lambda that
    has all the values filled in.

    This is used so that we can have module-level fixtures that
    refer to instance-level variables using lambdas.

    """

    pos_args = inspect_getfullargspec(__fn)[0]
    pass_pos_args = {arg: kw.pop(arg) for arg in pos_args}
    glb = dict(__fn.__globals__)
    glb.update(kw)
    new_fn = types.FunctionType(__fn.__code__, glb)
    return new_fn(**pass_pos_args)

def metadata_fixture(ddl="function"):
    """Provide MetaData for a pytest fixture."""

    def decorate(fn):
        def run_ddl(self):

            metadata = self.metadata = schema.MetaData()
            try:
                result = fn(self, metadata)
                metadata.create_all(config.db)
                # TODO:
                # somehow get a per-function dml erase fixture here
                yield result
            finally:
                metadata.drop_all(config.db)

        return config.fixture(scope=ddl)(run_ddl)

    return decorate

def force_drop_names(*names):
    """Force the given table names to be dropped after test complete,
    isolating for foreign key cycles

    """

    @decorator
    def go(fn, *args, **kw):

        try:
            return fn(*args, **kw)
        finally:
            drop_all_tables(config.db, inspect(config.db), include_names=names)

    return go

class adict(dict):
    """Dict keys available as attributes.  Shadows."""

    def __getattribute__(self, key):
        try:
            return self[key]
        except KeyError:
            return dict.__getattribute__(self, key)

    def __call__(self, *keys):
        return tuple([self[key] for key in keys])

    get_all = __call__

def drop_all_tables_from_metadata(metadata, engine_or_connection):
    from . import engines

    def go(connection):
        engines.testing_reaper.prepare_for_drop_tables(connection)

        if not connection.dialect.supports_alter:
            from . import assertions

            with assertions.expect_warnings(
                "Can't sort tables", assert_=False
            ):
                metadata.drop_all(connection)
        else:
            metadata.drop_all(connection)

    if not isinstance(engine_or_connection, Connection):
        with engine_or_connection.begin() as connection:
            go(connection)
    else:
        go(engine_or_connection)

def drop_all_tables(
    engine,
    inspector,
    schema=None,
    consider_schemas=(None,),
    include_names=None,
):

    if include_names is not None:
        include_names = set(include_names)

    if schema is not None:
        assert consider_schemas == (
            None,
        ), "consider_schemas and schema are mutually exclusive"
        consider_schemas = (schema,)

    with engine.begin() as conn:
        for table_key, fkcs in reversed(
            inspector.sort_tables_on_foreign_key_dependency(
                consider_schemas=consider_schemas
            )
        ):
            if table_key:
                if (
                    include_names is not None
                    and table_key[1] not in include_names
                ):
                    continue
                conn.execute(
                    DropTable(
                        Table(table_key[1], MetaData(), schema=table_key[0])
                    )
                )
            elif fkcs:
                if not engine.dialect.supports_alter:
                    continue
                for t_key, fkc in fkcs:
                    if (
                        include_names is not None
                        and t_key[1] not in include_names
                    ):
                        continue
                    tb = Table(
                        t_key[1],
                        MetaData(),
                        Column("x", Integer),
                        Column("y", Integer),
                        schema=t_key[0],
                    )
                    conn.execute(
                        DropConstraint(
                            ForeignKeyConstraint([tb.c.x], [tb.c.y], name=fkc)
                        )
                    )

def teardown_events(event_cls):
    @decorator
    def decorate(fn, *arg, **kw):
        try:
            return fn(*arg, **kw)
        finally:
            event_cls._clear()

    return decorate

def total_size(o):
    """Returns the approximate memory footprint an object and all of its
    contents.

    source: https://code.activestate.com/recipes/577504/

    """

    def dict_handler(d):
        return chain.from_iterable(d.items())

    all_handlers = {
        tuple: iter,
        list: iter,
        deque: iter,
        dict: dict_handler,
        set: iter,
        frozenset: iter,
    }
    seen = set()  # track which object id's have already been seen
    default_size = getsizeof(0)  # estimate sizeof object without __sizeof__

    def sizeof(o):
        if id(o) in seen:  # do not double count the same object
            return 0
        seen.add(id(o))
        s = getsizeof(o, default_size)

        for typ, handler in all_handlers.items():
            if isinstance(o, typ):
                s += sum(map(sizeof, handler(o)))
                break
        return s

    return sizeof(o)

def count_cache_key_tuples(tup):
    """given a cache key tuple, counts how many instances of actual
    tuples are found.

    used to alert large jumps in cache key complexity.

    """
    stack = [tup]

    sentinel = object()
    num_elements = 0

    while stack:
        elem = stack.pop(0)
        if elem is sentinel:
            num_elements += 1
        elif isinstance(elem, tuple):
            if elem:
                stack = list(elem) + [sentinel] + stack
    return num_elements


text:
set :deploy_to, "/data/fuseforge"
set :mongrel_conf, "/data/fuseforge/shared/config/mongrel_cluster/mongrel_cluster.yml"
set :rails_env, 'production'
set :user, "rails"
set :port, 22
set :ssh_options, { :forward_agent => true, :keys => %w(/Users/chirino/sandbox/fuse/fuseinfra/images/common/root/.ssh/id_rsa)  }
set :use_sudo, false

host = "forge.e.fusesourcedev.com"
role :app, host
role :web, host
role :db,  host, :primary => true


text:
'use strict';

var koa = require('koa');
var request = require('supertest');
require('should');

var AV = require('../..');
var config = require('../config');

AV.init(config);

var app = koa();

app.proxy = true;
app.use(AV.Cloud.HttpsRedirect({framework: 'koa'}));

app.use(function *(next) {
  this.body = 'Hello World!';
});

var server = app.listen();

describe('https-redirect', function() {
  it('should redirect', function(done) {
    request(server)
      .get('/test')
      .set('host', 'stg-abc.leanapp.cn')
      .expect(302)
      .end(function(err, res) {
        res.headers.location.should.equal('https://stg-abc.leanapp.cn/test');
        res.text.should.match('Redirecting to https://stg-abc.leanapp.cn/test.');
        done();
      });
  });

  it('should not redirect', function(done) {
    request(server)
      .get('/test')
      .expect(200)
      .expect("Hello World!", done);
  });
});


text:
package backend.interpreter.instances;

import java.util.List;

import backend.interpreter.data.DataHBool;
import backend.interpreter.data.DataHString;
import backend.interpreter.data.DataType;
import backend.interpreter.typeclass.EqClass;
import backend.interpreter.typeclass.ShowClass;
import backend.interpreter.typeclass.TypeClass;

public class InstanceHBool extends Instance {

    public InstanceHBool() {
	classInstances.add(TypeClass.Show);
	classInstances.add(TypeClass.Eq);
    }

    @Override
    public DataType runMethod(String method, List<DataType> l) {
	DataHBool a, b;
	switch (method) {
	// SHOW CLASS
	case ShowClass.SHOW:
	    a = (DataHBool) l.get(0);

	    return new DataHString(a.getData() ? "True" : "False");

	// EQ CLASS
	case EqClass.EQ:
	    a = (DataHBool) l.get(0);
	    b = (DataHBool) l.get(1);

	    return new DataHBool(a.getData() == b.getData());
	case EqClass.NEQ:
	    a = (DataHBool) l.get(0);
	    b = (DataHBool) l.get(1);

	    return new DataHBool(a.getData() != b.getData());
	}
	return null;
    }

}


text:
@interface TWUser : NSObject {

}

@property (nonatomic, copy) NSNumber *notifications;
@property (nonatomic, copy) NSNumber *favourites_count;
@property (nonatomic, copy) NSString *description;
@property (nonatomic, copy) NSNumber *following;
@property (nonatomic, copy) NSNumber *statuses_count;
@property (nonatomic, copy) NSString *profile_text_color;
@property (nonatomic, copy) NSNumber *geo_enabled;
@property (nonatomic, copy) NSString *profile_background_image_url;
@property (nonatomic, copy) NSString *profile_image_url;
@property (nonatomic, copy) NSString *profile_link_color;
@property (nonatomic, copy) NSNumber *verified;
@property (nonatomic, copy) NSNumber *profile_background_tile;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, copy) NSString *screen_name;
@property (nonatomic, copy) NSString *created_at;
@property (nonatomic, copy) NSString *profile_background_color;
@property (nonatomic, copy) NSString *profile_sidebar_fill_color;
@property (nonatomic, copy) NSNumber *followers_count;
@property (nonatomic, copy) NSNumber *protected;
@property (nonatomic, copy) NSString *location;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *time_zone;
@property (nonatomic, copy) NSNumber *friends_count;
@property (nonatomic, copy) NSString *profile_sidebar_border_color;
@property (nonatomic, copy) NSNumber *identifier;
@property (nonatomic, copy) NSNumber *utc_offset;

@end


text:
typedef NS_ENUM(int, LyCacheTime) {

    LyCacheNoRead = 0,
    LyCacheNoSave = -1,
    LyCacheNormal = 5,
    LyCacheOneMinute = 1,
    LyCacheOneDay = 24 * 60,
};

@interface LyNetSetting : NSObject

- (instancetype)initWithCtrlHub:(BOOL)isCtrlHub isCache:(BOOL)isCache timeInterval:(NSTimeInterval)timeInterval cachePolicy:(LyCacheTime)cachePolicy isEncrypt:(BOOL)isEncrypt requestType:(LyRequestSerializerType)requestType responseType:(LyResponseSerializerType)responseType baseUrl:(NSString *)baseUrl;

//加载动画控制方式,NO表示由调用的控制器控制,yes表示有AFNetWork类控制
@property (nonatomic,assign) BOOL isCtrlHub;

//是否缓存
@property (nonatomic,assign) BOOL isCache;

//缓存时长
@property (nonatomic,assign) NSTimeInterval cacheValidTimeInterval;

//缓存的策略
@property (nonatomic,assign) LyCacheTime cachePolicy;

//是否加密
@property (nonatomic,assign) BOOL isEncrypt;

@property (nonatomic,copy  ) NSString *baseUrl;

////请求数据的类型
@property (nonatomic,assign)LyRequestSerializerType requestType;

//响应数据的类型
@property (nonatomic,assign)LyResponseSerializerType responseType;

@end


text:
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;

namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
    internal abstract class AbstractSpecialTypePreselectingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
    {
        public AbstractSpecialTypePreselectingKeywordRecommender(
            SyntaxKind keywordKind,
            bool isValidInPreprocessorContext = false,
            bool shouldFormatOnCommit = false)
            : base(keywordKind, isValidInPreprocessorContext, shouldFormatOnCommit)
        {
        }

        protected abstract SpecialType SpecialType { get; }

        protected override bool ShouldPreselect(CSharpSyntaxContext context, CancellationToken cancellationToken)
        {
            return context.InferredTypes.Any(t => t.SpecialType == this.SpecialType);
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE114_Process_Control__w32_wchar_t_connect_socket_81.h
Label Definition File: CWE114_Process_Control__w32.label.xml
Template File: sources-sink-81.tmpl.h
*/
/*
 * @description
 * CWE: 114 Process Control
 * BadSource: connect_socket Read data using a connect socket (client side)
 * GoodSource: Hard code the full pathname to the library
 * Sinks:
 *    BadSink : Load a dynamic link library
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE114_Process_Control__w32_wchar_t_connect_socket_81
{

class CWE114_Process_Control__w32_wchar_t_connect_socket_81_base
{
public:
    /* pure virtual function */
    virtual void action(wchar_t * data) const = 0;
};

#ifndef OMITBAD

class CWE114_Process_Control__w32_wchar_t_connect_socket_81_bad : public CWE114_Process_Control__w32_wchar_t_connect_socket_81_base
{
public:
    void action(wchar_t * data) const;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE114_Process_Control__w32_wchar_t_connect_socket_81_goodG2B : public CWE114_Process_Control__w32_wchar_t_connect_socket_81_base
{
public:
    void action(wchar_t * data) const;
};

#endif /* OMITGOOD */

}


text:
import java.util.EmptyStackException;

public class Stacks<T> {
    private static class StackNode<T> {
        private T data;
        private StackNode<T> next;

        public StackNode(T data) {
            this.data = data;
        }
    }

    private StackNode<T> top;

    public T pop() {
        if (top == null) throw new EmptyStackException();
        T item = top.data;
        top = top.next;
        return item;
    }

    public void push(T item) {
        StackNode<T> t = new StackNode<>(item);
        t.next = top;
        top = t;
    }

    public T peek() {
        if (top == null) throw new EmptyStackException();
        return top.data;
    }

    public boolean isEmpty() {
        return top == null;
    }

}


text:
package org.springframework.security.config.annotation.web.configurers;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.yadis.YadisResolver;
import org.openid4java.message.AuthRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.openid.OpenIDAttribute;
import org.springframework.security.openid.OpenIDAuthenticationFilter;
import org.springframework.security.openid.OpenIDAuthenticationStatus;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import org.springframework.security.openid.OpenIDConsumer;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Tests to verify that all the functionality of <openid-login> attributes is
 * present
 *
 * @author Rob Winch
 * @author Josh Cummings
 */
@ExtendWith(SpringTestContextExtension.class)
public class NamespaceHttpOpenIDLoginTests {

	public final SpringTestContext spring = new SpringTestContext(this);

	@Autowired
	MockMvc mvc;

	@Test
	public void openidLoginWhenUsingDefaultsThenMatchesNamespace() throws Exception {
		this.spring.register(OpenIDLoginConfig.class).autowire();
		this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/login"));
		this.mvc.perform(post("/login/openid").with(csrf())).andExpect(redirectedUrl("/login?error"));
	}

	@Test
	public void openidLoginWhenAttributeExchangeConfiguredThenFetchAttributesMatchAttributeList() throws Exception {
		OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER = mock(ConsumerManager.class);
		AuthRequest mockAuthRequest = mock(AuthRequest.class);
		DiscoveryInformation mockDiscoveryInformation = mock(DiscoveryInformation.class);
		given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl");
		given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.associate(any()))
				.willReturn(mockDiscoveryInformation);
		given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
				any())).willReturn(mockAuthRequest);
		this.spring.register(OpenIDLoginAttributeExchangeConfig.class).autowire();
		try (MockWebServer server = new MockWebServer()) {
			String endpoint = server.url("/").toString();
			server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
			server.enqueue(new MockResponse()
					.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
			MvcResult mvcResult = this.mvc.perform(get("/login/openid")
					.param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "https://www.google.com/1"))
					.andExpect(status().isFound()).andReturn();
			Object attributeObject = mvcResult.getRequest().getSession()
					.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
			assertThat(attributeObject).isInstanceOf(List.class);
			List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
			assertThat(attributeList.stream().anyMatch((attribute) -> "firstname".equals(attribute.getName())
					&& "https://axschema.org/namePerson/first".equals(attribute.getType()) && attribute.isRequired()))
							.isTrue();
			assertThat(attributeList.stream().anyMatch((attribute) -> "lastname".equals(attribute.getName())
					&& "https://axschema.org/namePerson/last".equals(attribute.getType()) && attribute.isRequired()))
							.isTrue();
			assertThat(attributeList.stream().anyMatch((attribute) -> "email".equals(attribute.getName())
					&& "https://axschema.org/contact/email".equals(attribute.getType()) && attribute.isRequired()))
							.isTrue();
		}
	}

	@Test
	public void openidLoginWhenUsingCustomEndpointsThenMatchesNamespace() throws Exception {
		this.spring.register(OpenIDLoginCustomConfig.class).autowire();
		this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/authentication/login"));
		this.mvc.perform(post("/authentication/login/process").with(csrf()))
				.andExpect(redirectedUrl("/authentication/login?failed"));
	}

	@Test
	public void openidLoginWithCustomHandlersThenBehaviorMatchesNamespace() throws Exception {
		OpenIDAuthenticationToken token = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS,
				"identityUrl", "message", Arrays.asList(new OpenIDAttribute("name", "type")));
		OpenIDLoginCustomRefsConfig.AUDS = mock(AuthenticationUserDetailsService.class);
		User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
		given(OpenIDLoginCustomRefsConfig.AUDS.loadUserDetails(any(Authentication.class))).willReturn(user);
		OpenIDLoginCustomRefsConfig.ADS = spy(new WebAuthenticationDetailsSource());
		OpenIDLoginCustomRefsConfig.CONSUMER = mock(OpenIDConsumer.class);
		this.spring.register(OpenIDLoginCustomRefsConfig.class, UserDetailsServiceConfig.class).autowire();
		given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class)))
				.willThrow(new AuthenticationServiceException("boom"));
		// @formatter:off
		MockHttpServletRequestBuilder login = post("/login/openid")
				.with(csrf())
				.param("openid.identity", "identity");
		// @formatter:on
		this.mvc.perform(login).andExpect(redirectedUrl("/custom/failure"));
		reset(OpenIDLoginCustomRefsConfig.CONSUMER);
		given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class))).willReturn(token);
		this.mvc.perform(login).andExpect(redirectedUrl("/custom/targetUrl"));
		verify(OpenIDLoginCustomRefsConfig.AUDS).loadUserDetails(any(Authentication.class));
		verify(OpenIDLoginCustomRefsConfig.ADS).buildDetails(any(Object.class));
	}

	@Configuration
	@EnableWebSecurity
	static class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.authorizeRequests()
					.anyRequest().hasRole("USER")
					.and()
				.openidLogin()
					.permitAll();
			// @formatter:on
		}

	}

	@Configuration
	@EnableWebSecurity
	static class OpenIDLoginAttributeExchangeConfig extends WebSecurityConfigurerAdapter {

		static ConsumerManager CONSUMER_MANAGER;

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.authorizeRequests()
					.anyRequest().hasRole("USER")
					.and()
				.openidLogin()
					.consumerManager(CONSUMER_MANAGER)
					.attributeExchange("https://www.google.com/.*") // attribute-exchange@identifier-match
						.attribute("email") // openid-attribute@name
							.type("https://axschema.org/contact/email") // openid-attribute@type
							.required(true) // openid-attribute@required
							.count(1) // openid-attribute@count
							.and()
						.attribute("firstname")
							.type("https://axschema.org/namePerson/first")
							.required(true)
							.and()
						.attribute("lastname")
							.type("https://axschema.org/namePerson/last")
							.required(true)
							.and()
						.and()
					.attributeExchange(".*yahoo.com.*")
						.attribute("email")
							.type("https://schema.openid.net/contact/email")
							.required(true)
							.and()
						.attribute("fullname")
							.type("https://axschema.org/namePerson")
							.required(true)
							.and()
						.and()
					.permitAll();
			// @formatter:on
		}

	}

	@Configuration
	@EnableWebSecurity
	static class OpenIDLoginCustomConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			boolean alwaysUseDefaultSuccess = true;
			// @formatter:off
			http
				.authorizeRequests()
					.anyRequest().hasRole("USER")
					.and()
				.openidLogin()
					.permitAll()
					.loginPage("/authentication/login") // openid-login@login-page
					.failureUrl("/authentication/login?failed") // openid-login@authentication-failure-url
					.loginProcessingUrl("/authentication/login/process") // openid-login@login-processing-url
					.defaultSuccessUrl("/default", alwaysUseDefaultSuccess); // openid-login@default-target-url / openid-login@always-use-default-target
			// @formatter:on
		}

	}

	@Configuration
	@EnableWebSecurity
	static class OpenIDLoginCustomRefsConfig extends WebSecurityConfigurerAdapter {

		static AuthenticationUserDetailsService AUDS;
		static AuthenticationDetailsSource ADS;
		static OpenIDConsumer CONSUMER;

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
			handler.setDefaultTargetUrl("/custom/targetUrl");
			// @formatter:off
			http
				.authorizeRequests()
					.anyRequest().hasRole("USER")
					.and()
				.openidLogin()
					// if using UserDetailsService wrap with new UserDetailsByNameServiceWrapper<OpenIDAuthenticationToken>()
					.authenticationUserDetailsService(AUDS) // openid-login@user-service-ref
					.failureHandler(new SimpleUrlAuthenticationFailureHandler("/custom/failure")) // openid-login@authentication-failure-handler-ref
					.successHandler(handler) // openid-login@authentication-success-handler-ref
					.authenticationDetailsSource(ADS) // openid-login@authentication-details-source-ref
					.withObjectPostProcessor(new ObjectPostProcessor<OpenIDAuthenticationFilter>() {
						@Override
						public <O extends OpenIDAuthenticationFilter> O postProcess(O filter) {
							filter.setConsumer(CONSUMER);
							return filter;
						}
					});
			// @formatter:on
		}

	}

	@Configuration
	static class UserDetailsServiceConfig {

		@Bean
		UserDetailsService userDetailsService() {
			return new InMemoryUserDetailsManager(
					User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
		}

	}

}


text:
package com.foc.dataSource.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.foc.Globals;
import com.foc.SrvConst_ServerSide;
import com.foc.admin.FocLoginAccess;
import com.foc.util.Encryptor;
import com.foc.vaadin.FocWebApplication;
import com.foc.web.server.FocWebServer;
import com.foc.web.server.session.FocWebSession;

@SuppressWarnings("serial")
public class FocLinkServlet extends HttpServlet implements SrvConst_ServerSide {

   public void doGet (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
   {
      response.setContentType("text/html");
      response.setHeader("Pragma", "No-cache");
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache");

      PrintWriter out = response.getWriter();
      out.println("");
      out.println("<title>Everpro Servlet</title>");
      out.println("");
      out.println("
Everpro Servlet
");
      out.println ("
 Please post a request to this servlet in order to get a valid response.");
      out.println("");
      out.flush();

   }

	public SessionAndApplication doPost_Init(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String requestSessionID = request.getSession().getId();
		Globals.logString("SESSION_ID = " + requestSessionID);

		// Using the Basic authorization HTTP protocol creates an
		// IllegalArgumentException in Java. Known bug. Apparently fixed in JDK7
		// String auth = request.getHeader("Authorization");

		//FocWebServer webServer = FocWebServer.connect(request.getSession().getServletContext());
		// FocThreadLocal.setWebServer(webServer);//This line is important when the
		// WebServer already exists. In the second call or if the WebServer is
		// launched by the GUI

		FocWebApplication webApplication = null;
		FocWebSession webSession = null;
		int status = com.foc.Application.LOGIN_WRONG;

		{
			webApplication = FocWebServer.findWebApplicationBySessionID(requestSessionID, request.getSession().getServletContext());
			if (webApplication == null) {
				Globals.logString("EverproLinkServlet is creating a new FocWebApplication(UI)");
				try {
					Class cls = Class.forName("siren.isf.fenix.main.FenixUI");
					Class[] param = new Class[0];
					Constructor constr = cls.getConstructor(param);
					Object[] argsNew = new Object[0];

					webApplication = (FocWebApplication) constr.newInstance(argsNew);
					FocWebApplication.setInstanceForThread(webApplication);
					webApplication.initialize(null, request.getServletContext(), request.getSession(), false);
					webApplication.setData(FocWebServer.getInstance());
				} catch (Exception e) {
					Globals.logException(e);
				}
			}

			if (webApplication != null) {
				webSession = webApplication.getFocWebSession();
			}

			// ---------------------------------------------
			// If the FocWebSession is not found, create a new FocWebApplication and a
			// new FocWebSession.
			if (webSession == null) {
				Globals.logString("EverproLinkServlet is creating a new FocWebSession and adding the FocWebApplication(UI) to the webServer");
				webApplication.setFocWebSession(request.getSession(), new FocWebSession(request.getSession()));
				FocWebServer.getInstance().addApplication(webApplication);
				webSession = FocWebServer.findWebSessionBySessionID(requestSessionID, FocWebServer.getInstance());
			}

			// ---------------------------------------------
			// If the FocWebSession has no user, try to log in by reading the user
			// name and password from the HTTP request header.
			if (webSession != null && webSession.getFocUser() == null) {
				String username = request.getHeader("username");
				String password = request.getHeader("password");
				if (username == null) {
					username = (String) request.getAttribute(HEADER_KEY_USERNAME);
				}
				if (password == null) {
					password = (String) request.getAttribute(HEADER_KEY_PASSWORD);
				}

				Globals.logString(username);
				Globals.logString(password);
				String encryptedPassword = Encryptor.encrypt_MD5(String.valueOf(password));
				FocLoginAccess loginAccess = new FocLoginAccess();

				status = loginAccess.checkUserPassword(username, encryptedPassword, false);

				if (status == com.foc.Application.LOGIN_VALID) {
					// webSession = newApplication.getFocWebSession();
					webSession.setFocUser(loginAccess.getUser());
				}
				if (status == com.foc.Application.LOGIN_WRONG) {
					Globals.logString("Error: Login credentials are incorrect.");
//					PrintWriter printWriter = response.getWriter();
//					printWriter.println("Error: Login credentials are incorrect.");
				}
			}
		}

		SessionAndApplication session = new SessionAndApplication(webSession, webApplication, status);
		return session;
	}

  public class SessionAndApplication {
  	private FocWebSession     webSession     = null;
  	private FocWebApplication webApplication = null;
  	private int status = com.foc.Application.LOGIN_WRONG;

  	public SessionAndApplication(FocWebSession webSession, FocWebApplication webApplication, int status){
  		this.webSession     = webSession;
  		this.webApplication = webApplication;
  		this.status = status;
  	}

  	public void dispose(){
  		webSession = null;
  		webApplication = null;
  	}

		public FocWebSession getWebSession() {
			return webSession;
		}

		public void setWebSession(FocWebSession webSession) {
			this.webSession = webSession;
		}

		public FocWebApplication getWebApplication() {
			return webApplication;
		}

		public void setWebApplication(FocWebApplication webApplication) {
			this.webApplication = webApplication;
		}

		public int getStatus() {
			return status;
		}

		public void setStatus(int status) {
			this.status = status;
		}
  }

	public SessionAndApplication doPost_Init2(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String requestSessionID = request.getSession().getId();
		Globals.logString("SESSION_ID = " + requestSessionID);

		// Using the Basic authorization HTTP protocol creates an
		// IllegalArgumentException in Java. Known bug. Apparently fixed in JDK7
		// String auth = request.getHeader("Authorization");

		FocWebServer webServer = FocWebServer.connect(request.getSession().getServletContext(), false);
		// FocThreadLocal.setWebServer(webServer);//This line is important when the
		// WebServer already exists. In the second call or if the WebServer is
		// launched by the GUI

		FocWebApplication webApplication = null;
		FocWebSession webSession = null;
		int status = com.foc.Application.LOGIN_WRONG;

		if (webServer == null) {
			Globals.logString("Could not connect to the WebServer webServer = null");
		} else {
			webApplication = FocWebServer.findWebApplicationBySessionID(requestSessionID, webServer);
			if (webApplication == null) {
				Globals.logString("EverproLinkServlet is creating a new FocWebApplication(UI)");
				try {
					Class cls = Class.forName("b01.everpro.custom.application.CustomEverproWebApplication");
					Class[] param = new Class[0];
					Constructor constr = cls.getConstructor(param);
					Object[] argsNew = new Object[0];

					webApplication = (FocWebApplication) constr.newInstance(argsNew);
					FocWebApplication.setInstanceForThread(webApplication);
					webApplication.setData(webServer);
				} catch (Exception e) {
					Globals.logException(e);
				}
			}

			if (webApplication != null) {
				webSession = webApplication.getFocWebSession();
			}

			// ---------------------------------------------
			// If the FocWebSession is not found, create a new FocWebApplication and a
			// new FocWebSession.
			if (webSession == null) {
				Globals.logString("EverproLinkServlet is creating a new FocWebSession and adding the FocWebApplication(UI) to the webServer");
				webApplication.setFocWebSession(request.getSession(), new FocWebSession(request.getSession()));
				webServer.addApplication(webApplication);
				webSession = FocWebServer.findWebSessionBySessionID(requestSessionID, webServer);
			}

			// ---------------------------------------------
			// If the FocWebSession has no user, try to log in by reading the user
			// name and password from the HTTP request header.
			if (webSession != null && webSession.getFocUser() == null) {
				String username = request.getHeader("username");
				String password = request.getHeader("password");
				if (username == null) {
					username = (String) request.getAttribute(HEADER_KEY_USERNAME);
				}
				if (password == null) {
					password = (String) request.getAttribute(HEADER_KEY_PASSWORD);
				}

				Globals.logString(username);
				Globals.logString(password);
				String encryptedPassword = Encryptor.encrypt_MD5(String.valueOf(password));
				FocLoginAccess loginAccess = new FocLoginAccess();

				status = loginAccess.checkUserPassword(username, encryptedPassword, false);

				if (status == com.foc.Application.LOGIN_VALID) {
					// webSession = newApplication.getFocWebSession();
					webSession.setFocUser(loginAccess.getUser());
				}
				if (status == com.foc.Application.LOGIN_WRONG) {
					Globals.logString("Error: Login credentials are incorrect.");
//					PrintWriter printWriter = response.getWriter();
//					printWriter.println("Error: Login credentials are incorrect.");
				}
			}
		}

		SessionAndApplication session = new SessionAndApplication(webSession, webApplication, status);
		return session;
	}

}


text:
import copy
import json
import os

from rdr_service.main_util import configure_logging
from rdr_service.rdr_client.client import Client
from tests.helpers.unittest_base import BaseTestCase

# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = "http://localhost:8080"

_OFFLINE_BASE_PATH = "offline"

class BaseClientTest(BaseTestCase):
    def setUp(self):
        super().setUp()
        configure_logging()
        self.maxDiff = None
        instance = os.environ.get("PMI_DRC_RDR_INSTANCE") or _DEFAULT_INSTANCE
        creds_file = os.environ.get("TESTING_CREDS_FILE")
        self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
        self.offline_client = Client(
            base_path=_OFFLINE_BASE_PATH, parse_cli=False, default_instance=instance, creds_file=creds_file
        )

    def assertJsonEquals(self, obj_a, obj_b):
        obj_b = copy.deepcopy(obj_b)
        for transient_key in ("etag", "kind", "meta"):
            if transient_key in obj_b:
                del obj_b[transient_key]
        self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))

def _pretty(obj):
    return json.dumps(obj, sort_keys=True, indent=4, separators=(",", ": "))


text:
typedef struct {
	mraa_aio_context signal;
	int reading;
	float temperature;
	char units;
} THERMISTOR;

THERMISTOR *thermistor_init(int aio_pin, char units);
float thermistor_read(THERMISTOR *thermistor);
void thermistor_off(THERMISTOR *thermistor);


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You under the Apache License, Version 2.0
  ~ (the "License"); you may not use this file except in compliance with
  ~ the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:shadow="http://shardingsphere.apache.org/schema/shardingsphere/shadow"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://shardingsphere.apache.org/schema/shardingsphere/shadow
                           http://shardingsphere.apache.org/schema/shardingsphere/shadow/shadow.xsd
                           ">
    <shadow:shadow-algorithm id="simple-hint-algorithm" type="SIMPLE_HINT">
        <props>
            <prop key="shadow">true</prop>
            <prop key="foo">bar</prop>
        </props>
    </shadow:shadow-algorithm>

    <shadow:rule id="shadowRule">
        <shadow:data-source id="shadow-data-source" source-data-source-name="ds" shadow-data-source-name="ds-shadow"/>
        <shadow:default-shadow-algorithm-name name="simple-hint-algorithm"/>
    </shadow:rule>
</beans>


text:
import java.io.*;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.*;
import javax.naming.*;

public class QueueSend
{
    public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
    public final static String JMS_FACTORY = "com.wlsexpert.ConnectionFactory";
    public final static String QUEUE = "com.wlsexpert.Queue";

    private QueueConnectionFactory qconFactory;
    private QueueConnection qcon;
    private QueueSession qsession;
    private QueueSender qsender;
    private Queue queue;
    private TextMessage msg;

    public void init(Context ctx, String queueName) throws NamingException, JMSException
    {
        qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
        qcon = qconFactory.createQueueConnection();
        qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queue = (Queue) ctx.lookup(queueName);
        qsender = qsession.createSender(queue);
        msg = qsession.createTextMessage();
        qcon.start();
    }
    public void send(String message) throws JMSException
    {
        msg.setText(message);
        qsender.send(msg);
    }

    public void close() throws JMSException
    {
        qsender.close();
        qsession.close();
        qcon.close();
    }
    public static void main(String[] args) throws Exception
    {
        if (args.length != 1)
        {
            System.out.println("Usage: java QueueSend WebLogicURL");
            return;
        }

        InitialContext ic = getInitialContext(args[0]);
        QueueSend qs = new QueueSend();
        qs.init(ic, QUEUE);
        readAndSend(qs);
        qs.close();
    }

    private static void readAndSend(QueueSend qs) throws IOException, JMSException
    {
        String line = "Test Message Body with counter = ";
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        boolean readFlag = true;
        System.out.println("\n\tStart Sending Messages (Enter QUIT to Stop):\n");

        while (readFlag)
        {
            System.out.print("Msg_Sender: ");
            String msg = br.readLine();

            if (msg.equals("QUIT")
            ||  msg.equals("quit"))
            {
                qs.send(msg);
                System.exit(0);
            }

            qs.send(msg);
            System.out.println();
        }
        br.close();
    }

    private static InitialContext getInitialContext(String url) throws NamingException
    {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
        env.put(Context.PROVIDER_URL, url);
        return new InitialContext(env);
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.ascaria.network;

import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import cz.ascaria.network.messages.ChatCommandMessage;
import cz.ascaria.network.messages.ChatMessage;
import cz.ascaria.zoneofuprising.ZoneOfUprising;
import cz.ascaria.zoneofuprising.ai.ArtificialIntelligence;
import cz.ascaria.zoneofuprising.entities.BaseEntitiesManager;
import cz.ascaria.zoneofuprising.entities.Entity;
import cz.ascaria.zoneofuprising.utils.Vector3fHelper;
import cz.ascaria.zoneofuprising.world.ServerWorldManager;
import java.util.concurrent.Callable;

/**
 *
 * @author Ascaria Quynn
 */
public class ChatCommandManager implements MessageListener<HostedConnection> {

    private ServerWrapper gameServer;
    private BaseEntitiesManager entitiesManager;
    private ZoneOfUprising app;

    public void initialize(ServerWorldManager worldManager, ZoneOfUprising app) {
        this.gameServer = app.getGameServer();
        this.entitiesManager = app.getEntitiesManager();
        this.app = app;

        gameServer.addMessageListener(this,
            ChatCommandMessage.class
        );
    }

    public void cleanup() {
        gameServer.removeMessageListener(this);
    }

    public void messageReceived(final HostedConnection source, final Message m) {
        app.enqueue(new Callable() {
            public Object call() throws Exception {
                if(m instanceof ChatCommandMessage) {
                    chatCommandMessage(source, (ChatCommandMessage)m);
                }
                return null;
            }
        });
    }

    /**
     * Called when an chat command message is received, this means message that pass "^([a-z/]+) \"([^\"]+)\" (.+)".
     * @param source
     * @param m
     */
    public void chatCommandMessage(HostedConnection source, ChatCommandMessage m) {
        Console.sysprintln("Received chat command message: command: " + m.command + "; from: " + m.from + "; to: " + m.to + ";  message: " + m.message);
        // Find entity's location
        if(m.command.equals("/loc") && entitiesManager.entityExist(m.from)) {
            Entity entity = entitiesManager.getEntity(m.from);
            gameServer.send(source, new ChatMessage("System", "Your location is " + Vector3fHelper.round(entity.getNode().getWorldTranslation(), 2)));
        }
        // Send command to entity's AI
        if(m.command.equals("/entity")) {
            entityCommand(source, m);
        }
    }

    /**
     * Received entity command.
     * @param source
     * @param m
     */
    public void entityCommand(HostedConnection source, ChatCommandMessage m) {
        if(null != m.to && m.to.endsWith("*")) {
            for(String entityName : entitiesManager.getEntities().keySet()) {
                String beginning = m.to.substring(0, m.to.indexOf("*"));
                if(null != entityName && entityName.startsWith(beginning) && entitiesManager.entityExist(entityName)) {
                    ArtificialIntelligence ai = entitiesManager.getEntity(entityName).getNode().getControl(ArtificialIntelligence.class);
                    if(null != ai) {
                        ai.respond(source, m);
                    }
                }
            }
        } else if(entitiesManager.entityExist(m.to)) {
            Console.sysprintln("Entity '" + m.to + "' was found");
            ArtificialIntelligence ai = entitiesManager.getEntity(m.to).getNode().getControl(ArtificialIntelligence.class);
            if(null != ai) {
                ai.respond(source, m);
            }
        } else {
            gameServer.send(source, new ChatMessage("System", "Entity '" + m.to + "' was not found."));
        }
    }
}


text:
package org.apache.geode.internal.datasource;

/**
 * This class models a connection pool for non-transactional database connection. Extends the
 * AbstractPoolCache to inherit the pool bahavior.
 *
 */
import java.sql.SQLException;

import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;

import org.apache.logging.log4j.Logger;

import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.logging.LogService;

public class ConnectionPoolCacheImpl extends AbstractPoolCache {
  private static final Logger logger = LogService.getLogger();

  private static final long serialVersionUID = -3096029291871746431L;

  private ConnectionPoolDataSource m_cpds;

  /**
   * Constructor initializes the ConnectionPoolCacheImpl properties.
   */
  public ConnectionPoolCacheImpl(ConnectionPoolDataSource connectionpooldatasource,
      ConnectionEventListener eventListner, ConfiguredDataSourceProperties configs)
      throws PoolException {
    super(eventListner, configs);
    m_cpds = connectionpooldatasource;
    initializePool();
  }

  /**
   * This method destroys the connection.
   */
  @Override
  void destroyPooledConnection(Object connectionObject) {
    try {
      ((PooledConnection) connectionObject)
          .removeConnectionEventListener((javax.sql.ConnectionEventListener) connEventListner);
      ((PooledConnection) connectionObject).close();
      connectionObject = null;
    } catch (Exception ex) {
      if (logger.isTraceEnabled()) {
        logger.trace(
            "AbstractPoolcache::destroyPooledConnection:Exception in closing the connection.Ignoring it. The exeption is {}",
            ex.getMessage(), ex);
      }
    }
  }

  /**
   * Creates a new connection for the pool.
   *
   * @return the connection from the database as Object.
   */
  @Override
  public Object getNewPoolConnection() throws PoolException {
    if (m_cpds != null) {
      PooledConnection poolConn = null;
      try {
        poolConn = m_cpds.getPooledConnection(configProps.getUser(), configProps.getPassword());
      } catch (SQLException sqx) {
        throw new PoolException(
            LocalizedStrings.ConnectionPoolCacheImpl_CONNECTIONPOOLCACHEIMPLGENEWCONNECTION_EXCEPTION_IN_CREATING_NEW_POOLEDCONNECTION
                .toLocalizedString(),
            sqx);
      }
      poolConn.addConnectionEventListener((javax.sql.ConnectionEventListener) connEventListner);
      return poolConn;
    } else {
      if (logger.isDebugEnabled()) {
        logger.debug(
            "ConnectionPoolCacheImpl::geNewConnection: ConnectionPoolCache not intialized with ConnectionPoolDatasource");
      }
      throw new PoolException(
          LocalizedStrings.ConnectionPoolCacheImpl_CONNECTIONPOOLCACHEIMPLGENEWCONNECTION_CONNECTIONPOOLCACHE_NOT_INTIALIZED_WITH_CONNECTIONPOOLDATASOURCE
              .toLocalizedString());
    }
  }
}