SOAPHandler handleMessage return custom fault - web-services

I have a custom SOAPHandler and the handleMessage() is as follows :
public boolean handleMessage(SOAPMessageContext context) {
// TODO Auto-generated method stub
/* Step-1: Extract credentials from the SOAP header */
Boolean isOutbound = (Boolean) context
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
log.info("In TransportHandler.handleMessage(...) " + isOutbound);
if (!isOutbound) {
SOAPMessage soapMsg = context.getMessage();
try {
SOAPUtil soapUtil = new SOAPUtil();
Credentials credentials = soapUtil.retrieveCredentials(soapMsg);
/* Validate credentials against the directory */
SecurityUtil securityUtil = new SecurityUtil();
securityUtil.authenticateClient(credentials.getUserName(),
credentials.getPassword());
} catch (SecurityFault_Exception e) {
// TODO Auto-generated catch block
log.error(
"SecurityFault_Exception in TransportHandler.handleMessage(...)",
e);
SOAPFault securityFault = null;
try {
securityFault = soapMsg.getSOAPBody().addFault();
securityFault.setFaultString(e.getMessage());
throw new SOAPFaultException(securityFault);
} catch (SOAPException e1) {
// TODO Auto-generated catch block
log.error(
"SOAPException while handing SecurityFault_Exception in TransportHandler.handleMessage(...)",
e1);
}
} catch (RequestMessageFormatFault_Exception e) {
// TODO Auto-generated catch block
log.error(
"RequestMessageFormatFault_Exception in TransportHandler.handleMessage(...)",
e);
SOAPFault requestFormatFault = null;
try {
requestFormatFault = soapMsg.getSOAPBody().addFault();
requestFormatFault.setFaultString(e.getFaultInfo().getCustomMessage());
throw new SOAPFaultException(requestFormatFault);
} catch (SOAPException e1) {
// TODO Auto-generated catch block
log.error(
"SOAPException while handing RequestMessageFormatFault_Exception in TransportHandler.handleMessage(...)",
e1);
}
}
}
log.info("Returning from TransportHandler.handleMessage(...)");
return true;
}
For example, if someone doesn't add the security header, following is the response :
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server</faultcode>
<faultstring>Security header not present in the SOAP request</faultstring>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
Now in the handleMessage(...), I have wrapped the custom fault for bad header as shown :
catch (RequestMessageFormatFault_Exception e) {
// TODO Auto-generated catch block
log.error(
"RequestMessageFormatFault_Exception in TransportHandler.handleMessage(...)",
e);
SOAPFault requestFormatFault = null;
try {
requestFormatFault = soapMsg.getSOAPBody().addFault();
requestFormatFault.setFaultString(e.getFaultInfo().getCustomMessage());
throw new SOAPFaultException(requestFormatFault);
} catch (SOAPException e1) {
// TODO Auto-generated catch block
log.error(
"SOAPException while handing RequestMessageFormatFault_Exception in TransportHandler.handleMessage(...)",
e1);
}
}
As per our org. standards, I have the below faults declared in the wsdl(partially shown here) :
.
.
.
<message name="RequestMessageFormatFault">
<part name="RequestMessageFormatFault" element="sch:RequestMessageFormatFault" />
</message>
<message name="SecurityFault">
<part name="SecurityFault" element="sch:SecurityFault" />
</message>
.
.
.
<portType name="TransportInformationDelegate">
<operation name="GetTransportInformation">
.
.
<fault name="RequestMessageFormatFault" message="tns:RequestMessageFormatFault"/>
<fault name="SecurityFault" message="tns:SecurityFault"/>
</operation>
</portType>
<binding name="TransportInformationPortBinding" type="tns:TransportInformationDelegate">
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="GetTransportInformation">
.
.
.
.
<fault name="RequestMessageFormatFault">
<soap:fault name="RequestMessageFormatFault" use="literal"/>
</fault>
<fault name="SecurityFault">
<soap:fault name="SecurityFault" use="literal"/>
</fault>
</operation>
How shall I ensure that the response has this fault ? I tried the SOAPFault.addDetail(...) in vain.

Related

Balana: Root policy with issuer is treated like a trusted policy

