org.apache.synapse.SynapseConstants Java Examples

The following examples show how to use org.apache.synapse.SynapseConstants. 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: VaultLookupFunction.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the string value of the property which is get from the
 * corresponding context to the provided scope .
 * vault-lookup('xxx')
 * 
 * @param context
 *            the context at the point in the expression when the function
 *            is called
 * @param args
 *            arguments of the functions
 * @return The string value of a property
 * @throws FunctionCallException
 */
@Override
public Object call(Context context, List args) throws FunctionCallException {

	boolean traceOn = synCtx.getTracingState() == SynapseConstants.TRACING_ON;

	boolean traceOrDebugOn = traceOn || log.isDebugEnabled();

	if (args == null || args.size() == 0) {
		if (traceOrDebugOn) {
			traceOrDebug(traceOn, "vault value for lookup is not specified");
		}
		return NULL_STRING;

	}

	String argOne = StringFunction.evaluate(args.get(0), context.getNavigator());
	SecureVaultLookupHandler mediationSecurity;
	try {
		mediationSecurity = SecureVaultLookupHandlerImpl.getDefaultSecurityService();
		return mediationSecurity.evaluate(argOne, getSecretSourceInfo(args), synCtx);
	} catch (Exception msg) {
		throw new FunctionCallException(msg);
	}

}
 
Example #2
Source File: TestKeyAuthenticator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private void handleAuthenticationError(MessageContext mc) {
    mc.setProperty(SynapseConstants.ERROR_CODE, "401");
    mc.setProperty(SynapseConstants.ERROR_MESSAGE, "Authorize error");
    mc.setProperty(SynapseConstants.ERROR_EXCEPTION, "Either test token is missing or found an invalid test token");

    Mediator sequence = mc.getSequence(APISecurityConstants.API_AUTH_FAILURE_HANDLER);

    mc.setProperty(APIMgtGatewayConstants.HTTP_RESPONSE_STATUS_CODE, HttpStatus.SC_UNAUTHORIZED);
    // Invoke the custom error handler specified by the user
    if (sequence != null && !sequence.mediate(mc)) {
        // If needed user should be able to prevent the rest of the fault handling
        // logic from getting executed
        return;
    }
    sendFault(mc, HttpStatus.SC_UNAUTHORIZED);
}
 
Example #3
Source File: MetricHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Start the timers to observe request latency.
 *
 * @param synCtx           The Synapse Message Context
 * @param serviceName      The proxy/api/inbound endpoint name
 * @param serviceType      The service type (proxy/api/inbound endpoint)
 * @param apiInvocationUrl The api invocation url
 */
private void startTimers(MessageContext synCtx, String serviceName, String serviceType, String apiInvocationUrl) {
    switch (serviceType) {
        case SynapseConstants.PROXY_SERVICE_TYPE:
            synCtx.setProperty(MetricConstants.PROXY_LATENCY_TIMER,
                    metricReporterInstance.getTimer(MetricConstants.PROXY_LATENCY_SECONDS,
                            new String[]{serviceName, serviceType}));
            break;
        case MetricConstants.INBOUND_ENDPOINT:
            synCtx.setProperty(MetricConstants.INBOUND_ENDPOINT_LATENCY_TIMER,
                    metricReporterInstance.getTimer(MetricConstants.INBOUND_ENDPOINT_LATENCY_SECONDS,
                            new String[]{serviceName, serviceType}));
            break;
        case SynapseConstants.FAIL_SAFE_MODE_API:
            synCtx.setProperty(MetricConstants.API_LATENCY_TIMER,
                    metricReporterInstance.getTimer(MetricConstants.API_LATENCY_SECONDS,
                            new String[]{serviceName, serviceType, apiInvocationUrl}));
            break;
        default:
            log.error("No proper service type found");
            break;
    }
}
 
