org.apache.synapse.core.SynapseEnvironment Java Examples

The following examples show how to use org.apache.synapse.core.SynapseEnvironment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * @param to     get an endpoint to send the information
 * @param member The member to which an EP has to be created
 * @param synCtx synapse context
 * @return the created endpoint
 */
private Endpoint getEndpoint(EndpointReference to, org.apache.axis2.clustering.Member member, MessageContext synCtx) {
    AddressEndpoint endpoint = new AddressEndpoint();
    endpoint.setEnableMBeanStats(false);
    endpoint.setName("DLB:" + member.getHostName() +
            ":" + member.getPort() + ":" + UUID.randomUUID());

    EndpointDefinition definition = new EndpointDefinition();
    definition.setTimeoutAction(SynapseConstants.DISCARD_AND_FAULT);
    definition.setTimeoutDuration(LoadBalancerConfiguration.getInstance().getEndpointTimeout());
    definition.setReplicationDisabled(true);
    definition.setAddress(to.getAddress());

    endpoint.setDefinition(definition);
    endpoint.init((SynapseEnvironment)
            ((Axis2MessageContext) synCtx).getAxis2MessageContext().
                    getConfigurationContext().getAxisConfiguration().
                    getParameterValue(SynapseConstants.SYNAPSE_ENV));
    return endpoint;
}
 
Example #2
Source File: APIAuthenticationHandler.java    From docs-apim with Apache License 2.0 6 votes vote down vote up
public void init(SynapseEnvironment synapseEnvironment) {
if (log.isDebugEnabled()) {
	log.debug("Initializing API authentication handler instance");
}
      String authenticatorType = ServiceReferenceHolder.getInstance().getAPIManagerConfiguration().
              getFirstProperty(APISecurityConstants.API_SECURITY_AUTHENTICATOR);
      if (authenticatorType == null) {
          authenticatorType = OAuthAuthenticator.class.getName();
      }
      try {
          authenticator = (Authenticator) Class.forName(authenticatorType).newInstance();
      } catch (Exception e) {
          // Just throw it here - Synapse will handle it
          throw new SynapseException("Error while initializing authenticator of " +
                  "type: " + authenticatorType);
      }
      authenticator.init(synapseEnvironment);
  }
 
Example #3
Source File: TaskResource.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private void populateTaskData(MessageContext messageContext, String taskName) {

        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();

        SynapseConfiguration configuration = messageContext.getConfiguration();
        Startup task = configuration.getStartup(taskName);
        SynapseEnvironment synapseEnvironment =
                getSynapseEnvironment(axis2MessageContext.getConfigurationContext().getAxisConfiguration());
        TaskDescription description =
                synapseEnvironment.getTaskManager().getTaskDescriptionRepository().getTaskDescription(task.getName());
        JSONObject jsonBody = getTaskAsJson(description);


        if (Objects.nonNull(jsonBody)) {
            Utils.setJsonPayLoad(axis2MessageContext, jsonBody);
        } else {
            axis2MessageContext.setProperty(Constants.HTTP_STATUS_CODE, Constants.NOT_FOUND);
        }
    }
 
Example #4
Source File: RabbitMQInjectHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public RabbitMQInjectHandler(String injectingSeq, String onErrorSeq, boolean sequential,
                             SynapseEnvironment synapseEnvironment) {
    this.injectingSeq = injectingSeq;
    if (injectingSeq == null || injectingSeq.equals("")) {
        String msg = "Injecting Sequence name is not specified.";
        log.error(msg);
        throw new SynapseException(msg);
    }
    seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration().getSequence(injectingSeq);
    if (seq == null) {
        throw new SynapseException("Specified injecting sequence: " + injectingSeq + "is invalid.");
    }
    if (!seq.isInitialized()) {
        seq.init(synapseEnvironment);
    }
    this.onErrorSeq = onErrorSeq;
    this.sequential = sequential;
    this.synapseEnvironment = synapseEnvironment;
}
 