I implemented the wso2 Balana PDP.
I have a simple policy issued by Bob giving subject Alice permission. When I evaluate a request from Alice the implementation returns a Permit even though there is no trusted policy (I assumed it should return NotApplicable).
As far as I understand there needs to be at least one policy without issuer as the root of the reduction graph (OASIS Specification).
Do I need to implement the policy finder differently or did I misunderstand the administration concept?
This is the PDP code:
package xacmlimplementation.wso2;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.wso2.balana.Balana;
import org.wso2.balana.PDP;
import org.wso2.balana.PDPConfig;
import org.wso2.balana.ParsingException;
import org.wso2.balana.combine.PolicyCombiningAlgorithm;
import org.wso2.balana.combine.xacml2.FirstApplicablePolicyAlg;
import org.wso2.balana.ctx.AbstractResult;
import org.wso2.balana.ctx.ResponseCtx;
import org.wso2.balana.finder.AttributeFinderModule;
import org.wso2.balana.finder.PolicyFinder;
import org.wso2.balana.finder.PolicyFinderModule;
import org.wso2.balana.finder.impl.FileBasedPolicyFinderModule;
import org.xml.sax.SAXException;
import xacmlimplementation.engine.XacmlResult;
import xacmlimplementation.engine.XacmlResult.Decision;
import xacmlimplementation.engine.XacmlResult.ErrorType;
public class TestBalana {
public static void main(String[] args) {
Set<String> policyLocations = new HashSet<String>();
policyLocations.add("/path/to/policy.xml");
String request = "/path/to/request.xml";
// create default instance of Balana
Balana balana = Balana.getInstance();
// Default PDP config
PDPConfig pdpConfig = balana.getPdpConfig();
// Set up policy finder
PolicyCombiningAlgorithm wso2Alg = new FirstApplicablePolicyAlg();
PolicyFinder policyFinder = new PolicyFinder();
Set<PolicyFinderModule> policyFinderModules = new HashSet<PolicyFinderModule>();
// module for the root policies
// FileBasedPolicyFinderModule uses DenyOverrides
PolicyFinderModule policyModule = new FileBasedPolicyFinderModule(policyLocations);
policyFinderModules.add(policyModule);
policyFinder.setModules(policyFinderModules);
PDP pdp = new PDP(new PDPConfig(pdpConfig.getAttributeFinder(), policyFinder, null));
String requestString = null;
try {
Path p = Paths.get(request);
byte[] content = java.nio.file.Files.readAllBytes(p);
requestString = new String(content);
} catch (IOException e) {
System.out.println("Error reading "+request);
return;
}
String response = pdp.evaluate(requestString);
ResponseCtx responseCtx = null;
ByteArrayInputStream inputStream = null;
AbstractResult result = null;
try {
DocumentBuilderFactory dbf;
Document doc;
inputStream = new ByteArrayInputStream(response.getBytes());
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
doc = dbf.newDocumentBuilder().parse(inputStream);
responseCtx = ResponseCtx.getInstance(doc.getDocumentElement());
Iterator<AbstractResult> it = responseCtx.getResults().iterator();
result = it.next();
} catch (ParsingException e) {
System.out.println("Error parsing xacml response: " + e.getMessage());
e.printStackTrace();
return;
} catch (NoSuchElementException e) {
System.out.println("Result list is empty");
e.printStackTrace();
return;
} catch (SAXException e) {
System.out.println(e);
e.printStackTrace();
return;
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
return;
} catch (ParserConfigurationException e) {
System.out.println(e);
e.printStackTrace();
return;
}
try {
inputStream.close();
} catch (IOException e) {
System.err.println("Error in closing input stream of XACML response");
return;
}
//System.out.println(result.encode());
switch (result.getDecision()) {
case AbstractResult.DECISION_PERMIT:
System.out.println("Permit");
break;
case AbstractResult.DECISION_DENY:
System.out.println("Deny");
break;
case AbstractResult.DECISION_NOT_APPLICABLE:
System.out.println("NotApplicable");
break;
case AbstractResult.DECISION_INDETERMINATE:
case AbstractResult.DECISION_INDETERMINATE_PERMIT:
case AbstractResult.DECISION_INDETERMINATE_DENY:
case AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT:
System.out.println("Indeterminate");
break;
default:
System.out.println("Decision doesn't match Permit, Deny, NotApplicable, ...");
break;
}
}
}
The policy:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<PolicySet xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyCombiningAlgId="urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:permit-overrides" PolicySetId="PolicySet1" Version="1.0">
<Target/>
<Policy PolicyId="PolicyBobGrantsAliceAccess" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:permit-overrides" Version="1.0">
<PolicyIssuer>
<Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" IncludeInResult="true">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Bob</AttributeValue>
</Attribute>
</PolicyIssuer>
<Target>
<AnyOf>
<AllOf>
<Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Alice</AttributeValue>
<AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"/>
</Match>
</AllOf>
</AnyOf>
</Target>
<Rule Effect="Permit" RuleId="Rule1">
<Target/>
</Rule>
</Policy>
</PolicySet>
The request:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Request xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" CombinedDecision="false" ReturnPolicyIdList="false">
<Attributes Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject">
<Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" IncludeInResult="false">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Alice</AttributeValue>
</Attribute>
</Attributes>
</Request>