Example #4
Source File: MetricHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleResponseOutFlow(MessageContext synCtx) {
    if (null != synCtx.getProperty(SynapseConstants.PROXY_SERVICE)) {
        stopTimers(synCtx.getProperty(MetricConstants.PROXY_LATENCY_TIMER), synCtx);
    } else {
        serviceInvokePort = getServiceInvokePort(synCtx);
        if (null != synCtx.getProperty(SynapseConstants.IS_INBOUND) &&
                (serviceInvokePort != internalHttpApiPort)) {
            stopTimers(synCtx.
                    getProperty(MetricConstants.INBOUND_ENDPOINT_LATENCY_TIMER), synCtx);
        }
        if (serviceInvokePort != internalHttpApiPort) {
            stopTimers(synCtx.getProperty(MetricConstants.API_LATENCY_TIMER), synCtx);
            synCtx.setProperty(RESTConstants.IS_PROMETHEUS_ENGAGED, true);
        }
    }
    return true;
}
 
Example #5
Source File: CarbonSynapseController.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public SynapseConfiguration createSynapseConfiguration() {

        Properties properties = SynapsePropertiesLoader.loadSynapseProperties();

        if (serverConfigurationInformation.getResolveRoot() != null) {
            properties.put(SynapseConstants.RESOLVE_ROOT,
                    serverConfigurationInformation.getResolveRoot());
        }

        if (serverConfigurationInformation.getSynapseHome() != null) {
            properties.put(SynapseConstants.SYNAPSE_HOME,
                    serverConfigurationInformation.getSynapseHome());
        }

        //TODO load synapse config from the file
        // Load the synapse configuration from the file system
        log.debug("Loading the mediation configuration from the file system");
        return super.createSynapseConfiguration();
    }
 
Example #6
Source File: HL7MessageUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public static MessageContext createErrorMessageContext(String rawMessage, Exception errorMsg,
                                                       InboundProcessorParams params)
        throws AxisFault, HL7Exception {
    MessageContext synCtx = createSynapseMessageContext(
            params.getProperties().getProperty(MLLPConstants.HL7_INBOUND_TENANT_DOMAIN));

    if (params.getProperties().getProperty(Axis2HL7Constants.HL7_VALIDATION_PASSED) != null) {
        synCtx.setProperty(Axis2HL7Constants.HL7_VALIDATION_PASSED,
                           params.getProperties().getProperty(Axis2HL7Constants.HL7_VALIDATION_PASSED));
    }

    try {
        synCtx.setProperty(SynapseConstants.ERROR_CODE, SynapseConstants.RCV_IO_ERROR_RECEIVING);
        synCtx.setProperty(SynapseConstants.ERROR_MESSAGE, errorMsg.getMessage());
        synCtx.setProperty(SynapseConstants.ERROR_DETAIL,
                           (errorMsg.getCause() == null ? "null" : errorMsg.getCause().getMessage()));
        synCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, errorMsg);
        synCtx.setEnvelope(createErrorEnvelope(synCtx, rawMessage, errorMsg.getMessage(), params));
    } catch (Exception e) {
        throw new HL7Exception(e);
    }

    return synCtx;
}
 
Example #7
Source File: APIMgtFaultHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void mediate() throws Exception {
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIMgtFaultHandler apiMgtFaultHandler = new APIMgtFaultHandlerWrapper(apiMgtUsageDataPublisher, true, false);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty("REST_FULL_REQUEST_PATH")).thenReturn("/abc/1.0.0/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.REQUEST_START_TIME)).thenReturn("12345678");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY)).thenReturn("abc-def-ghi");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONTEXT)).thenReturn("/abc/1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_VERSION)).thenReturn("1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API)).thenReturn("api1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.RESOURCE)).thenReturn("/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.VERSION)).thenReturn("1.0.0");
    Mockito.when((messageContext.getProperty(SynapseConstants.ERROR_CODE))).thenReturn("404");
    Mockito.when(messageContext.getProperty(SynapseConstants.ERROR_MESSAGE)).thenReturn("not found");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.USER_ID)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME)).thenReturn("127.0.0.1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_PUBLISHER)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_NAME)).thenReturn("App1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_ID)).thenReturn("1");
    Mockito.when(messageContext.getProperty(SynapseConstants.TRANSPORT_IN_NAME)).thenReturn("https");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--api1-1.0.0");
    apiMgtFaultHandler.mediate(messageContext);
}
 