Example #5
Source File: StartupUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public static TaskDescription getTaskDescription(String name, SynapseEnvironment synapseEnvironment) {

		if (log.isDebugEnabled()) {
			log.debug("Returning a Startup : " + name + " from the configuration");
		}
		TaskDescription taskDescription = synapseEnvironment.getTaskManager().
				getTaskDescriptionRepository().getTaskDescription(name);
		if (taskDescription != null) {
			if (log.isDebugEnabled()) {
				log.debug("Returning a TaskDescription : " + taskDescription);

			}
			return taskDescription;
		} else {
			if (log.isDebugEnabled()) {
				log.debug("There is no  Startup with name :" + name);
			}
			return null;
		}
	}
 
Example #6
Source File: StartupUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public static void updateStartup(String name, OMElement taskElement, SynapseConfiguration synapseConfiguration,
                                 SynapseEnvironment synapseEnvironment) {

	Startup st = synapseConfiguration.getStartup(name);

	if (st == null) {
		log.warn("Cannot update the startup named: " + name + ", it doesn't exists in the SynapseConfiguration");
		return;
	}

	String fileName = null;
	if (st instanceof AbstractStartup) {
		fileName = st.getFileName();
	}

	deleteStartup(st.getName(), synapseConfiguration);
	addStartup(taskElement, fileName, false, synapseConfiguration, synapseEnvironment);
}
 
Example #7
Source File: StartupUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private static void addStartup(OMElement startupElement, String fileName, boolean generateFileName,
                               SynapseConfiguration synapseConfiguration, SynapseEnvironment synapseEnvironment) {

	SimpleQuartzFactory factory = new SimpleQuartzFactory();
	Startup startup = factory.createStartup(startupElement);

	if (startup == null) {
		handleException("Startup is null");
	} else {
		if (startup instanceof AbstractStartup) {
			if (generateFileName) {
				fileName = ServiceBusUtils.generateFileName((startup.getName()));
			}
			startup.setFileName(fileName);
		}
		synapseConfiguration.addStartup(startup);
		startup.init(synapseEnvironment);
		persistStartup(startup, synapseConfiguration.getAxisConfiguration());

		if (log.isDebugEnabled()) {
			log.debug("Added Startup : " + startup + " from the configuration");
		}
	}
}
 
Example #8
Source File: LoadBalancerServiceComponent.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Un-registers the Endpoint deployer.
 *
 * @param axisConfig         AxisConfiguration to which this deployer belongs
 * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
 */
private void unregisterDeployer(AxisConfiguration axisConfig,
                                SynapseEnvironment synapseEnvironment)
        throws TenantAwareLoadBalanceEndpointException {
    if (axisConfig != null) {
        DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig
                .getConfigurator();
        String synapseConfigPath = ServiceBusUtils
                .getSynapseConfigAbsPath(synapseEnvironment
                        .getServerContextInformation());
        String endpointDirPath = synapseConfigPath + File.separator
                + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
        deploymentEngine.removeDeployer(endpointDirPath,
                ServiceBusConstants.ARTIFACT_EXTENSION);
    }
}
 
Example #9
Source File: LoadBalancerServiceComponent.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Registers the Endpoint deployer.
 *
 * @param axisConfig         AxisConfiguration to which this deployer belongs
 * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
 */
private void registerDeployer(AxisConfiguration axisConfig,
                              SynapseEnvironment synapseEnvironment)
        throws TenantAwareLoadBalanceEndpointException {
    SynapseConfiguration synCfg = synapseEnvironment
            .getSynapseConfiguration();
    DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig
            .getConfigurator();
    SynapseArtifactDeploymentStore deploymentStore = synCfg
            .getArtifactDeploymentStore();

    String synapseConfigPath = ServiceBusUtils
            .getSynapseConfigAbsPath(synapseEnvironment
                    .getServerContextInformation());
    String endpointDirPath = synapseConfigPath + File.separator
            + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;

    for (Endpoint ep : synCfg.getDefinedEndpoints().values()) {
        if (ep.getFileName() != null) {
            deploymentStore.addRestoredArtifact(endpointDirPath
                    + File.separator + ep.getFileName());
        }
    }
    deploymentEngine.addDeployer(new EndpointDeployer(), endpointDirPath,
            ServiceBusConstants.ARTIFACT_EXTENSION);
}
 
