getting error in oozie job - mapreduce

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

Related

Spring Trace Id and Span ID in GCP Cloud Run request log

I am using spring cloud GCP logging and trace in my GCP cloud run application
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<include resource="org/springframework/cloud/gcp/logging/logback-appender.xml"/>
<root level="INFO">
<appender-ref ref="STACKDRIVER"/>
</root>
</configuration>
After adding this I can see that logs are grouped
Now I have two questions
Can we have the trace ID and and span ID printed in the request log it self.
After adding stack driver, the spring default console pattern is not shown. All the logs are printed in raw format. They do not have thread-name, span id, appName etc.
Can these two be achieved?
Update
Trying to enhance the log
#Component
public class NukTraceIdLoggingEnhancer extends TraceIdLoggingEnhancer {
#Override
public void enhanceLogEntry(LogEntry.Builder builder) {
super.enhanceLogEntry(builder);
LogEntry.Builder newDummyBuilder = builder;
LogEntry logEntry = newDummyBuilder.build();
Payload<?> payload = logEntry.getPayload();
if (logEntry.getPayload() instanceof JsonPayload) {
JsonPayload jsonPayload = (JsonPayload) payload;
String content = (String) ((JsonPayload) payload).getDataAsMap().get("message");
content = "abc" + logEntry.getSpanId() + ", " + logEntry.getTrace() + content;
jsonPayload.getDataAsMap().replace("message", content);
builder.setPayload(jsonPayload);
}
}
#Override
public void enhanceLogEntry(LogEntry.Builder builder, ILoggingEvent e) {
super.enhanceLogEntry(builder, e);
LogEntry.Builder newDummyBuilder = builder;
LogEntry logEntry = newDummyBuilder.build();
Payload<?> payload = logEntry.getPayload();
if (logEntry.getPayload() instanceof JsonPayload) {
JsonPayload jsonPayload = (JsonPayload) payload;
String content = (String) ((JsonPayload) payload).getDataAsMap().get("message");
content = "XYZ" + logEntry.getSpanId() + ", " + logEntry.getTrace() + content;
jsonPayload.getDataAsMap().replace("message", content);
builder.setPayload(jsonPayload);
}
}
}
logback-spring.xml
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<property name="STACKDRIVER_LOG_NAME" value="${STACKDRIVER_LOG_NAME:-spring.log}"/>
<property name="STACKDRIVER_LOG_FLUSH_LEVEL" value="${STACKDRIVER_LOG_FLUSH_LEVEL:-WARN}"/>
<appender name="MY_STACKDRIVER" class="com.google.cloud.spring.logging.LoggingAppender">
<log>${STACKDRIVER_LOG_NAME}</log> <!-- Optional : default spring.log -->
<loggingEventEnhancer>abc.configuration.NukTraceIdLoggingEnhancer</loggingEventEnhancer>
<flushLevel>INFO</flushLevel> <!-- Optional : default ERROR -->
</appender>
<root level="INFO">
<appender-ref ref="MY_STACKDRIVER"/>
</root>
</configuration>

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>

Wso2ESB: Call Rest API through Entitlement policy from client producing CORS issue

