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

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>

Related

getting error in oozie job

I have a WordCount MapReduce job, when it runs from hadoop cli it runs well and given the output. but when I run the job through oozie it throwing me error 'Error: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, received org.apache.hadoop.io.LongWritable'
Here is the code
package Drivers;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class WordCount extends Configured implements Tool
{
public static void main(String[] args) throws Exception
{
int res = ToolRunner.run(new Configuration(), new WordCount(), args);
System.exit(res);
}
#Override
public int run(String[] args) throws Exception
{
Job job = Job.getInstance(getConf(), "Tool Job");
job.setJarByClass(WordCount.class);
job.setMapperClass(WordMap.class);
job.setReducerClass(RedForSum.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
return job.waitForCompletion(true) ? 0 : 1;
}
//map method
public static class WordMap extends Mapper<LongWritable,Text,Text,IntWritable>
{
public void map(LongWritable k, Text v,Context con) throws IOException, InterruptedException
{
String line=v.toString();
StringTokenizer t = new StringTokenizer(line);
while(t.hasMoreTokens())
{
String word=t.nextToken();
con.write(new Text(word),new IntWritable(1));
}
}
}
//reducer method
public static class RedForSum extends Reducer<Text, IntWritable,Text,IntWritable>
{
public void reduce(Text k, Iterable<IntWritable> vlist, Context con) throws IOException, InterruptedException
{
int tot=0;
for(IntWritable v:vlist)
tot+=v.get();
con.write(k, new IntWritable(tot));
}
}
}
my workflow.xml is here
<workflow-app xmlns="uri:oozie:workflow:0.1" name="map-reduce-wf">
<start to="mr-node"/>
<action name="mr-node">
<map-reduce>
<job-tracker>${jobTracker}</job-tracker>
<name-node>${nameNode}</name-node>
<configuration>
<property>
<name>mapred.mapper.new-api</name>
<value>true</value>
</property>
<property>
<name>mapred.reducer.new-api</name>
<value>true</value>
</property>
<property>
<name>mapred.job.queue.name</name>
<value>${queueName}</value>
</property>
<property>
<name>mapreduce.mapper.class</name>
<value>Drivers.WordCount$WordMap</value>
</property>
<property>
<name>mapreduce.reducer.class</name>
<value>Drivers.WordCount$RedForSum</value>
</property>
<property>
<name>mapred.output.key.class</name>
<value>org.apache.hadoop.io.Text</value>
</property>
<property>
<name>mapred.output.value.class</name>
<value>org.apache.hadoop.io.IntWritable</value>
</property>
<property>
<name>mapred.input.dir</name>
<value>${inputDir}</value>
</property>
<property>
<name>mapred.output.dir</name>
<value>${outputDir}</value>
</property>
</configuration>
</map-reduce>
<ok to="end"/>
<error to="fail"/>
</action>
<kill name="fail">
<message>Map/Reduce failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
</kill>
<end name="end"/>
</workflow-app>
When I run through oozie
oozie job -oozie http://localhost:11000/oozie -config /home/cloudera/job.properties -run
it throwing me the error
Error: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, received org.apache.hadoop.io.LongWritable
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.collect(MapTask.java:1072)
at org.apache.hadoop.mapred.MapTask$NewOutputCollector.write(MapTask.java:715)
at org.apache.hadoop.mapreduce.task.TaskInputOutputContextImpl.write(TaskInputOutputContextImpl.java:89)
at org.apache.hadoop.mapreduce.lib.map.WrappedMapper$Context.write(WrappedMapper.java:112)
at org.apache.hadoop.mapreduce.Mapper.map(Mapper.java:124)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
Can someone please let me know where I was mistaken.
Thanks in Advance.
The problem seems to be in workflow xml. here the property name should be mapreduce.map.class and mapreduce.reduce.class instead of mapreduce.mapper.class and mapreduce.reducer.class correspondingly. So modified workflow should have these properties.
<property>
<name>mapreduce.map.class</name>
<value>Drivers.WordCount$WordMap</value>
</property>
<property>
<name>mapreduce.reduce.class</name>
<value>Drivers.WordCount$RedForSum</value>
</property>
For more on this please refere here

Endpoint Publish for REST Web Services

I've published JAX-WS web services with Endpoint.publish during development. Is there any such utility class exists (in JAX-RS) for publishing REST web services in jersey? I referred couple of articles, and majority of them are based on publishing the web services in some containers like Jetty, Grizzly etc.
Jersey-Grizzly has a very simple solution. From https://github.com/jesperfj/jax-rs-heroku:
package embedded.rest.server;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;
#Path("/hello")
public class Main {
public static void main(String[] args) {
final String baseUri = "http://localhost:7080/";
final Map<String, String> initParams = new HashMap<String, String>();
// Register the package that contains your javax.ws.rs-annotated beans here
initParams.put("com.sun.jersey.config.property.packages","embedded.rest.server");
System.out.println("Starting grizzly...");
try {
SelectorThread threadSelector =
GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(String.format("Jersey started with WADL "
+ "available at %sapplication.wadl.", baseUri));
}
catch(Exception e) {
e.printStackTrace();
}
}
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Well, this was easy!";
}
}
If you're using Maven, you'll need the following three dependencies:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>com.sun.grizzly</groupId>
<artifactId>grizzly-servlet-webserver</artifactId>
<version>1.9.18-i</version>
</dependency>
To test it, just open http://localhost:7080/hello in a browser.
I think you can use Provider interface to publishing a RESTful Web Service with JAX-WS.
The example class:
#WebServiceProvider
#BindingType(value=HTTPBinding.HTTP_BINDING)
public class AddNumbersImpl implements Provider {
#Resource
protected WebServiceContext wsContext;
public Source invoke(Source source) {
try {
MessageContext mc = wsContext.getMessageContext();
// check for a PATH_INFO request
String path = (String)mc.get(MessageContext.PATH_INFO);
if (path != null && path.contains("/num1") &&
path.contains("/num2")) {
return createResultSource(path);
}
String query = (String)mc.get(MessageContext.QUERY_STRING);
System.out.println("Query String = "+query);
ServletRequest req = (ServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
int num1 = Integer.parseInt(req.getParameter("num1"));
int num2 = Integer.parseInt(req.getParameter("num2"));
return createResultSource(num1+num2);
} catch(Exception e) {
e.printStackTrace();
throw new HTTPException(500);
}
}
private Source createResultSource(String str) {
StringTokenizer st = new StringTokenizer(str, "=&/");
String token = st.nextToken();
int number1 = Integer.parseInt(st.nextToken());
st.nextToken();
int number2 = Integer.parseInt(st.nextToken());
int sum = number1+number2;
return createResultSource(sum);
}
private Source createResultSource(int sum) {
String body =
"<ns:addNumbersResponse xmlns:ns="http://java.duke.org"><ns:return>"
+sum
+"</ns:return></ns:addNumbersResponse>";
Source source = new StreamSource(
new ByteArrayInputStream(body.getBytes()));
return source;
}
}
To deploy our endpoint on a servlet container running with the JAX-WS
RI we need to create a WAR file.
The adjusted web.xml:
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener>
<servlet>
<servlet-name>restful-addnumbers</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>restful-addnumbers</servlet-name>
<url-pattern>/addnumbers/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
and need to add sun-jaxws.xml deployment descriptor to the WAR file.
<endpoints
xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint
name="restful-addnumbers"
implementation="restful.server.AddNumbersImpl"
wsdl="WEB-INF/wsdl/AddNumbers.wsdl"
url-pattern="/addnumbers/*" />
</endpoints>
Or could be create simple HttpServer
import java.io.IOException;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;
public class YourREST {
static final String BASE_URI = "http://localhost:9999/yourrest/";
public static void main(String[] args) {
try {
HttpServer server = HttpServerFactory.create(BASE_URI);
server.start();
System.out.println("Press Enter to stop the server. ");
System.in.read();
server.stop(0);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

IBM JAX-RPC web service : Though the response is Boolean we are getting a number in the output

We have a generated webservice based on WSDL using JAX-RPC, in WSDL we have response like below
<element name="notificationsResponse">
<complexType>
<sequence>
<element name="Ack" type="xsd:boolean"/>
</sequence>
</complexType>
</element>
</schema>
Even the generated code has the method return type as Boolean
public boolean notificationXXXXX(java.lang.String XXXX,
java.lang.String XXXX, java.lang.String XXXX)
But when we invoke the service from Soap UI, we are seeing the response 'Ack' as 0, 1 not as true / false. This was working fine with JAX-WS.
Any help on this is highly appreciated
I have solved it using Handlers. Handlers can be added to webservices.xml file as below
<webservice-description>
<webservice-description-name>XXXXXXXXXXXX</webservice-description-name>
<wsdl-file>WEB-INF/wsdl/XXXXXXXXXXXXX.wsdl</wsdl-file>
<jaxrpc-mapping-file>WEB-INF/XXXXXXXXXXX.xml</jaxrpc-mapping-file>
<port-component>
<port-component-name>XXXXXXXXXX</port-component-name>
<wsdl-port xmlns:pfx="http://XXXXX">pfx:XXXXX</wsdl-port>
<service-endpoint-interface>XXXXXXXXX</service-endpoint-interface>
<service-impl-bean>
<servlet-link>XXXXXXXXXXXX</servlet-link>
</service-impl-bean>
**<handler id="Handler_1066493401322">
<handler-name>com.a.b.ResponseHandler</handler-name>
<handler-class>com.a.b.ResponseHandler</handler-class>
</handler>**
</port-component>
</webservice-description>
Handler class should override handleResponse() method to intercept the response
import java.util.Date;
import java.util.Iterator;
import javax.xml.namespace.QName;
import javax.xml.rpc.handler.GenericHandler;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.handler.soap.SOAPMessageContext;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import org.w3c.dom.NodeList;
import com.ibm.ws.webcontainer.srt.SRTServletResponse;
public class ResponseHandler extends GenericHandler {
protected HandlerInfo info = null;
public boolean handleResponse(MessageContext context) {
try {
SOAPMessageContext smc = (SOAPMessageContext) context;
SOAPMessage message = smc.getMessage();
SOAPBody sb = message.getSOAPBody();
NodeList nl = sb.getChildNodes();
nl= sb.getChildNodes().item(0).getChildNodes().item(0).getChildNodes();
String responseValue = nl.item(0).getNodeValue();
System.out.println("Received response value is"+ responseValue);
if("1".equals(responseValue))
{
System.out.println(" Setting the response value to true");
nl.item(0).setNodeValue("true");
}
else
{
System.out.println(" Setting the response value to false");
nl.item(0).setNodeValue("false");
}
} catch (Exception x) {
// insert error handling here
x.printStackTrace();
}
return true;
}
/* (non-Javadoc)
* #see javax.xml.rpc.handler.Handler#getHeaders()
*/
public QName[] getHeaders() {
return info.getHeaders();
}
public void init(HandlerInfo arg) {
info = arg;
}
public void destroy() {
}
}
According to XML Schema Datatypes specification, Boolean may have 4 values:
booleanRep ::= 'true' | 'false' | '1' | '0'

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;
}
}

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.