Example #10
Source File: LoadBalancerServiceComponent.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
protected void unsetSynapseRegistrationsService(
        SynapseRegistrationsService synapseRegistrationsService) {
    int tenantId = synapseRegistrationsService.getTenantId();
    if (ServiceReferenceHolder.getInstance().containsSynapseEnvironmentService(tenantId)) {
        SynapseEnvironment env = ServiceReferenceHolder.getInstance().getSynapseEnvironmentService(tenantId)
                .getSynapseEnvironment();

        ServiceReferenceHolder.getInstance().removeSynapseEnvironmentService(
                synapseRegistrationsService.getTenantId());

        AxisConfiguration axisConfig = synapseRegistrationsService
                .getConfigurationContext().getAxisConfiguration();
        if (axisConfig != null) {
            try {
                unregisterDeployer(axisConfig, env);
            } catch (Exception e) {
                log.warn("Couldn't remove the endpoint deployer");
            }
        }
    }
}
 
Example #11
Source File: GenericProcessor.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public GenericProcessor(String name, String classImpl, Properties properties, long scanInterval,
                        String injectingSeq, String onErrorSeq, SynapseEnvironment synapseEnvironment,
                        boolean coordination, boolean sequential) {
    this.name = name;
    this.properties = properties;
    this.interval = scanInterval;
    this.injectingSeq = injectingSeq;
    this.onErrorSeq = onErrorSeq;
    this.synapseEnvironment = synapseEnvironment;
    this.classImpl = classImpl;
    this.coordination = coordination;
    this.sequential = sequential;
}
 
Example #12
Source File: GenericEventBasedConsumer.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public GenericEventBasedConsumer(Properties properties, String name, SynapseEnvironment synapseEnvironment,
                                 String injectingSeq, String onErrorSeq, boolean coordination, boolean sequential) {
    this.properties = properties;
    this.name = name;
    this.synapseEnvironment = synapseEnvironment;
    this.injectingSeq = injectingSeq;
    this.onErrorSeq = onErrorSeq;
    this.coordination = coordination;
    this.sequential = sequential;
}
 
Example #13
Source File: StartupUtils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public static Iterator<TaskDescription> getAllTaskDescriptions(SynapseEnvironment synapseEnvironment) {

		if (log.isDebugEnabled()) {
			log.debug("Returning a All Startups from the configuration");
		}
		return synapseEnvironment.getTaskManager().
				getTaskDescriptionRepository().getAllTaskDescriptions();
	}
 
Example #14
Source File: MqttInjectHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * constructor initialize parameters and synapseEnvironment
 *
 * @param injectingSeq
 * @param onErrorSeq
 * @param sequential
 * @param synapseEnvironment
 */
public MqttInjectHandler(String injectingSeq, String onErrorSeq, boolean sequential,
                         SynapseEnvironment synapseEnvironment, String contentType) {
    this.injectingSeq = injectingSeq;
    this.onErrorSeq = onErrorSeq;
    this.sequential = sequential;
    this.synapseEnvironment = synapseEnvironment;
    this.contentType = contentType;
}
 
Example #15
Source File: KAFKAInjectHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public KAFKAInjectHandler(String injectingSeq, String onErrorSeq, boolean sequential,
                          SynapseEnvironment synapseEnvironment, String contentType) {
    this.injectingSeq = injectingSeq;
    this.onErrorSeq = onErrorSeq;
    this.sequential = sequential;
    this.synapseEnvironment = synapseEnvironment;
    this.contentType = contentType;
}
 
Example #16
Source File: MicroIntegratorBaseUtils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Get Synapse Environment. This might throw NPE if called before SynapseEnvironment is initialized.
 *
 * @return SynapseEnvironment - SynapseEnvironment
 */