Example #8
Source File: APIMgtFaultHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void mediate1() throws Exception {
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIMgtFaultHandler apiMgtFaultHandler = new APIMgtFaultHandlerWrapper(apiMgtUsageDataPublisher, true, false);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty("REST_FULL_REQUEST_PATH")).thenReturn("/abc/1.0.0/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.REQUEST_START_TIME)).thenReturn("12345678");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY)).thenReturn("abc-def-ghi");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONTEXT)).thenReturn("/abc/1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_VERSION)).thenReturn("1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API)).thenReturn("api1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.RESOURCE)).thenReturn("/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.VERSION)).thenReturn("1.0.0");
    Mockito.when((messageContext.getProperty(SynapseConstants.ERROR_CODE))).thenReturn("404");
    Mockito.when(messageContext.getProperty(SynapseConstants.ERROR_MESSAGE)).thenReturn("not found");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.USER_ID)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME)).thenReturn("127.0.0.1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_NAME)).thenReturn("App1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_ID)).thenReturn("1");
    Mockito.when(messageContext.getProperty(SynapseConstants.TRANSPORT_IN_NAME)).thenReturn("https");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--api1-1.0.0");
    apiMgtFaultHandler.mediate(messageContext);
}
 
Example #9
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 #10
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private void prepareEndPointSequence(MessageContext synCtx, Endpoint endpoint) {

        Object o = synCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_ENDPOINT_LIST);
        List<Endpoint> endpointList;
        if (o instanceof List) {
            endpointList = (List<Endpoint>) o;
            endpointList.add(this);

        } else {
            // this is the first endpoint in the hierarchy. so create the queue and
            // insert this as the first element.
            endpointList = new ArrayList<Endpoint>();
            endpointList.add(this);
            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_ENDPOINT_LIST, endpointList);
        }

        // if the next endpoint is not a session affinity one, endpoint sequence ends
        // here. but we have to add the next endpoint to the list.
        if (!(endpoint instanceof TenantAwareLoadBalanceEndpoint)) {
            endpointList.add(endpoint);
            // Clearing out if there any any session information with current message
            if (dispatcher.isServerInitiatedSession()) {
                dispatcher.removeSessionID(synCtx);
            }
        }
    }
 
Example #11
Source File: TestMessageContext.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public Mediator getMainSequence() {
    Object o = localEntries.get(SynapseConstants.MAIN_SEQUENCE_KEY);
    if (o != null && o instanceof Mediator) {
        return (Mediator) o;
    } else {
        Mediator main = getConfiguration().getMainSequence();
        localEntries.put(SynapseConstants.MAIN_SEQUENCE_KEY, main);
        return main;
    }
}
 
Example #12
Source File: TestMessageContext.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public Mediator getFaultSequence() {
    Object o = localEntries.get(SynapseConstants.FAULT_SEQUENCE_KEY);
    if (o != null && o instanceof Mediator) {
        return (Mediator) o;
    } else {
        Mediator fault = getConfiguration().getFaultSequence();
        localEntries.put(SynapseConstants.FAULT_SEQUENCE_KEY, fault);
        return fault;
    }
}
 
Example #13
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 #14
Source File: StartupAdminService.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public void addTaskDescription(TaskDescription taskDescription) {
	final Lock lock = getLock();
	try {
		lock.lock();
		validateTaskDescription(taskDescription);
		OMElement taskElement = TaskDescriptionSerializer
				.serializeTaskDescription(SynapseConstants.SYNAPSE_OMNAMESPACE, taskDescription);
		validateTaskElement(taskElement);

		StartupUtils.addStartup(taskElement, getSynapseConfiguration(), getSynapseEnvironment());
	} finally {
		lock.unlock();
	}
}
 