I am facing Cross origin issue when tried to call a ESB Rest API which has Entitlement policy. Please find the below client call, ESB API, and Handler.
Ajax call:
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer 5d8ce0224d82cca7fb55fdcf4015b67');
},
withCredentials: true,
dataType: "json",
type: 'GET',
url: relativeURL+"/test,
},
success: function(json)
{}});
ESB API Configuration
<api xmlns="http://ws.apache.org/ns/synapse" name="CustomerApi" context="/CustomerApi">
<resource methods="POST GET OPTIONS DELETE PUT">
<inSequence>
<log level="custom">
<property name="Message Flow" value="Customer Search API - IN"> </property>
<property name="HTTP_METHOD IS###########" expression="$axis2:HTTP_METHOD"></property>
<property name="ip address" expression="get-property('axis2','REMOTE_ADDR')"></property>
</log>
<property name="Authorization" expression="get-property('transport','Authorization')"></property>
<property name="Access-Control-Allow-Credentials" value="true" scope="transport"></property>
<property name="Access-Control-Allow-Headers" value="authorization,Access-Control-Allow-Origin,Content-Type,origin,accept,X-Requested-With" scope="transport"></property>
<property name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" scope="transport"></property>
<property name="Access-Control-Allow-Origin" value="*" scope="transport"></property>
<property name="xacml_use_rest" value="true" scope="axis2" type="STRING"></property>
<property name="xacml_resource_prefix" value="/api/customers" scope="axis2"></property>
<property name="xacml_resource_prefix_only" value="true" scope="axis2"></property>
<property name="TIME_IN" expression="get-property('SYSTEM_TIME')" scope="default" type="LONG"></property>
<log level="custom">
<property name="Authorization.........." expression="get-property('transport','Authorization')"></property>
</log>
<entitlementService remoteServiceUrl="https://localhost:9444/services" remoteServiceUserName="admin" remoteServicePassword="enc:kuv2MubUUveMyv6GeHrXr9il59ajJIqUI4eoYHcgGKf/BBFOWn96NTjJQI+wYbWjKW6r79S7L7ZzgYeWx7DlGbff5X3pBN2Gh9yV0BHP1E93QtFqR7uTWi141Tr7V7ZwScwNqJbiNoV+vyLbsqKJE7T3nP8Ih9Y6omygbcLcHzg=" callbackClass="org.wso2.carbon.identity.entitlement.mediator.callback.UTEntitlementCallbackHandler" client="basicAuth">
<onReject>
<log level="custom">
<property name="Message Flow" value="REJECTED# Dobbies"></property>
</log>
<property name="HTTP_SC" value="401" scope="axis2" type="STRING"></property>
<payloadFactory media-type="xml">
<format>
<oatherizationresponse xmlns="">Not Authorized </oatherizationresponse>
</format>
<args></args>
</payloadFactory>
<respond></respond>
</onReject>
<onAccept>
<log level="custom">
<property name="Message Flow" value="ACCEPTED# Dobbies"></property>
</log>
<property name="Authorization" expression="fn:concat('Basic ', base64Encode('test:test'))" scope="transport"></property>
<send>
<endpoint>
<address uri="/api/customers/"></address>
</endpoint>
</send>
<property name="TIME_OUT" expression="get-property('SYSTEM_TIME')" scope="default" type="LONG"></property>
<script language="js">var time1 = mc.getProperty("TIME_IN");var time2 = mc.getProperty("TIME_OUT");var timeTaken = time2 - time1;mc.setProperty("RESPONSE_TIME", timeTaken);</script>
<log level="custom">
<property name="Time Duration in ms:" expression="get-property('RESPONSE_TIME') "></property>
</log>
</onAccept>
<obligations></obligations>
<advice></advice>
</entitlementService>
</inSequence>
<outSequence>
<send></send>
</outSequence>
</resource>
<handlers>
<handler class="org.wso2.handler.SimpleOauthHandlerNew">
</handler>
</handlers
</api>
SimpleOauthHandlerNew:
package org.wso2.handler;
import java.util.Map;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.apache.http.HttpHeaders;
import org.apache.synapse.ManagedLifecycle;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;
import org.wso2.carbon.identity.oauth2.stub.OAuth2ServiceStub;
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO;
public class SimpleOauthHandlerNew extends AbstractHandler implements ManagedLifecycle {
private String securityHeader = HttpHeaders.AUTHORIZATION;
private String consumerKeyHeaderSegment = "Bearer";
private String oauthHeaderSplitter = ",";
private String consumerKeySegmentDelimiter = " ";
private String oauth2TokenValidationService = "oauth2TokenValidationService";
private String identityServerUserName = "identityServerUserName";
private String identityServerPw = "identityServerPw";
private String oAuth2Service = "oauth2Service";
#Override
public boolean handleRequest(MessageContext messageContext) {
try{
ConfigurationContext configCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
//Read parameters from axis2.xml
String identityServerUrl = messageContext.getConfiguration().getAxisConfiguration().getParameter(oauth2TokenValidationService).getValue().toString();
String username = messageContext.getConfiguration().getAxisConfiguration().getParameter(identityServerUserName).getValue().toString();
String password = messageContext.getConfiguration().getAxisConfiguration().getParameter(identityServerPw).getValue().toString();
OAuth2TokenValidationServiceStub stub = new OAuth2TokenValidationServiceStub(configCtx,identityServerUrl);
String oauth2ServiceUrl = messageContext.getConfiguration().getAxisConfiguration().getParameter(oAuth2Service).getValue().toString();
OAuth2ServiceStub oAuth2ServiceStub = new OAuth2ServiceStub(configCtx,oauth2ServiceUrl);
ServiceClient client = stub._getServiceClient();
Options options = client.getOptions();
HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();
authenticator.setUsername(username);
authenticator.setPassword(password);
authenticator.setPreemptiveAuthentication(true);
options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
client.setOptions(options);
OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO();
// dto.set("bearer");
Map headers = (Map) ((Axis2MessageContext) messageContext).getAxis2MessageContext().
getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
String apiKey = null;
if (headers != null) {
apiKey = extractCustomerKeyFromAuthHeader(headers);
}
OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
accessToken.setTokenType("bearer");
accessToken.setIdentifier(apiKey);
dto.setAccessToken(accessToken);
//validate passed apiKey(token)
if (stub.validate(dto).getValid()) {
String user = stub.validate(dto).getAuthorizedUser();
System.out.println(">>>>>>>>>"+user);
user = user.substring(0, user.indexOf('#'));
System.out.println(">>>>>>>>>"+user);
org.apache.axis2.context.MessageContext msgContext;
Axis2MessageContext axis2Msgcontext = null;
axis2Msgcontext = (Axis2MessageContext) messageContext;
msgContext = axis2Msgcontext.getAxis2MessageContext();
msgContext.setProperty("username", user);
return true;
}else{
return false;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
}
public String extractCustomerKeyFromAuthHeader(Map headersMap) {
String authHeader = (String) headersMap.get(securityHeader);
if (authHeader == null) {
return null;
}
if (authHeader.startsWith("OAuth ") || authHeader.startsWith("oauth ")) {
authHeader = authHeader.substring(authHeader.indexOf("o"));
}
String[] headers = authHeader.split(oauthHeaderSplitter);
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
String[] elements = headers[i].split(consumerKeySegmentDelimiter);
if (elements != null && elements.length > 1) {
int j = 0;
boolean isConsumerKeyHeaderAvailable = false;
for (String element : elements) {
if (!"".equals(element.trim())) {
if (consumerKeyHeaderSegment.equals(elements[j].trim())) {
isConsumerKeyHeaderAvailable = true;
} else if (isConsumerKeyHeaderAvailable) {
return removeLeadingAndTrailing(elements[j].trim());
}
}
j++;
}
}
}
}
return null;
}
private String removeLeadingAndTrailing(String base) {
String result = base;
if (base.startsWith("\"") || base.endsWith("\"")) {
result = base.replace("\"", "");
}
return result.trim();
}
#Override
public boolean handleResponse(MessageContext messageContext) {
return true;
}
#Override
public void init(SynapseEnvironment synapseEnvironment) {
}
#Override
public void destroy() {
}
}
In browser im getting
XMLHttpRequest cannot load /CustomerApi?limit=10&offset=0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://172.250.46.250:8095' is therefore not allowed access.
Please provide me a solution to call the Rest end point from the client. Thanks in advance.
It's ages since this question is asked but not answered.
I had the same issue and was stuck with it for few days and thought adding my findings.
One way to add CORS support is to expose your API via WSO2 API Manager and configure CORS support there
https://docs.wso2.com/display/AM200/Enabling+CORS+for+APIs
With WSO2 EI, easiest way to add CORS support for your API is to set a HTTP header before the response is sent back.
Eg:
<header description="CORS" name="Access-Control-Allow-Origin" scope="transport" value="*"/>

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.