public static SynapseEnvironment getSynapseEnvironment() {

    Parameter synapseEnvironmentParatemer =
            CarbonCoreDataHolder.getInstance().getAxis2ConfigurationContextService().getServerConfigContext()
                    .getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV);
    return (SynapseEnvironment) synapseEnvironmentParatemer.getValue();
}
 
Example #17
Source File: InboundGRPCListener.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public InboundGRPCListener(InboundProcessorParams params) {
    String injectingSeq = params.getInjectingSeq();
    String onErrorSeq = params.getOnErrorSeq();
    SynapseEnvironment synapseEnvironment = params.getSynapseEnvironment();
    String portParam = params.getProperties().getProperty(InboundGRPCConstants.INBOUND_ENDPOINT_PARAMETER_GRPC_PORT);
    try {
        port = Integer.parseInt(portParam);
    } catch (NumberFormatException e) {
        log.warn("Exception occurred when getting " + InboundGRPCConstants.INBOUND_ENDPOINT_PARAMETER_GRPC_PORT +
                " property. Setting the port as " + InboundGRPCConstants.DEFAULT_INBOUND_ENDPOINT_GRPC_PORT);
        port = InboundGRPCConstants.DEFAULT_INBOUND_ENDPOINT_GRPC_PORT;
    }
    injectHandler = new GRPCInjectHandler(injectingSeq, onErrorSeq, false, synapseEnvironment);
}
 
Example #18
Source File: BasicAuthAuthenticator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes this authenticator instance.
 *
 * @param env Current SynapseEnvironment instance
 */
public void init(SynapseEnvironment env) {
    try {
        this.basicAuthCredentialValidator = new BasicAuthCredentialValidator();
    } catch (APISecurityException e) {
        log.error(e);
    }
}
 
Example #19
Source File: CORSRequestHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public void init(SynapseEnvironment synapseEnvironment) {
    if (log.isDebugEnabled()) {
        log.debug("Initializing CORSRequest Handler instance");
    }
    if (getApiManagerConfigurationService() != null) {
        initializeHeaders();
    }
}
 
Example #20
Source File: APIAuthenticationHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public void init(SynapseEnvironment synapseEnvironment) {
    this.synapseEnvironment = synapseEnvironment;
    if (log.isDebugEnabled()) {
        log.debug("Initializing API authentication handler instance");
    }
    if (getApiManagerConfigurationService() != null) {
        initializeAuthenticators();
    }
    if (StringUtils.isNotEmpty(keyManagers)) {
        Collections.addAll(keyManagersList, keyManagers.split(","));
    } else {
        keyManagersList.add(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS);
    }
}
 
Example #21
Source File: APIAuthenticationHandlerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void setup(){
    synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    messageContext = Mockito.mock(Axis2MessageContext.class);
    axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(APIMgtGatewayConstants.REQUEST_RECEIVED_TIME)).thenReturn("1506576365");
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);

    PowerMockito.mockStatic(Timer.Context.class);
    context = Mockito.mock(Timer.Context.class);
}
 
Example #22
Source File: APIAuthenticationHandlerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleRequestSecurityException() {
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    APIAuthenticationHandler apiAuthenticationHandler = createAPIAuthenticationHandlerForExceptionTest();
    apiAuthenticationHandler.init(synapseEnvironment);

    Options options = Mockito.mock(Options.class);
    Mockito.when(options.getMessageId()).thenReturn("1");
    Mockito.when(axis2MsgCntxt.getOptions()).thenReturn(options);

    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIConstants.USER_AGENT, "");
    transportHeaders.put(APIMgtGatewayConstants.AUTHORIZATION, "gsu64r874tcin7ry8oe");
    messageContext.setProperty(RESTConstants.REST_FULL_REQUEST_PATH, "");
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    axis2MsgCntxt.setProperty(APIMgtGatewayConstants.REQUEST_RECEIVED_TIME, null);
    Assert.assertFalse(apiAuthenticationHandler.handleRequest(messageContext));

    Mockito.when(messageContext.isDoingGET()).thenReturn(true);

    Assert.assertFalse(apiAuthenticationHandler.handleRequest(messageContext));

    Assert.assertTrue(apiAuthenticationHandler.isAnalyticsEnabled());

}
 