Example #15
Source File: ProxyLogHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public void handleLogAppenderSetter (MessageContext synCtx) {
    String proxyName = (String) synCtx.getProperty(SynapseConstants.PROXY_SERVICE);

    ProxyService proxyService;
    if (proxyName != null && (proxyService = synCtx.getConfiguration().getProxyService(proxyName)) != null ) {
        proxyService.setLogSetterValue();
    }
}
 
Example #16
Source File: LocalEntryResource.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the provided Entry to the json array provided.
 *
 * @param list  json array
 * @param entry Entry
 */
private void addLocalEntryToJsonList(Entry entry, JSONArray list) {

    // Escape local entries defined by the server
    String key = entry.getKey();
    if (SynapseConstants.SERVER_IP.equals(key) || SynapseConstants.SERVER_HOST.equals(key)) {
        return;
    }
    String entryType = getEntryType(entry);
    JSONObject entryObject = new JSONObject();
    entryObject.put(Constants.NAME, key);
    entryObject.put(TYPE_ATTRIBUTE, entryType);
    list.put(entryObject);

}
 
Example #17
Source File: AbstractServiceBusAdmin.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
protected ServerConfigurationInformation getServerConfigurationInformation() {
    Parameter p = getAxisConfig().getParameter(SynapseConstants.SYNAPSE_SERVER_CONFIG_INFO);
    if (p != null) {
        return (ServerConfigurationInformation) p.getValue();
    }
    return null;
}
 
Example #18
Source File: AbstractServiceBusAdmin.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
protected ServerContextInformation getServerContextInformation() {
    Parameter p = getAxisConfig().getParameter(SynapseConstants.SYNAPSE_SERVER_CTX_INFO);
    if (p != null) {
        return (ServerContextInformation) p.getValue();
    }
    return null;
}
 
Example #19
Source File: Utils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method used to send the response back from the request.
 *
 * @param messageContext messageContext of the request
 * @param status         HTTP Status to return from the response
 */
public static void send(MessageContext messageContext, int status) {
    org.apache.axis2.context.MessageContext axis2MC =
            ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    axis2MC.setProperty(NhttpConstants.HTTP_SC, status);
    messageContext.setResponse(true);
    messageContext.setProperty(SynapseConstants.RESPONSE, "true");
    messageContext.setTo(null);
    axis2MC.removeProperty(Constants.Configuration.CONTENT_TYPE);
    Axis2Sender.sendBack(messageContext);
}
 
Example #20
Source File: APIMgtResponseHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void mediate() throws Exception {
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIManagerAnalyticsConfiguration apiManagerAnalyticsConfiguration = Mockito.mock
            (APIManagerAnalyticsConfiguration.class);
    Mockito.when(apiManagerAnalyticsConfiguration.isBuildMsg()).thenReturn(false);
    APIMgtResponseHandler apiMgtResponseHandler = new APIMgtResponseHandlerWrapper(apiMgtUsageDataPublisher,
            true, false, apiManagerAnalyticsConfiguration);
    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);
    Mockito.when(axis2MsgCntxt.getProperty(SynapseConstants.HTTP_SC)).thenReturn(200);
    Mockito.when(messageContext.getProperty("REST_FULL_REQUEST_PATH")).thenReturn("/abc/1.0.0/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.REQUEST_START_TIME)).thenReturn("12345678");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY)).thenReturn("abc-def-ghi");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONTEXT)).thenReturn("/abc/1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_VERSION)).thenReturn("1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API)).thenReturn("api1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.RESOURCE)).thenReturn("/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.VERSION)).thenReturn("1.0.0");
    Mockito.when((messageContext.getProperty(SynapseConstants.ERROR_CODE))).thenReturn("404");
    Mockito.when(messageContext.getProperty(SynapseConstants.ERROR_MESSAGE)).thenReturn("not found");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.USER_ID)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME)).thenReturn("127.0.0.1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_PUBLISHER)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_NAME)).thenReturn("App1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_ID)).thenReturn("1");
    Mockito.when(messageContext.getProperty(SynapseConstants.TRANSPORT_IN_NAME)).thenReturn("https");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--api1-1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.REST_URL_PREFIX)).thenReturn("https://localhost");
    apiMgtResponseHandler.mediate(messageContext);
}
 
