use of org.apache.synapse.endpoints.Endpoint in project wso2-synapse by wso2.
the class ClassEndpointFactory method createEndpoint.
protected Endpoint createEndpoint(OMElement epConfig, boolean anonymousEndpoint, Properties properties) {
ClassEndpoint clazzEndpoint = new ClassEndpoint();
OMAttribute endpointName = epConfig.getAttribute(new QName(XMLConfigConstants.NULL_NAMESPACE, "name"));
if (endpointName != null) {
clazzEndpoint.setName(endpointName.getAttributeValue());
}
OMElement classElement = epConfig.getFirstChildWithName(CLASS_QNAME);
if (classElement == null) {
return null;
}
String nameAttr = classElement.getAttributeValue(NAME_QNAME);
if (nameAttr == null) {
return null;
}
Endpoint endpoint = null;
try {
Class clazz = Class.forName(nameAttr);
endpoint = (Endpoint) clazz.newInstance();
for (Iterator iter = classElement.getChildrenWithName(PARAMETER_QNAME); iter.hasNext(); ) {
OMElement paramEle = (OMElement) iter.next();
setParameter(endpoint, paramEle, clazzEndpoint);
}
} catch (Exception e) {
handleException("Cannot create class endpoint", e);
}
clazzEndpoint.setClassEndpoint(endpoint);
return clazzEndpoint;
}
use of org.apache.synapse.endpoints.Endpoint in project wso2-synapse by wso2.
the class ProxyServiceSerializer method serializeProxy.
public static OMElement serializeProxy(OMElement parent, ProxyService service) {
OMElement proxy = fac.createOMElement("proxy", synNS);
if (service.getName() != null) {
proxy.addAttribute(fac.createOMAttribute("name", nullNS, service.getName()));
} else {
handleException("Invalid proxy service. Service name is required");
}
String descriptionStr = service.getDescription();
if (descriptionStr != null) {
OMElement description = fac.createOMElement("description", synNS);
description.addChild(fac.createOMText(descriptionStr));
proxy.addChild(description);
}
ArrayList transports = service.getTransports();
if (transports != null && !transports.isEmpty()) {
String transportStr = "" + transports.get(0);
for (int i = 1; i < transports.size(); i++) {
transportStr = transportStr.concat(" " + transports.get(i));
}
proxy.addAttribute(fac.createOMAttribute("transports", nullNS, transportStr));
}
if (service.getServiceGroup() != null) {
proxy.addAttribute(fac.createOMAttribute("serviceGroup", nullNS, service.getServiceGroup()));
}
List pinnedServers = service.getPinnedServers();
if (pinnedServers != null && !pinnedServers.isEmpty()) {
String pinnedServersStr = "" + pinnedServers.get(0);
for (int i = 1; i < pinnedServers.size(); i++) {
pinnedServersStr = pinnedServersStr.concat(" " + pinnedServers.get(i));
}
proxy.addAttribute(fac.createOMAttribute("pinnedServers", nullNS, pinnedServersStr));
}
if (service.isStartOnLoad()) {
proxy.addAttribute(fac.createOMAttribute("startOnLoad", nullNS, "true"));
} else {
proxy.addAttribute(fac.createOMAttribute("startOnLoad", nullNS, "false"));
}
String endpoint = service.getTargetEndpoint();
OMElement target = fac.createOMElement("target", synNS);
Endpoint inLineEndpoint = service.getTargetInLineEndpoint();
if (endpoint != null) {
target.addAttribute(fac.createOMAttribute("endpoint", nullNS, endpoint));
proxy.addChild(target);
} else if (inLineEndpoint != null) {
OMElement epElement = EndpointSerializer.getElementFromEndpoint(inLineEndpoint);
target.addChild(epElement);
proxy.addChild(target);
}
String inSeq = service.getTargetInSequence();
String outSeq = service.getTargetOutSequence();
String faultSeq = service.getTargetFaultSequence();
SequenceMediatorSerializer serializer = new SequenceMediatorSerializer();
if (inSeq != null) {
target.addAttribute(fac.createOMAttribute("inSequence", nullNS, inSeq));
proxy.addChild(target);
} else {
SequenceMediator inLineInSeq = service.getTargetInLineInSequence();
if (inLineInSeq != null) {
OMElement inSeqElement = serializer.serializeAnonymousSequence(null, inLineInSeq);
inSeqElement.setLocalName("inSequence");
target.addChild(inSeqElement);
proxy.addChild(target);
}
}
if (outSeq != null) {
target.addAttribute(fac.createOMAttribute("outSequence", nullNS, outSeq));
proxy.addChild(target);
} else {
SequenceMediator inLineOutSeq = service.getTargetInLineOutSequence();
if (inLineOutSeq != null) {
OMElement outSeqElement = serializer.serializeAnonymousSequence(null, inLineOutSeq);
outSeqElement.setLocalName("outSequence");
target.addChild(outSeqElement);
proxy.addChild(target);
}
}
if (faultSeq != null) {
target.addAttribute(fac.createOMAttribute("faultSequence", nullNS, faultSeq));
proxy.addChild(target);
} else {
SequenceMediator inLineFaultSeq = service.getTargetInLineFaultSequence();
if (inLineFaultSeq != null) {
OMElement faultSeqElement = serializer.serializeAnonymousSequence(null, inLineFaultSeq);
faultSeqElement.setLocalName("faultSequence");
target.addChild(faultSeqElement);
proxy.addChild(target);
}
}
String wsdlKey = service.getWSDLKey();
String wsdlEndpoint = service.getPublishWSDLEndpoint();
String preservePolicy = service.getPreservePolicy();
URI wsdlUri = service.getWsdlURI();
Object inLineWSDL = service.getInLineWSDL();
if (wsdlKey != null || wsdlUri != null || inLineWSDL != null || wsdlEndpoint != null) {
OMElement wsdl = fac.createOMElement("publishWSDL", synNS);
if (wsdlEndpoint != null) {
wsdl.addAttribute(fac.createOMAttribute("endpoint", nullNS, wsdlEndpoint));
} else if (wsdlKey != null) {
wsdl.addAttribute(fac.createOMAttribute("key", nullNS, wsdlKey));
} else if (inLineWSDL != null) {
wsdl.addChild((OMNode) inLineWSDL);
} else if (wsdlUri != null) {
wsdl.addAttribute(fac.createOMAttribute("uri", nullNS, wsdlUri.toString()));
}
if (preservePolicy != null) {
wsdl.addAttribute(fac.createOMAttribute("preservePolicy", nullNS, preservePolicy));
}
ResourceMapSerializer.serializeResourceMap(wsdl, service.getResourceMap());
proxy.addChild(wsdl);
}
for (PolicyInfo pi : service.getPolicies()) {
OMElement policy = fac.createOMElement("policy", synNS);
if (pi.getPolicyKey() != null) {
policy.addAttribute(fac.createOMAttribute("key", nullNS, pi.getPolicyKey()));
} else {
handleException("Policy without a key has been found");
}
if (pi.getOperation() != null) {
policy.addAttribute(fac.createOMAttribute("operationName", nullNS, pi.getOperation().getLocalPart()));
if (pi.getOperation().getNamespaceURI() != null) {
policy.addAttribute(fac.createOMAttribute("operationNamespace", nullNS, pi.getOperation().getNamespaceURI()));
}
}
if (pi.getType() != 0) {
policy.addAttribute(fac.createOMAttribute("type", nullNS, pi.getMessageLable().toLowerCase()));
}
proxy.addChild(policy);
}
for (String propertyName : service.getParameterMap().keySet()) {
OMElement property = fac.createOMElement("parameter", synNS);
property.addAttribute(fac.createOMAttribute("name", nullNS, propertyName));
Object value = service.getParameterMap().get(propertyName);
if (value != null) {
if (value instanceof String) {
property.setText(((String) value).trim());
proxy.addChild(property);
} else if (value instanceof OMNode) {
property.addChild((OMNode) value);
proxy.addChild(property);
}
}
}
if (service.isWsAddrEnabled()) {
proxy.addChild(fac.createOMElement("enableAddressing", synNS));
}
if (service.isWsSecEnabled()) {
proxy.addChild(fac.createOMElement("enableSec", synNS));
}
StatisticsConfigurable statisticsConfigurable = service.getAspectConfiguration();
if (statisticsConfigurable != null && statisticsConfigurable.isStatisticsEnable()) {
proxy.addAttribute(fac.createOMAttribute(XMLConfigConstants.STATISTICS_ATTRIB_NAME, nullNS, XMLConfigConstants.STATISTICS_ENABLE));
}
if (statisticsConfigurable != null && statisticsConfigurable.isTracingEnabled()) {
proxy.addAttribute(fac.createOMAttribute(XMLConfigConstants.TRACE_ATTRIB_NAME, nullNS, XMLConfigConstants.TRACE_ENABLE));
}
if (parent != null) {
parent.addChild(proxy);
}
return proxy;
}
use of org.apache.synapse.endpoints.Endpoint in project wso2-synapse by wso2.
the class ProxyService method buildAxisService.
/**
* Build the underlying Axis2 service from the Proxy service definition
*
* @param synCfg the Synapse configuration
* @param axisCfg the Axis2 configuration
* @return the Axis2 service for the Proxy
*/
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) {
auditInfo("Building Axis service for Proxy service : " + name);
if (pinnedServers != null && !pinnedServers.isEmpty()) {
Parameter param = axisCfg.getParameter(SynapseConstants.SYNAPSE_ENV);
if (param != null && param.getValue() instanceof SynapseEnvironment) {
SynapseEnvironment synEnv = (SynapseEnvironment) param.getValue();
String serverName = synEnv != null ? synEnv.getServerContextInformation().getServerConfigurationInformation().getServerName() : "localhost";
if (!pinnedServers.contains(serverName)) {
log.info("Server name " + serverName + " not in pinned servers list. " + "Not deploying Proxy service : " + name);
return null;
}
}
}
// get the wsdlElement as an OMElement
if (trace()) {
trace.info("Loading the WSDL : " + (publishWSDLEndpoint != null ? " endpoint = " + publishWSDLEndpoint : (wsdlKey != null ? " key = " + wsdlKey : (wsdlURI != null ? " URI = " + wsdlURI : " <Inlined>"))));
}
InputStream wsdlInputStream = null;
OMElement wsdlElement = null;
boolean wsdlFound = false;
String publishWSDL = null;
SynapseEnvironment synEnv = SynapseConfigUtils.getSynapseEnvironment(axisCfg);
String synapseHome = synEnv != null ? synEnv.getServerContextInformation().getServerConfigurationInformation().getSynapseHome() : "";
if (wsdlKey != null) {
synCfg.getEntryDefinition(wsdlKey);
Object keyObject = synCfg.getEntry(wsdlKey);
// start of fix for ESBJAVA-2641
if (keyObject == null) {
synCfg.removeEntry(wsdlKey);
}
// end of fix for ESBJAVA-2641
if (keyObject instanceof OMElement) {
wsdlElement = (OMElement) keyObject;
}
wsdlFound = true;
} else if (inLineWSDL != null) {
wsdlElement = (OMElement) inLineWSDL;
wsdlFound = true;
} else if (wsdlURI != null) {
try {
URL url = wsdlURI.toURL();
publishWSDL = url.toString();
OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL, synapseHome);
if (node instanceof OMElement) {
wsdlElement = (OMElement) node;
}
wsdlFound = true;
} catch (MalformedURLException e) {
handleException("Malformed URI for wsdl", e);
} catch (IOException e) {
// handleException("Error reading from wsdl URI", e);
boolean enablePublishWSDLSafeMode = false;
Map proxyParameters = this.getParameterMap();
if (!proxyParameters.isEmpty()) {
if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
enablePublishWSDLSafeMode = Boolean.parseBoolean(proxyParameters.get("enablePublishWSDLSafeMode").toString().toLowerCase());
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" + "</syn:parameter> to proxy service.");
}
handleException("Error reading from wsdl URI", e);
}
}
if (enablePublishWSDLSafeMode) {
// !!!Need to add a reload function... And display that the wsdl/service is offline!!!
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: true");
}
log.warn("Unable to load the WSDL for : " + name, e);
return null;
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: false");
}
handleException("Error reading from wsdl URI", e);
}
}
} else if (publishWSDLEndpoint != null) {
try {
URL url = null;
Endpoint ep = synCfg.getEndpoint(publishWSDLEndpoint);
if (ep == null) {
handleException("Unable to resolve WSDL url. " + publishWSDLEndpoint + " is null");
}
if (ep instanceof AddressEndpoint) {
url = new URL(((AddressEndpoint) (ep)).getDefinition().getAddress() + "?wsdl");
} else if (ep instanceof WSDLEndpoint) {
url = new URL(((WSDLEndpoint) (ep)).getWsdlURI());
} else {
handleException("Unable to resolve WSDL url. " + publishWSDLEndpoint + " is not a AddressEndpoint or WSDLEndpoint");
}
publishWSDL = url.toString();
OMNode node = SynapseConfigUtils.getOMElementFromURL(publishWSDL, synapseHome);
if (node instanceof OMElement) {
wsdlElement = (OMElement) node;
}
wsdlFound = true;
} catch (MalformedURLException e) {
handleException("Malformed URI for wsdl", e);
} catch (IOException e) {
// handleException("Error reading from wsdl URI", e);
boolean enablePublishWSDLSafeMode = false;
Map proxyParameters = this.getParameterMap();
if (!proxyParameters.isEmpty()) {
if (proxyParameters.containsKey("enablePublishWSDLSafeMode")) {
enablePublishWSDLSafeMode = Boolean.parseBoolean(proxyParameters.get("enablePublishWSDLSafeMode").toString().toLowerCase());
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("Please add <syn:parameter name=\"enableURISafeMode\">true" + "</syn:parameter> to proxy service.");
}
handleException("Error reading from wsdl URI " + publishWSDL, e);
}
}
if (enablePublishWSDLSafeMode) {
// !!!Need to add a reload function... And display that the wsdl/service is offline!!!
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: true");
}
log.warn("Unable to load the WSDL for : " + name, e);
return null;
} else {
if (trace()) {
trace.info("WSDL was unable to load for: " + publishWSDL);
trace.info("enableURISafeMode: false");
}
handleException("Error reading from wsdl URI " + publishWSDL, e);
}
}
} else {
// our SynapseDispatcher will properly dispatch to
if (trace())
trace.info("Did not find a WSDL. Assuming a POX or Legacy service");
axisService = new AxisService();
AxisOperation mediateOperation = new InOutAxisOperation(SynapseConstants.SYNAPSE_OPERATION_NAME);
// Set the names of the two messages so that Axis2 is able to produce a WSDL (see SYNAPSE-366):
mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE).setName("in");
mediateOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).setName("out");
axisService.addOperation(mediateOperation);
}
// if a WSDL was found
if (wsdlElement != null) {
OMNamespace wsdlNamespace = wsdlElement.getNamespace();
// if preservePolicy is set to 'false', remove the security policy content of publish wsdl
if (preservePolicy != null && preservePolicy.equals("false")) {
if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.equals(wsdlNamespace.getNamespaceURI())) {
removePolicyOfWSDL(wsdlElement);
}
}
// serialize and create an input stream to read WSDL
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (trace())
trace.info("Serializing wsdlElement found to build an Axis2 service");
wsdlElement.serialize(baos);
wsdlInputStream = new ByteArrayInputStream(baos.toByteArray());
} catch (XMLStreamException e) {
handleException("Error converting to a StreamSource", e);
}
if (wsdlInputStream != null) {
try {
// detect version of the WSDL 1.1 or 2.0
if (trace())
trace.info("WSDL Namespace is : " + wsdlNamespace.getNamespaceURI());
if (wsdlNamespace != null) {
WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null;
if (WSDL2Constants.WSDL_NAMESPACE.equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder = new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null);
} else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11.equals(wsdlNamespace.getNamespaceURI())) {
wsdlToAxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlInputStream);
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
if (wsdlToAxisServiceBuilder == null) {
throw new SynapseException("Could not get the WSDL to Axis Service Builder");
}
wsdlToAxisServiceBuilder.setBaseUri(wsdlURI != null ? wsdlURI.toString() : synapseHome);
if (trace()) {
trace.info("Setting up custom resolvers");
}
// load the UserDefined WSDLResolver and SchemaURIResolver implementations
if (synCfg.getProperty(SynapseConstants.SYNAPSE_WSDL_RESOLVER) != null && synCfg.getProperty(SynapseConstants.SYNAPSE_SCHEMA_RESOLVER) != null) {
setUserDefinedResourceResolvers(synCfg, wsdlInputStream, wsdlToAxisServiceBuilder);
} else {
if (resourceMap != null) {
// if the resource map is available use it
wsdlToAxisServiceBuilder.setCustomResolver(new CustomXmlSchemaURIResolver(resourceMap, synCfg));
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder) wsdlToAxisServiceBuilder).setCustomWSDLResolver(new CustomWSDLLocator(new InputSource(wsdlInputStream), wsdlURI != null ? wsdlURI.toString() : "", resourceMap, synCfg));
}
} else {
// if the resource map isn't available ,
// then each import URIs will be resolved using base URI
wsdlToAxisServiceBuilder.setCustomResolver(new CustomXmlSchemaURIResolver());
// Axis 2 also needs a WSDLLocator for WSDL 1.1 documents
if (wsdlToAxisServiceBuilder instanceof WSDL11ToAxisServiceBuilder) {
((WSDL11ToAxisServiceBuilder) wsdlToAxisServiceBuilder).setCustomWSDLResolver(new CustomWSDLLocator(new InputSource(wsdlInputStream), wsdlURI != null ? wsdlURI.toString() : ""));
}
}
}
if (trace()) {
trace.info("Populating Axis2 service using WSDL");
if (trace.isTraceEnabled()) {
trace.trace("WSDL : " + wsdlElement.toString());
}
}
axisService = wsdlToAxisServiceBuilder.populateService();
// this is to clear the bindings and ports already in the WSDL so that the
// service will generate the bindings on calling the printWSDL otherwise
// the WSDL which will be shown is same as the original WSDL except for the
// service name
axisService.getEndpoints().clear();
} else {
handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0");
}
} catch (AxisFault af) {
handleException("Error building service from WSDL", af);
} catch (IOException ioe) {
handleException("Error reading WSDL", ioe);
}
}
} else if (wsdlFound) {
handleException("Couldn't build the proxy service : " + name + ". Unable to locate the specified WSDL to build the service");
}
// default Service destination
if (axisService == null) {
throw new SynapseException("Could not create a proxy service");
}
axisService.setName(name);
if (description != null) {
axisService.setDocumentation(description);
}
// Setting file path for axis2 service
if (filePath != null) {
axisService.setFileName(filePath);
}
// destination
if (transports == null || transports.size() == 0) {
// default to all transports using service name as destination
} else {
if (trace())
trace.info("Exposing transports : " + transports);
axisService.setExposedTransports(transports);
}
// process parameters
if (trace() && parameters.size() > 0) {
trace.info("Setting service parameters : " + parameters);
}
for (Object o : parameters.keySet()) {
String name = (String) o;
Object value = parameters.get(name);
Parameter p = new Parameter();
p.setName(name);
p.setValue(value);
try {
axisService.addParameter(p);
} catch (AxisFault af) {
handleException("Error setting parameter : " + name + "" + "to proxy service as a Parameter", af);
}
}
if (JavaUtils.isTrueExplicitly(axisService.getParameterValue(ABSOLUTE_SCHEMA_URL_PARAM))) {
axisService.setCustomSchemaNamePrefix("");
}
if (JavaUtils.isTrueExplicitly(axisService.getParameterValue(ABSOLUTE_PROXY_SCHEMA_URL_PARAM))) {
axisService.setCustomSchemaNamePrefix("fullschemaurl");
}
if (JavaUtils.isTrueExplicitly(axisService.getParameterValue("disableOperationValidation"))) {
try {
AxisOperation defaultOp = processOperationValidation(axisService);
// proxyServiceGroup.setParent(axisCfg);
} catch (AxisFault axisFault) {
// ignore
}
}
boolean isNoSecPolicy = false;
if (!policies.isEmpty()) {
for (PolicyInfo pi : policies) {
Policy policy = getPolicyFromKey(pi.getPolicyKey(), synCfg);
if (policy == null) {
handleException("Cannot find Policy from the key");
}
if (NO_SECURITY_POLICY.equals(policy.getId())) {
isNoSecPolicy = true;
log.info("NoSecurity Policy found, skipping policy attachment");
continue;
}
if (pi.isServicePolicy()) {
axisService.getPolicySubject().attachPolicy(policy);
} else if (pi.isOperationPolicy()) {
AxisOperation op = axisService.getOperation(pi.getOperation());
if (op != null) {
op.getPolicySubject().attachPolicy(policy);
} else {
handleException("Couldn't find the operation specified " + "by the QName : " + pi.getOperation());
}
} else if (pi.isMessagePolicy()) {
if (pi.getOperation() != null) {
AxisOperation op = axisService.getOperation(pi.getOperation());
if (op != null) {
op.getMessage(pi.getMessageLable()).getPolicySubject().attachPolicy(policy);
} else {
handleException("Couldn't find the operation " + "specified by the QName : " + pi.getOperation());
}
} else {
// operation is not specified and hence apply to all the applicable messages
for (Iterator itr = axisService.getOperations(); itr.hasNext(); ) {
Object obj = itr.next();
if (obj instanceof AxisOperation) {
// check whether the policy is applicable
if (!((obj instanceof OutOnlyAxisOperation && pi.getType() == PolicyInfo.MESSAGE_TYPE_IN) || (obj instanceof InOnlyAxisOperation && pi.getType() == PolicyInfo.MESSAGE_TYPE_OUT))) {
AxisMessage message = ((AxisOperation) obj).getMessage(pi.getMessageLable());
message.getPolicySubject().attachPolicy(policy);
}
}
}
}
} else {
handleException("Undefined Policy type");
}
}
}
// create a custom message receiver for this proxy service
ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver();
msgRcvr.setName(name);
msgRcvr.setProxy(this);
Iterator iter = axisService.getOperations();
while (iter.hasNext()) {
AxisOperation op = (AxisOperation) iter.next();
op.setMessageReceiver(msgRcvr);
}
try {
axisService.addParameter(SynapseConstants.SERVICE_TYPE_PARAM_NAME, SynapseConstants.PROXY_SERVICE_TYPE);
if (serviceGroup == null) {
auditInfo("Adding service " + name + " to the Axis2 configuration");
axisCfg.addService(axisService);
} else {
auditInfo("Adding service " + name + " to the service group " + serviceGroup);
if (axisCfg.getServiceGroup(serviceGroup) == null) {
// If the specified group does not exist we should create it
AxisServiceGroup proxyServiceGroup = new AxisServiceGroup();
proxyServiceGroup.setServiceGroupName(serviceGroup);
proxyServiceGroup.setParent(axisCfg);
// Add the service to the new group and add the group the AxisConfiguration
proxyServiceGroup.addService(axisService);
axisCfg.addServiceGroup(proxyServiceGroup);
} else {
// Simply add the service to the existing group
axisService.setParent(axisCfg.getServiceGroup(serviceGroup));
axisCfg.addServiceToExistingServiceGroup(axisService, serviceGroup);
}
}
this.setRunning(true);
} catch (AxisFault axisFault) {
try {
if (axisCfg.getService(axisService.getName()) != null) {
if (trace())
trace.info("Removing service " + name + " due to error : " + axisFault.getMessage());
axisCfg.removeService(axisService.getName());
}
} catch (AxisFault ignore) {
}
handleException("Error adding Proxy service to the Axis2 engine", axisFault);
}
// should Addressing be engaged on this service?
if (wsAddrEnabled) {
auditInfo("WS-Addressing is enabled for service : " + name);
try {
axisService.engageModule(axisCfg.getModule(SynapseConstants.ADDRESSING_MODULE_NAME), axisCfg);
} catch (AxisFault axisFault) {
handleException("Error loading WS Addressing module on proxy service : " + name, axisFault);
}
}
// should Security be engaged on this service?
boolean secModuleEngaged = false;
if (wsSecEnabled && !isNoSecPolicy) {
auditInfo("WS-Security is enabled for service : " + name);
try {
axisService.engageModule(axisCfg.getModule(SynapseConstants.SECURITY_MODULE_NAME), axisCfg);
secModuleEngaged = true;
} catch (AxisFault axisFault) {
handleException("Error loading WS Sec module on proxy service : " + name, axisFault);
}
} else if (isNoSecPolicy) {
log.info("NoSecurity Policy found, skipping rampart engagement");
}
moduleEngaged = secModuleEngaged || wsAddrEnabled;
wsdlPublished = wsdlFound;
// Engaging Axis2 modules
Object engaged_modules = parameters.get(ENGAGED_MODULES);
if (engaged_modules != null) {
String[] moduleNames = getModuleNames((String) engaged_modules);
if (moduleNames != null) {
for (String moduleName : moduleNames) {
try {
AxisModule axisModule = axisCfg.getModule(moduleName);
if (axisModule != null) {
axisService.engageModule(axisModule, axisCfg);
moduleEngaged = true;
}
} catch (AxisFault axisFault) {
handleException("Error loading " + moduleName + " module on proxy service : " + name, axisFault);
}
}
}
}
auditInfo("Successfully created the Axis2 service for Proxy service : " + name);
return axisService;
}
use of org.apache.synapse.endpoints.Endpoint in project wso2-synapse by wso2.
the class SynapseCallbackReceiver method handleMessage.
/**
* Handle the response or error (during a failed send) message received for an outgoing request
*
* @param messageID Request message ID
* @param response the Axis2 MessageContext that has been received and has to be handled
* @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above
* Axis2 MC, that holds Synapse specific information such as the error
* handler stack and local properties etc.
* @throws AxisFault if the message cannot be processed
*/
private void handleMessage(String messageID, MessageContext response, org.apache.synapse.MessageContext synapseOutMsgCtx, AsyncCallback callback) throws AxisFault {
// apply the tenant information to the out message context
TenantInfoConfigurator configurator = synapseOutMsgCtx.getEnvironment().getTenantInfoConfigurator();
if (configurator != null) {
configurator.applyTenantInfo(synapseOutMsgCtx);
}
Boolean isConcurrencyThrottleEnabled = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE);
if (isConcurrencyThrottleEnabled != null && isConcurrencyThrottleEnabled) {
ConcurrentAccessController concurrentAccessController = (ConcurrentAccessController) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_CONTROLLER);
int available = concurrentAccessController.incrementAndGet();
int concurrentLimit = concurrentAccessController.getLimit();
if (log.isDebugEnabled()) {
log.debug("Concurrency Throttle : Connection returned" + " :: " + available + " of available of " + concurrentLimit + " connections");
}
ConcurrentAccessReplicator concurrentAccessReplicator = (ConcurrentAccessReplicator) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_REPLICATOR);
String throttleKey = (String) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE_KEY);
if (concurrentAccessReplicator != null) {
concurrentAccessReplicator.replicate(throttleKey, true);
}
}
Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
if (o != null && Boolean.TRUE.equals(o)) {
// This path hits with a fault. Sequence mediator threads should not remove faultSequence.
// SynapseCallbackReceiver thread should handle the faultStack.
Pipe pipe = (Pipe) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
if (pipe != null && pipe.isSerializationComplete()) {
NHttpServerConnection conn = (NHttpServerConnection) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("pass-through.Source-Connection");
SourceConfiguration sourceConfiguration = (SourceConfiguration) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
Pipe newPipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().setProperty(PassThroughConstants.PASS_THROUGH_PIPE, newPipe);
}
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
// fault envelope
try {
synapseOutMsgCtx.getEnvelope().build();
} catch (Exception x) {
synapseOutMsgCtx.setEnvelope(response.getEnvelope());
}
Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);
synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, response.getProperty(SynapseConstants.ERROR_CODE));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE, response.getProperty(SynapseConstants.ERROR_MESSAGE));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_DETAIL, response.getProperty(SynapseConstants.ERROR_DETAIL));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);
if (synapseOutMsgCtx.getEnvironment().isContinuationEnabled()) {
synapseOutMsgCtx.setContinuationEnabled(true);
}
if (log.isDebugEnabled()) {
log.debug("[Failed Request Message ID : " + messageID + "]" + " [New to be Retried Request Message ID : " + synapseOutMsgCtx.getMessageID() + "]");
}
int errorCode = (Integer) response.getProperty(SynapseConstants.ERROR_CODE);
// If a timeout has occured and the timeout action of the callback is to discard the message
if (errorCode == SynapseConstants.NHTTP_CONNECTION_TIMEOUT && callback.getTimeOutAction() == SynapseConstants.DISCARD) {
// Do not execute any fault sequences. Discard message
if (log.isWarnEnabled()) {
log.warn("Synapse timed out for the request with Message ID : " + messageID + ". Ignoring fault handlers since the timeout action is DISCARD");
}
faultStack.removeAllElements();
} else {
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
}
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
Endpoint successfulEndpoint = null;
if (faultStack != null && !faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
successfulEndpoint = (Endpoint) faultStack.pop();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " + (response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " + (response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("WSA-Action: " + (response.getWSAAction() != null ? response.getWSAAction() : "null"));
String[] cids = null;
try {
cids = response.getAttachmentMap().getAllContentIDs();
} catch (Exception ex) {
// partially read stream could lead to corrupted attachment map and hence this exception
// corrupted attachment map leads to inconsistent runtime exceptions and behavior
// discard the attachment map for the fault handler invocation
// ensure the successful completion for fault handler flow
response.setAttachmentMap(null);
log.error("Synapse encountered an exception when reading attachments from bytes stream. " + "Hence Attachments map is dropped from the message context.", ex);
}
if (cids != null && cids.length > 0) {
for (String cid : cids) {
log.debug("Attachment : " + cid);
}
}
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx = ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
// Processes 'Accept-Encoding'
ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);
response.setServiceContext(null);
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.setAxisMessage(axisOutMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));
// set properties on response
response.setServerSide(true);
response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT, axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// response.setDoingREST(axisOutMsgCtx.isDoingREST()); This information already present, hence removing
if (axisOutMsgCtx.isDoingMTOM() && (axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM) == null || Boolean.getBoolean((String) axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM)) == true)) {
response.setDoingMTOM(true);
response.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE);
}
if (axisOutMsgCtx.isDoingSwA()) {
response.setDoingSwA(true);
response.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE);
}
// property state to original state.
if (axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES) != null) {
response.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
} else {
response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
}
Object messageType = axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
if (!HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(messageType)) {
// copy the message type property that's used by the out message to the
// response message
response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, messageType);
}
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(new RelatesTo[] { new RelatesTo(axisOutMsgCtx.getMessageID()) });
}
response.setReplyTo(axisOutMsgCtx.getReplyTo());
response.setFaultTo(axisOutMsgCtx.getFaultTo());
if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
}
// axis2 client options still contains properties such as policy files used in
// outgoing request. Need to remove those.
removeUnwantedClientOptions(response);
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext = new Axis2MessageContext(response, synapseOutMsgCtx.getConfiguration(), synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
Object obj = synapseOutMsgCtx.getProperty(SynapseConstants.FORCE_ERROR_PROPERTY);
String errorOnSOAPFault = (String) obj;
if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) {
if (log.isDebugEnabled()) {
log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault");
}
try {
RelayUtils.buildMessage(((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext(), true);
} catch (Exception e) {
// handleException("Error while building message", e, synapseInMessageContext);
}
if ((synapseInMessageContext.getEnvelope() != null) && synapseInMessageContext.getEnvelope().hasFault()) {
if (log.isDebugEnabled()) {
log.debug("SOAPFault found in response message, forcing endpoint " + successfulEndpoint.getName() + " to fail");
}
// setup new pipe configuration..if failure happens (this will be setup as the source writer and during the TargetContext
// clean up operation the writer will be reset and pull to the buffer
MessageContext axis2OUTMC = ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
NHttpServerConnection conn = (NHttpServerConnection) axis2OUTMC.getProperty("pass-through.Source-Connection");
if (conn != null) {
SourceConfiguration sourceConfiguration = (SourceConfiguration) axis2OUTMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
Pipe pipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
axis2OUTMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
}
synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, SynapseConstants.ENDPOINT_CUSTOM_ERROR);
boolean failOver = false;
if (successfulEndpoint instanceof AbstractEndpoint) {
Endpoint endpoint = ((AbstractEndpoint) successfulEndpoint).getParentEndpoint();
if (endpoint != null && (endpoint instanceof FailoverEndpoint)) {
failOver = true;
}
}
for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key));
}
if (failOver) {
// we may required to handle same message for failover cases only other than that
// should treat based on the incoming message
((FaultHandler) successfulEndpoint).handleFault(synapseOutMsgCtx, null);
} else {
faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null) {
synapseInMessageContext.getFaultStack().addAll(faultStack);
((FaultHandler) successfulEndpoint).handleFault(synapseInMessageContext, null);
}
}
return;
} else {
successfulEndpoint.onSuccess();
}
} else if (successfulEndpoint != null) {
successfulEndpoint.onSuccess();
}
synapseInMessageContext.setTo(new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
synapseInMessageContext.setMessageFlowTracingState(synapseOutMsgCtx.getMessageFlowTracingState());
for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key));
}
// Copy SequenceCallStack from original MC to the new MC
Boolean isContinuationCall = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.CONTINUATION_CALL);
if (isContinuationCall != null && isContinuationCall) {
// Set the message direction
if (!synapseOutMsgCtx.isResponse()) {
synapseInMessageContext.setResponse(false);
}
Stack<ContinuationState> seqContinuationStates = synapseOutMsgCtx.getContinuationStateStack();
for (int i = 0; i < seqContinuationStates.size(); i++) {
synapseInMessageContext.pushContinuationState(seqContinuationStates.get(i));
}
}
// If this response is related to session affinity endpoints -Server initiated session
Dispatcher dispatcher = (Dispatcher) synapseOutMsgCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
dispatcher.updateSession(synapseInMessageContext);
}
// send the response message through the synapse mediation flow
try {
synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
} catch (Exception syne) {
// introduced to handle runtime exceptions which are occurred inside Synapse handlers
// partially read stream could lead to corrupted attachment map and hence this exception
// corrupted attachment map leads to inconsistent runtime exceptions and behavior
// discard the attachment map for the fault handler invocation
// ensure the successful completion for fault handler flow
// even we drop attachment map for both cases messages which have attachment /
// messages which do not have attachments it would still not be any impact.
// However setting attachment map to null for messages which do not have attachments is not required.
// introduced due to the fact conflicts between Axiom exceptions for attachment/ non attachments cases
// and performance impact that could cause of regular expression matching of exceptional stack traces.
Axis2MessageContext axis2smc = (Axis2MessageContext) synapseInMessageContext;
org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
// Set correct status code
axis2MessageCtx.setProperty(PassThroughConstants.HTTP_SC, HttpStatus.SC_INTERNAL_SERVER_ERROR);
axis2MessageCtx.setAttachmentMap(null);
Stack stack = synapseInMessageContext.getFaultStack();
if (stack != null && stack.isEmpty()) {
registerFaultHandler(synapseInMessageContext);
}
if (stack != null && !stack.isEmpty()) {
((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
} else {
log.error("Synapse encountered an exception, " + "No error handlers found - [Message Dropped]\n" + syne.getMessage());
}
}
}
}
use of org.apache.synapse.endpoints.Endpoint in project wso2-synapse by wso2.
the class RecipientListEndpointFactory method createEndpoint.
@Override
protected Endpoint createEndpoint(OMElement epConfig, boolean anonymousEndpoint, Properties properties) {
OMElement recipientListElement = epConfig.getFirstChildWithName(new QName(SynapseConstants.SYNAPSE_NAMESPACE, "recipientlist"));
if (recipientListElement != null) {
// create endpoint
RecipientListEndpoint recipientListEndpoint = new RecipientListEndpoint();
// set endpoint name
OMAttribute name = epConfig.getAttribute(new QName(org.apache.synapse.config.xml.XMLConfigConstants.NULL_NAMESPACE, "name"));
if (name != null) {
recipientListEndpoint.setName(name.getAttributeValue());
}
// set endpoints or members
if (recipientListElement.getFirstChildWithName(XMLConfigConstants.ENDPOINT_ELT) != null) {
if (recipientListElement.getChildrenWithName((MEMBER)).hasNext()) {
String msg = "Invalid Synapse configuration. " + "child elements";
log.error(msg);
throw new SynapseException(msg);
}
List<Endpoint> endpoints = getEndpoints(recipientListElement, recipientListEndpoint, properties);
recipientListEndpoint.setChildren(endpoints);
} else if (recipientListElement.getFirstChildWithName(MEMBER) != null) {
if (recipientListElement.getChildrenWithName((XMLConfigConstants.ENDPOINT_ELT)).hasNext()) {
String msg = "Invalid Synapse configuration. " + "recipientListElement element cannot have both member & endpoint " + "child elements";
log.error(msg);
throw new SynapseException(msg);
}
List<Member> members = getMembers(recipientListElement);
recipientListEndpoint.setMembers(members);
} else if (recipientListElement.getFirstChildWithName(DYNAMIC_SET) != null) {
OMElement dynamicSetElement = recipientListElement.getFirstChildWithName(DYNAMIC_SET);
Value dynamicEndpointSet = new ValueFactory().createValue("value", dynamicSetElement);
String maxStr = dynamicSetElement.getAttributeValue(new QName("max-cache"));
int maxCache = -1;
try {
maxCache = Integer.parseInt(maxStr);
} catch (NumberFormatException e) {
}
recipientListEndpoint = new RecipientListEndpoint(maxCache < 0 ? RecipientListEndpoint.DEFAULT_MAX_POOL : maxCache);
if (name != null) {
recipientListEndpoint.setName(name.getAttributeValue());
}
recipientListEndpoint.setDynamicEnpointSet(dynamicEndpointSet);
}
if (recipientListEndpoint.getChildren() == null && recipientListEndpoint.getMembers() == null && recipientListEndpoint.getDynamicEnpointSet() == null) {
String msg = "Invalid Synapse configuration.\n" + "A RecipientListEndpoint must have child/member elements, but the RecipientListEndpoint " + "'" + recipientListEndpoint.getName() + "' does not have any child/member/dynamic endpoint elements.";
log.error(msg);
throw new SynapseException(msg);
}
// process the parameters
processProperties(recipientListEndpoint, epConfig);
return recipientListEndpoint;
}
return null;
}
Aggregations