Example #23
Source File: APIAuthenticationHandlerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testDestroy() {
    APIAuthenticationHandler apiAuthenticationHandler = new APIAuthenticationHandler();
    apiAuthenticationHandler.destroy();
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    SynapseConfiguration synapseConfiguration = Mockito.mock(SynapseConfiguration.class);
    AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class);
    Mockito.when(synapseEnvironment.getSynapseConfiguration()).thenReturn(synapseConfiguration);
    Mockito.when(synapseConfiguration.getAxisConfiguration()).thenReturn(axisConfiguration);
    PowerMockito.mockStatic(Util.class);
    PowerMockito.when(Util.getTenantDomain()).thenReturn("carbon.super");
    apiAuthenticationHandler.init(synapseEnvironment);
    apiAuthenticationHandler.destroy();
}
 
Example #24
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testMsgThrottleOutWhenProductionHardThrottlingLimitsThrottled() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
            accessInformation);
    throttleHandler.setProductionMaxCount("100");
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    throttleHandler.init(synapseEnvironment);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    authenticationContext.setStopOnQuotaReach(false);
    authenticationContext.setKeyType("PRODUCTION");
    authenticationContext.setSpikeArrestLimit(0);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    matchingConditions.add(conditionGroupDTO);
    Mockito.when(accessInformation.isAccessAllowed()).thenReturn(false);

    //Should discontinue message flow if PRODUCTION hard throttling limits are exceeded
    Assert.assertFalse(throttleHandler.handleRequest(messageContext));
}
 
Example #25
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
    public void testMsgThrottleOutWhenSandBoxHardThrottlingLimitsThrottled() {
        ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

        ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
                accessInformation);
        throttleHandler.setSandboxMaxCount("100");
        SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
        throttleHandler.init(synapseEnvironment);
        MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
        messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
        ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
                .MessageContext.TRANSPORT_HEADERS);
        AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
                (API_AUTH_CONTEXT);
        authenticationContext.setApiTier(throttlingTier);
        authenticationContext.setStopOnQuotaReach(false);
        authenticationContext.setKeyType("SANDBOX");
        authenticationContext.setSpikeArrestLimit(0);
        messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

        verbInfo.setConditionGroups(conditionGroupDTOs);
        ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
        matchingConditions.add(conditionGroupDTO);
        String subscriptionLevelThrottleKey = authenticationContext.getApplicationId() + ":" + apiContext + ":"
                + apiVersion;
        String applicationLevelThrottleKey = authenticationContext.getApplicationId() + ":" + authenticationContext
                .getUsername();
        String combinedResourceLevelThrottleKey = resourceLevelThrottleKey + conditionGroupDTO.getConditionGroupId();
//        Mockito.when(throttleDataHolder.isThrottled(combinedResourceLevelThrottleKey)).thenReturn(false);
//        Mockito.when(throttleDataHolder.isThrottled(subscriptionLevelThrottleKey)).thenReturn(false);
//        Mockito.when(throttleDataHolder.isThrottled(applicationLevelThrottleKey)).thenReturn(false);
//        Mockito.when(throttleDataHolder.isKeyTemplatesPresent()).thenReturn(false);
//        Mockito.when(accessInformation.isAccessAllowed()).thenReturn(false);

        //Should discontinue message flow if SANDBOX hard throttling limits are exceeded
        Assert.assertFalse(throttleHandler.handleRequest(messageContext));
    }
 
Example #26
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testMsgThrottleOutWhenHardThrottlingFailedWithThrottleException() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
            accessInformation);
    throttleHandler.setProductionMaxCount("100");
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    throttleHandler.init(synapseEnvironment);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    authenticationContext.setKeyType("SANDBOX");
    authenticationContext.setSpikeArrestLimit(0);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    matchingConditions.add(conditionGroupDTO);


    //Throw ThrottleException while retrieving access information
    Mockito.doThrow(ThrottleException.class).when(accessInformation).isAccessAllowed();
    //Should discontinue message flow, when an exception is thrown during hard limit throttling information
    //process time
    Assert.assertFalse(throttleHandler.handleRequest(messageContext));
}
 