Example #21
Source File: APIMgtResponseHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void mediateWithContentLength() throws Exception {
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIManagerAnalyticsConfiguration apiManagerAnalyticsConfiguration = Mockito.mock
            (APIManagerAnalyticsConfiguration.class);
    Mockito.when(apiManagerAnalyticsConfiguration.isBuildMsg()).thenReturn(true);
    APIMgtResponseHandler apiMgtResponseHandler = new APIMgtResponseHandlerWrapper(apiMgtUsageDataPublisher,
            true, false, apiManagerAnalyticsConfiguration);
    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);
    Mockito.when(axis2MsgCntxt.getProperty(SynapseConstants.HTTP_SC)).thenReturn(200);
    Map headers = new HashMap();
    headers.put(HttpHeaders.CONTENT_LENGTH, "103");
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn
            (headers);
    Mockito.when(messageContext.getProperty("REST_FULL_REQUEST_PATH")).thenReturn("/abc/1.0.0/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.REQUEST_START_TIME)).thenReturn("12345678");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY)).thenReturn("abc-def-ghi");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONTEXT)).thenReturn("/abc/1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_VERSION)).thenReturn("1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API)).thenReturn("api1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.RESOURCE)).thenReturn("/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.VERSION)).thenReturn("1.0.0");
    Mockito.when((messageContext.getProperty(SynapseConstants.ERROR_CODE))).thenReturn("404");
    Mockito.when(messageContext.getProperty(SynapseConstants.ERROR_MESSAGE)).thenReturn("not found");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.USER_ID)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME)).thenReturn("127.0.0.1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_PUBLISHER)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_NAME)).thenReturn("App1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_ID)).thenReturn("1");
    Mockito.when(messageContext.getProperty(SynapseConstants.TRANSPORT_IN_NAME)).thenReturn("https");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--api1-1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.REST_URL_PREFIX)).thenReturn("https://localhost");
    apiMgtResponseHandler.mediate(messageContext);
}
 
Example #22
Source File: APIMgtResponseHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void mediateWithStartTimeNotSet() throws Exception {
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIManagerAnalyticsConfiguration apiManagerAnalyticsConfiguration = Mockito.mock
            (APIManagerAnalyticsConfiguration.class);
    Mockito.when(apiManagerAnalyticsConfiguration.isBuildMsg()).thenReturn(false);
    APIMgtResponseHandler apiMgtResponseHandler = new APIMgtResponseHandlerWrapper(apiMgtUsageDataPublisher,
            true, false, apiManagerAnalyticsConfiguration);
    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);
    Mockito.when(axis2MsgCntxt.getProperty(SynapseConstants.HTTP_SC)).thenReturn(200);
    Mockito.when(messageContext.getProperty("REST_FULL_REQUEST_PATH")).thenReturn("/abc/1.0.0/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY)).thenReturn("abc-def-ghi");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONTEXT)).thenReturn("/abc/1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_VERSION)).thenReturn("1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API)).thenReturn("api1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.RESOURCE)).thenReturn("/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.VERSION)).thenReturn("1.0.0");
    Mockito.when((messageContext.getProperty(SynapseConstants.ERROR_CODE))).thenReturn("404");
    Mockito.when(messageContext.getProperty(SynapseConstants.ERROR_MESSAGE)).thenReturn("not found");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.USER_ID)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME)).thenReturn("127.0.0.1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_PUBLISHER)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_NAME)).thenReturn("App1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_ID)).thenReturn("1");
    Mockito.when(messageContext.getProperty(SynapseConstants.TRANSPORT_IN_NAME)).thenReturn("https");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--api1-1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.REST_URL_PREFIX)).thenReturn("https://localhost");
    apiMgtResponseHandler.mediate(messageContext);
}
 