As in the iterate to change the message and send it fully (wso2esb)

I receive a message from AAA nested children. I want every child BBB replace the value of CCC. Then send the modified message on AAA
<AAA>
<BBB>
<CCC>test1</CCC>
<DDD>testing</DDD>
</BBB>
<BBB>
<CCC>test2</CCC>
<DDD>testing</DDD>
</BBB>
<BBB>
<CCC>test3</CCC>
<DDD>testing</DDD>
</BBB>
<BBB>
<CCC>test4</CCC>
<DDD>testing</DDD>
</BBB>
<BBB>
<CCC>test5</CCC>
<DDD>testing</DDD>
</BBB>
</AAA>
I do it:
<iterate continueParent="true" expression="/AAA/BBB">
<target>
<sequence>
<property name="newValue" value="chang testing" scope="default" type="STRING"/>
<enrich>
<source clone="false" type="custom" xpath="get-property('newValue')"/>
<target action="replace" type="custom" xpath="//DDD"/>
</enrich>
</sequence>
</target>
</iterate>
But changing the message is not stored on
If you use iterate mediator you have to aggregate the results to get the modified message. How ever this can be achieved by using xslt mediator. Sample proxy configuration would be look like follows
<proxy name="yourpproxy" transports="https http" startOnLoad="true" trace="disable">
<description/>
<target>
<inSequence>
<xslt key="yourxsltkey"/>
<send/>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
</proxy>
where yourxsltkey is the key to your xslt definition. This can be either declare as local entry or in registry. As an sample here i have defined as a local entry.
<localEntry key="yourxsltkey">
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<AAA xmlns="http://ws.apache.org/ns/synapse">
<xsl:for-each select="AAA/BBB">
<BBB><xsl:value-of select="CCC"/></BBB>
</xsl:for-each>
</AAA>
</xsl:template>
</xsl:stylesheet>
</localEntry>
I wrote my mediator and use it for this purpose
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.impl.dom.NamespaceImpl;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.AxisFault;
import org.apache.synapse.Mediator;
import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
import org.apache.synapse.mediators.eip.EIPUtils;
import org.apache.synapse.util.MessageHelper;
import org.apache.synapse.util.xpath.SynapseXPath;
import org.jaxen.JaxenException;
import java.util.List;
public class SplitMediator extends AbstractMediator {
private String sequenceRef = null;
private String xpathString = null;
private String attachPathString = null;
private String uri = null;
private String prefix = null;
public boolean mediate(MessageContext synCtx) {
if (sequenceRef == null || xpathString == null || attachPathString == null) {
handleException("Error creating a mediate due to sequenceRef or xpathString attachPathString is null", synCtx);
return false;
}
try {
SOAPEnvelope envelope = synCtx.getEnvelope();
Mediator sequenceMediator = synCtx.getSequence(sequenceRef);
SynapseXPath expression = new SynapseXPath(xpathString);
if (uri != null && prefix != null)
expression.addNamespace(new NamespaceImpl(uri, prefix));
SynapseXPath attachPath = new SynapseXPath(attachPathString);
if (uri != null && prefix != null)
attachPath.addNamespace(new NamespaceImpl(uri, prefix));
List<OMNode> splitElements = EIPUtils.getDetachedMatchingElements(envelope, synCtx, expression);
MessageContext templateMessageContext = MessageHelper.cloneMessageContext(synCtx);
OMElement omElement = getOMElementByXPath(attachPath, envelope, synCtx);
for (OMNode o : splitElements) {
MessageContext changeCtx = getNewMessageContextToSequence(templateMessageContext, o, attachPath);
sequenceMediator.mediate(changeCtx);
List elementList = EIPUtils.getMatchingElements(changeCtx.getEnvelope(), expression);
OMNode changeElement = (OMNode) elementList.get(0);
omElement.addChild(changeElement);
}
} catch (JaxenException e) {
handleException("Error evaluating split XPath expression : " + xpathString, e, synCtx);
} catch (AxisFault af) {
handleException("Error creating an iterated copy of the message", af, synCtx);
}
return true;
}
private MessageContext getNewMessageContextToSequence(MessageContext templateMessageContext, OMNode o, SynapseXPath attachPath) throws AxisFault, JaxenException {
MessageContext synCtx = MessageHelper.cloneMessageContext(templateMessageContext);
SOAPEnvelope envelope = synCtx.getEnvelope();
OMElement omElement = getOMElementByXPath(attachPath, envelope, synCtx);
omElement.addChild(o);
return synCtx;
}
private OMElement getOMElementByXPath(SynapseXPath attachPath, SOAPEnvelope envelope, MessageContext synCtx) {
Object attachElem = attachPath.evaluate(envelope, synCtx);
if (attachElem != null &&
attachElem instanceof List && !((List) attachElem).isEmpty()) {
attachElem = ((List) attachElem).get(0);
}
// for the moment attaching element should be an OMElement
if (attachElem != null && attachElem instanceof OMElement) {
return ((OMElement) attachElem);
} else {
handleException("Error in attaching the splitted elements :: " +
"Unable to get the attach path specified by the expression " +
attachPath, synCtx);
}
return null;
}
///////////////////////////////////////////////////////////////////////////////////////
// Getters and Setters //
///////////////////////////////////////////////////////////////////////////////////////
public String getXpathString() {
return xpathString;
}
public void setXpathString(String xpathString) {
this.xpathString = xpathString;
}
public String getAttachPathString() {
return attachPathString;
}
public void setAttachPathString(String attachPathString) {
this.attachPathString = attachPathString;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSequenceRef() {
return sequenceRef;
}
public void setSequenceRef(String sequenceRef) {
this.sequenceRef = sequenceRef;
}
}

Why don't change lifecycle state of mule runtime?

I want to save some informaion to database when I send a request to mule service.
for this issue: I wrote below config in xml file:
<mule xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns:cxf="http://www.mulesoft.org/schema/mule/cxf" xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting"
xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security"
xmlns:ss="http://www.springframework.org/schema/security" xmlns:jdbc="http://www.mulesoft.org/schema/mule/jdbc"
xmlns:spring="http://www.springframework.org/schema/beans" version="CE-3.3.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/cxf http://www.mulesoft.org/schema/mule/cxf/current/mule-cxf.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd
http://www.mulesoft.org/schema/mule/spring-security http://www.mulesoft.org/schema/mule/spring-security/3.3/mule-spring-security.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.mulesoft.org/schema/mule/jdbc http://www.mulesoft.org/schema/mule/jdbc/current/mule-jdbc.xsd ">
<spring:beans>
<spring:bean id="Initializer" name="Initializer" class="org.mule.example.scripting.IpClient" doc:name="Bean"/>
</spring:beans>
<notifications>
<notification event="COMPONENT-MESSAGE"/>
<notification-listener ref="Initializer"/>
</notifications>
<configuration doc:name="Configuration">
<expression-language>
<global-functions>
def parseIp(fullIp) {
return
fullIp.substring(fullIp.indexOf('/') + 1, fullIp.indexOf(':'))
}
</global-functions>
</expression-language>
</configuration>
<http:connector name="httpConnector" doc:name="HTTP\HTTPS">
<service-overrides sessionHandler="org.mule.session.NullSessionHandler" />
</http:connector>
<mule-ss:security-manager>
<mule-ss:delegate-security-provider
name="memory-dao" delegate-ref="authenticationManager" />
</mule-ss:security-manager>
<spring:beans>
<ss:authentication-manager alias="authenticationManager">
<ss:authentication-provider>
<ss:user-service id="userService">
<ss:user name="weather" password="weather" authorities="ROLE_ADMIN" />
</ss:user-service>
</ss:authentication-provider>
</ss:authentication-manager>
</spring:beans>
<flow name="Serive_test" doc:name="Serive_test">
<http:inbound-endpoint host="localhost" port="8089"
path="service/local-weather" exchange-pattern="request-response"
doc:name="HTTP">
<mule-ss:http-security-filter realm="mule-realm" />
</http:inbound-endpoint>
<async doc:name="Async">
<set-variable variableName="remoteClientAddress"
value="#[parseIp(message.inboundProperties['MULE_REMOTE_CLIENT_ADDRESS'])]"
doc:name="Variable" />
<message-properties-transformer
doc:name="myproperty" scope="session">
<add-message-property key="message.payload.remoteClientAddress"
value="#[parseIp(message.inboundProperties['MULE_REMOTE_CLIENT_ADDRESS'])]" />
</message-properties-transformer>
<component doc:name="classTest" class="org.mule.example.scripting.IpClient" />
</async>
<cxf:proxy-service service="Weather" doc:name="Weather_webservice"
wsdlLocation="http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl" namespace="http://ws.cdyne.com/WeatherWS/"
payload="envelope"></cxf:proxy-service>
<copy-properties propertyName="SOAPAction" doc:name="Property"></copy-properties>
<cxf:proxy-client doc:name="Weather_webservice"
payload="envelope" />
<outbound-endpoint address="http://wsf.cdyne.com/WeatherWS/Weather.asmx"
exchange-pattern="request-response" doc:name="HTTP"></outbound-endpoint>
</flow>
and IpClient class:
public class IpClient implements Callable,ModelNotificationListener<ModelNotification> {
#Override
public void onNotification(ModelNotification notification) {
// TODO Auto-generated method stub
System.out.println("Notification order event: " + notification.getActionName() );
if(notification.getAction() == ModelNotification.MODEL_DISPOSED || notification.getAction() == ModelNotification.MODEL_STOPPED){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
ConnectDB c = new ConnectDB("localhost:3306", "accounting", "root", "");
String sql = " INSERT INTO weather (ip, date, CurrentState) VALUES (?,?,?) ";
PreparedStatement ps = null;
try {
ps = c.getConnnection().prepareStatement(sql);
ps.setString(1, "127.0.0.1");
ps.setString(2, dateFormat.format(date).toString());
ps.setString(3, notification.getActionName());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
c.close();
}
}
}
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
MuleMessage msg = eventContext.getMessage();
String remClient = msg.getProperty("remoteClientAddress", PropertyScope.INVOCATION);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
ConnectDB c = new ConnectDB("localhost:3306", "accounting", "root", "");
String sql = " INSERT INTO weather (ip, date, CurrentState) VALUES (?,?,?) ";
PreparedStatement ps = c.getConnnection().prepareStatement(sql);
ps.setString(1, remClient);
ps.setString(2, dateFormat.format(date).toString());
ps.setString(3, msg.getMuleContext().getLifecycleManager().getCurrentPhase());
ps.executeUpdate();
c.close();
return msg.getPayload();
}
}
this program just works correctly if I start to run service. for example my service run before suddenly it was dissposed(for example my wsdl(http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl doesn't work)). my log program saved all records in state of start and after dissposing it works similar. if I stoped my service and run it again it works correctly and it saves all records in dissposed mode.
I don't know how to change my program that it saves correctly in runtime.
The (ill named) Initializer bean is not used as a <component> anywhere in the configuration so there's no way its onCall method will ever get called.
If your intention with:
<notification event="COMPONENT-MESSAGE"/>
is to have the Initializer called for each component invocation you then have to make it implement ComponentMessageNotificationListener (like you made it implement ModelNotificationListener).

Soap Error connecting to hosted CRM online 2011

I have been trying to troubleshoot this error for a long time.
"An error occurred when verifying security for the message"
I did some research, people said this is because the time difference between the server and the client.
This anyone else have the same problem?
Below is the detail of my error
System.ServiceModel.FaultException was caught
Message=An error occurred when verifying security for the message.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at WindowsFormsApplication1.CrmSdk.Discovery.IDiscoveryService.Execute(DiscoveryRequest request)
at WindowsFormsApplication1.CrmSdk.Discovery.DiscoveryServiceClient.Execute(DiscoveryRequest request) in WindowsFormsApplication1\Service References\CrmSdk.Discovery\Reference.cs:line 723
at WindowsFormsApplication1.Form1.DiscoverOrganizationUrl(String organizationName, String discoveryServiceUrl) in Form1.cs:line 110
InnerException:
Here is the code i used to access the hosted CRM online webservice
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
//using System.ServiceModel;
//using System.ServiceModel.Description;
namespace WindowsFormsApplication1
{
using CrmSdk;
using CrmSdk.Discovery;
using System.Net;
using System.Globalization;
using LocalServices;
using System.ServiceModel;
using System.Web.Services.Protocols;
public partial class Form1 : Form
{
///hosted CRM online
private const string DiscoveryServiceUrl = "https://disco.crm.dynamics.com/XRMServices/2011/Discovery.svc";
private IOrganizationService _service;
private string fetchXML =
#"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='name' />
<attribute name='address1_city' />
<attribute name='primarycontactid' />
<attribute name='telephone1' />
<attribute name='accountid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='ownerid' operator='eq-userid' />
<condition attribute='statecode' operator='eq' value='0' />
</filter>
<link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
<attribute name='emailaddress1' />
</link-entity>
</entity>
</fetch>
";
public Form1()
{
InitializeComponent();
//GetDataFromCRM();
GetDataFromCRM2();
}
private void GetDataFromCRM2()
{
private string DiscoverOrganizationUrl(string organizationName, string discoveryServiceUrl)
{
using (CrmSdk.Discovery.DiscoveryServiceClient client = new CrmSdk.Discovery.DiscoveryServiceClient("CustomBinding_IDiscoveryService", discoveryServiceUrl))
{
//ApplyCredentials(client, credentials);
client.ClientCredentials.Windows.ClientCredential.UserName = UserName;
client.ClientCredentials.Windows.ClientCredential.Password = Password
client.ClientCredentials.Windows.ClientCredential.Domain = Domain
CrmSdk.Discovery.RetrieveOrganizationRequest request = new CrmSdk.Discovery.RetrieveOrganizationRequest()
{
UniqueName = organizationName
};
try
{
CrmSdk.Discovery.RetrieveOrganizationResponse response = (CrmSdk.Discovery.RetrieveOrganizationResponse)client.Execute(request);
foreach (KeyValuePair<CrmSdk.Discovery.EndpointType, string> endpoint in response.Detail.Endpoints)
{
if (CrmSdk.Discovery.EndpointType.OrganizationService == endpoint.Key)
{
Console.WriteLine("Organization Service URL: {0}", endpoint.Value);
return endpoint.Value;
}
}
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Organization {0} does not have an OrganizationService endpoint defined.", organizationName));
}
catch (FaultException e)
{
MessageBox.Show(e.Message);
throw;
}
catch (SoapHeaderException e)
{
MessageBox.Show(e.Message);
throw;
}
catch (SoapException e)
{
MessageBox.Show(e.Message);
throw;
}
return null;
}
}
//private static void ApplyCredentials<TChannel>(ClientBase<TChannel> client, ICredentials credentials)
// where TChannel : class
//{
// client.ClientCredentials.Windows.ClientCredential = credentials.Windows.ClientCredential;
//}
private void ExecuteFetch(string serviceUrl)
{
using (OrganizationServiceClient client = new OrganizationServiceClient("CustomBinding_IOrganizationService", new EndpointAddress(serviceUrl)))
{
client.ClientCredentials.Windows.ClientCredential.UserName = UserName;
client.ClientCredentials.Windows.ClientCredential.Password = Password;
client.ClientCredentials.Windows.ClientCredential.Domain = Domain;
_service = (IOrganizationService)client;
FetchExpression expression = new FetchExpression();
expression.Query =
#"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='name' />
<attribute name='address1_city' />
<attribute name='primarycontactid' />
<attribute name='telephone1' />
<attribute name='accountid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='ownerid' operator='eq-userid' />
<condition attribute='statecode' operator='eq' value='0' />
</filter>
<link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
<attribute name='emailaddress1' />
</link-entity>
</entity>
</fetch>
";
EntityCollection result = _service.RetrieveMultiple(expression);
DataTable temp = ConvertEntityToTable(result);
}
}
/// Convert Entity To datatable
private DataTable ConvertEntityToTable(EntityCollection result)
{
DataTable dt = new DataTable();
int rowCount = result.Entities.Count();
try
{
for (int i = 0; i < rowCount; i++)
{
DataRow dr = dt.NewRow();
Entity currentEntity = (Entity)result.Entities[i];
var keys = currentEntity.Attributes.Count();
for (int j = 0; j < keys; j++)
{
string columName = currentEntity.Attributes[j].Key;
string value = currentEntity.Attributes[j].Value.ToString();
if (dt.Columns.IndexOf(columName) == -1)
dt.Columns.Add(columName, Type.GetType("Sysem.String"));
dr[columName] = value;
}
dt.Rows.Add(dr);
}
return dt;
}
catch (Exception exp)
{
throw;
}
}
}
}
app.config
<bindings>
<customBinding>
<binding name="CustomBinding_IDiscoveryService">
<textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
messageVersion="Default" writeEncoding="utf-8">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</textMessageEncoding>
<httpsTransport manualAddressing="false" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
useDefaultWebProxy="true" requireClientCertificate="false"
/>
</binding>
It throw the error at FaultException
Thanks for all the help
The general consensus appears to be that besides the actual time, the timezone and daylight savings time settings appear to be the cause of this error. The client and server need to be in sync with each other.

Unable to access web service endpoint: Spring-WS 2

I'm new to Spring-WS and I have defined an endpoint based off a schema generated from JAXB annotated classes. However, when I try to access the endpoint via soapUI, I get the following error along with a 404 response code:
No endpoint mapping found for [SaajSoapMessage {clip}clipClaimRequest]
Any ideas as to what I'm doing wrong? Thanks for any help given.
The endpoint class:
#Endpoint
public class TestEndpoint {
#PayloadRoot(localPart = "clipClaimRequest", namespace = "clip")
#ResponsePayload
public CLIPClaimResponse registerClaim(#RequestPayload CLIPClaimRequest request) {
return new CLIPClaimResponse("Success", "test success");
}
}
The request/response classes (marshalled/unmarshalled via JAXB):
#XmlRootElement(name = "clipClaimRequest")
#XmlType(name = "CLIPClaimRequest")
public class CLIPClaimRequest {
private Claim claim;
#XmlElement(required = true)
public Claim getClaim() {
return claim;
}
public void setClaim(Claim claim) {
this.claim = claim;
}
}
And:
#XmlRootElement(name = "clipClaimResponse")
#XmlType(name = "CLIPClaimResponse")
public class CLIPClaimResponse {
private String code;
private String description;
public CLIPClaimResponse() {
}
public CLIPClaimResponse(String code, String desc) {
setCode(code);
setDescription(desc);
}
#XmlElement(required = true)
public String getCode() {
return code;
}
#XmlElement(required = true)
public String getDescription() {
return description;
}
public void setCode(String code) {
this.code = code;
}
public void setDescription(String description) {
this.description = description;
}
}
web.xml servlet configuration:
<servlet>
<servlet-name>spring-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<init-param>
<description>This is used by SpringWS to dynamically convert WSDL urls</description>
<param-name>transformWsdlLocations</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-ws</servlet-name>
<url-pattern>/clipClaimService/*</url-pattern>
</servlet-mapping>
spring-ws-servlet.xml configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context:annotation-config />
<sws:annotation-driven />
<sws:dynamic-wsdl id="claimRegistration" portTypeName="CLIPClaimPort"
locationUri="/clipClaimService/" targetNamespace="clip">
<sws:xsd location="/WEB-INF/CLIP_Poc.xsd" />
</sws:dynamic-wsdl>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<!-- list of classes... -->
</list>
</property>
<property name="schema" value="/WEB-INF/CLIP_PoC.xsd" />
</bean>
<bean id="marshallingPayloadMethodProcessor"
class="org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor">
<constructor-arg ref="jaxb2Marshaller" />
<constructor-arg ref="jaxb2Marshaller" />
</bean>
<bean id="defaultMethodEndpointAdapter"
class="org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter">
<property name="methodArgumentResolvers">
<list>
<ref bean="marshallingPayloadMethodProcessor" />
</list>
</property>
<property name="methodReturnValueHandlers">
<list>
<ref bean="marshallingPayloadMethodProcessor" />
</list>
</property>
</bean>
</beans>
And finally, CLIP_PoC.xsd, the schema from which the WSDL was generated:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="clip" targetNamespace="clip" version="1.0">
<xs:element name="clipClaimRequest" type="CLIPClaimRequest"/>
<xs:element name="clipClaimResponse" type="CLIPClaimResponse"/>
<!-- type definitions for all the complex elements used... -->
</xs:schema>
I figured it out. I had forgotten to put: <context:component-scan base-package="my.base.package"/> in my spring-ws-servlet.xml file. This fixed it somehow.