Example #27
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testMsgThrottleOutWhenCustomThrottlingLimitExceeded() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
            accessInformation);
    throttleHandler.setProductionMaxCount("100");
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    throttleHandler.init(synapseEnvironment);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    authenticationContext.setSpikeArrestLimit(0);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    Mockito.when(accessInformation.isAccessAllowed()).thenReturn(false);
    matchingConditions.add(conditionGroupDTO);
    throttleDataHolder.addKeyTemplate("$user", "$user");
    throttleDataHolder.addKeyTemplate("testKeyTemplate", "testKeyTemplateValue");
    throttleDataHolder.addThrottleData("testKeyTemplate", System.currentTimeMillis() + 10000);
    Assert.assertFalse(throttleHandler.handleRequest(messageContext));
    throttleDataHolder.removeKeyTemplate("testKeyTemplate");
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
 
Example #28
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testMsgThrottleOutWhenHittingSubscriptionLevelSpike() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();

    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
            accessInformation);
    throttleHandler.setSandboxMaxCount("100");
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    throttleHandler.init(synapseEnvironment);

    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    authenticationContext.setKeyType("SANDBOX");
    authenticationContext.setSpikeArrestLimit(100);
    authenticationContext.setStopOnQuotaReach(true);

    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    matchingConditions.add(conditionGroupDTO);
    throttleDataHolder.addKeyTemplate("$user", "$user");
    Mockito.when(accessInformation.isAccessAllowed()).thenReturn(false);
    Assert.assertFalse(throttleHandler.handleRequest(messageContext));
}
 
Example #29
Source File: ThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckForStaledThrottleData() {
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    ServiceReferenceHolder.getInstance().setThrottleDataPublisher(new ThrottleDataPublisher());
    ThrottleHandler throttleHandler = new ThrottlingHandlerWrapper(timer, throttleDataHolder, throttleEvaluator,
            accessInformation);
    throttleHandler.setProductionMaxCount("100");
    SynapseEnvironment synapseEnvironment = Mockito.mock(SynapseEnvironment.class);
    throttleHandler.init(synapseEnvironment);
    MessageContext messageContext = TestUtils.getMessageContextWithAuthContext(apiContext, apiVersion);
    messageContext.setProperty(VERB_INFO_DTO, verbInfoDTO);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty(org.apache.axis2.context
            .MessageContext.TRANSPORT_HEADERS);
    AuthenticationContext authenticationContext = (AuthenticationContext) messageContext.getProperty
            (API_AUTH_CONTEXT);
    authenticationContext.setApiTier(throttlingTier);
    authenticationContext.setSpikeArrestLimit(0);
    messageContext.setProperty(API_AUTH_CONTEXT, authenticationContext);

    verbInfo.setConditionGroups(conditionGroupDTOs);
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>();
    Mockito.when(accessInformation.isAccessAllowed()).thenReturn(false);
    matchingConditions.add(conditionGroupDTO);
    throttleDataHolder.addKeyTemplate("testKeyTemplate", "testKeyTemplateValue");
    throttleDataHolder.addThrottleData("testKeyTemplate", System.currentTimeMillis() - 10000);
    Assert.assertTrue(throttleHandler.handleRequest(messageContext));
}
 
Example #30
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public void init(SynapseEnvironment synapseEnvironment) {
    super.init(synapseEnvironment);

    LoadBalanceAlgorithm algorithm = LoadBalanceAlgorithmFactory.createAlgorithm(algorithmClassName);
    requestDelegator = new RequestDelegator(algorithm);
    synapseEnvironment.getSynapseConfiguration().setProperty(SynapseConstants.PROP_SAL_ENDPOINT_DEFAULT_SESSION_TIMEOUT, String.valueOf(sessionTimeout));
    setDispatcher(new HttpSessionDispatcher());
}