Example #23
Source File: APIMgtResponseHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void mediateWithStartTimeAndEndTime() throws Exception {
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIManagerAnalyticsConfiguration apiManagerAnalyticsConfiguration = Mockito.mock
            (APIManagerAnalyticsConfiguration.class);
    Mockito.when(apiManagerAnalyticsConfiguration.isBuildMsg()).thenReturn(false);
    APIMgtResponseHandler apiMgtResponseHandler = new APIMgtResponseHandlerWrapper(apiMgtUsageDataPublisher,
            true, false, apiManagerAnalyticsConfiguration);
    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);
    Mockito.when(axis2MsgCntxt.getProperty(SynapseConstants.HTTP_SC)).thenReturn(200);
    Mockito.when(messageContext.getProperty("REST_FULL_REQUEST_PATH")).thenReturn("/abc/1.0.0/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONSUMER_KEY)).thenReturn("abc-def-ghi");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.CONTEXT)).thenReturn("/abc/1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_VERSION)).thenReturn("1.0.0");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API)).thenReturn("api1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.RESOURCE)).thenReturn("/a");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.VERSION)).thenReturn("1.0.0");
    Mockito.when((messageContext.getProperty(SynapseConstants.ERROR_CODE))).thenReturn("404");
    Mockito.when(messageContext.getProperty(SynapseConstants.ERROR_MESSAGE)).thenReturn("not found");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.USER_ID)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.HOST_NAME)).thenReturn("127.0.0.1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.API_PUBLISHER)).thenReturn("admin");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_NAME)).thenReturn("App1");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.APPLICATION_ID)).thenReturn("1");
    Mockito.when(messageContext.getProperty(SynapseConstants.TRANSPORT_IN_NAME)).thenReturn("https");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API)).thenReturn("admin--api1-1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.REST_URL_PREFIX)).thenReturn("https://localhost");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.REQUEST_START_TIME)).thenReturn("10");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.BACKEND_REQUEST_START_TIME)).thenReturn("11");
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.BACKEND_REQUEST_END_TIME)).thenReturn(13);
    apiMgtResponseHandler.mediate(messageContext);
}
 
Example #24
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());
}
 
Example #25
Source File: WebSocketClientHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private org.apache.synapse.MessageContext getSynapseMessageContext(String tenantDomain) throws AxisFault {
    org.apache.synapse.MessageContext synCtx = createSynapseMessageContext(tenantDomain);
    if (responseSender != null) {
        synCtx.setProperty(SynapseConstants.IS_INBOUND, true);
        synCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, responseSender);
    }
    synCtx.setProperty(WebsocketConstants.WEBSOCKET_SUBSCRIBER_PATH, handshaker.uri().toString());
    return synCtx;
}
 
Example #26
Source File: PrometheusReporter.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Create the api related metrics.
 */
public void initializeApiMetrics() {
    String[] labels = {MetricConstants.SERVICE_NAME, MetricConstants.SERVICE_TYPE, MetricConstants.INVOCATION_URL};

    createMetrics(SynapseConstants.FAIL_SAFE_MODE_API, MetricConstants.COUNTER,
            MetricConstants.API_REQUEST_COUNT_TOTAL,
            "Total number of requests to an api", labels);
    createMetrics(SynapseConstants.FAIL_SAFE_MODE_API, MetricConstants.HISTOGRAM,
            MetricConstants.API_LATENCY_SECONDS,
            "Latency of requests to an api", labels);

    initializeApiErrorMetrics();
}
 
Example #27
Source File: RabbitMQInjectHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Determine the message builder to use, set the message payload to the message context and
 * inject the message.
 *
 * @param properties  the AMQP basic properties
 * @param body        the message body
 * @param inboundName Inbound Name
 * @return delivery status of the message
 */
public boolean onMessage(AMQP.BasicProperties properties, byte[] body, String inboundName) {
    org.apache.synapse.MessageContext msgCtx = createMessageContext();
    try {
        MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        RabbitMQUtils.buildMessage(properties, body, axis2MsgCtx);
        axis2MsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, RabbitMQUtils.getTransportHeaders(properties));

        if (seq != null) {
            if (log.isDebugEnabled()) {
                log.debug("injecting message to sequence : " + injectingSeq);
            }
            seq.setErrorHandler(onErrorSeq);
            msgCtx.setProperty(SynapseConstants.IS_INBOUND, true);
            msgCtx.setProperty(SynapseConstants.INBOUND_ENDPOINT_NAME, inboundName);
            msgCtx.setProperty(SynapseConstants.ARTIFACT_NAME,
                               SynapseConstants.FAIL_SAFE_MODE_INBOUND_ENDPOINT + inboundName);
            synapseEnvironment.injectInbound(msgCtx, seq, sequential);
        } else {
            log.error("Sequence: " + injectingSeq + " not found");
        }

        Object rollbackProperty = msgCtx.getProperty(RabbitMQConstants.SET_ROLLBACK_ONLY);
        if ((rollbackProperty instanceof Boolean && ((Boolean) rollbackProperty)) ||
            (rollbackProperty instanceof String && Boolean.parseBoolean((String) rollbackProperty))) {
            return false;
        }

    } catch (AxisFault axisFault) {
        log.error("Error when trying to read incoming message ...", axisFault);
        return false;
    }
    return true;
}
 
Example #28
Source File: PrometheusReporter.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Create the proxy services related metrics.
 */
public void initializeProxyMetrics() {
    String[] labels = {MetricConstants.SERVICE_NAME, MetricConstants.SERVICE_TYPE};

    createMetrics(SynapseConstants.PROXY_SERVICE_TYPE, MetricConstants.COUNTER,
            MetricConstants.PROXY_REQUEST_COUNT_TOTAL,
            "Total number of requests to a proxy service", labels);
    createMetrics(SynapseConstants.PROXY_SERVICE_TYPE, MetricConstants.HISTOGRAM,
            MetricConstants.PROXY_LATENCY_SECONDS,
            "Latency of requests to a proxy service", labels);

    initializeProxyErrorMetrics();
}
 
Example #29
Source File: StartupAdminService.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public void editTaskDescription(TaskDescription taskDescription) {
	final Lock lock = getLock();
	try {
		lock.lock();
		validateTaskDescription(taskDescription);
		OMElement taskElement = TaskDescriptionSerializer
				.serializeTaskDescription(SynapseConstants.SYNAPSE_OMNAMESPACE, taskDescription);
		validateTaskElement(taskElement);

		StartupUtils.updateStartup(taskDescription.getName(), taskElement, getSynapseConfiguration(),
		                           getSynapseEnvironment());
	} finally {
		lock.unlock();
	}
}
 
Example #30
Source File: InboundWebsocketSourceHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public org.apache.synapse.MessageContext getSynapseMessageContext(String tenantDomain) throws AxisFault {
    MessageContext synCtx = createSynapseMessageContext(tenantDomain);
    synCtx.setProperty(SynapseConstants.IS_INBOUND, true);
    ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty(SynapseConstants.IS_INBOUND, true);
    synCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, responseSender);
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, responseSender);
    synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_SOURCE_HANDLER_CONTEXT,
                       wrappedContext.getChannelHandlerContext());
    ((Axis2MessageContext) synCtx).getAxis2MessageContext()
            .setProperty(InboundWebsocketConstants.WEBSOCKET_SOURCE_HANDLER_CONTEXT,
                         wrappedContext.getChannelHandlerContext());
    if (outflowDispatchSequence != null) {
        synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_SEQUENCE, outflowDispatchSequence);
        ((Axis2MessageContext) synCtx).getAxis2MessageContext()
                .setProperty(InboundWebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_SEQUENCE,
                             outflowDispatchSequence);
    }
    if (outflowErrorSequence != null) {
        synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_FAULT_SEQUENCE,
                           outflowErrorSequence);
        ((Axis2MessageContext) synCtx).getAxis2MessageContext()
                .setProperty(InboundWebsocketConstants.WEBSOCKET_OUTFLOW_DISPATCH_FAULT_SEQUENCE,
                             outflowErrorSequence);
    }
    synCtx.setProperty(InboundWebsocketConstants.WEBSOCKET_SUBSCRIBER_PATH, subscriberPath.toString());
    return synCtx;
}