A try to call two CXF-2.5.0 dynamic clients fails with:
org.apache.cxf.interceptor.Fault: Marshalling Error: net.webservicex.GetWeather is not known to this context
package my.test;
import javax.xml.namespace.QName;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class TwoDynClients {
public static void main(String[] args) throws Exception {
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client clientA = dcf.createClient("http://www.webservicex.net/stockquote.asmx?WSDL");
Object[] resultA = clientA.invoke(new QName("http://www.webserviceX.NET/", "GetQuote"), "GOOG");
System.out.println("resultA: " + resultA[0]);
Client clientB = dcf.createClient("http://www.webservicex.net/GlobalWeather.asmx?wsdl");
Object[] resultB = clientB.invoke(new QName("http://www.webserviceX.NET", "GetWeather"), new Object[] {"Stuttgart", "Germany"} );
System.out.println("resultB: " + resultB[0]);
}
}
The output of snippet above is:
29.12.2011 9:37:12 org.apache.cxf.jaxb.JAXBUtils logGeneratedClassNames
INFO: Created classes: net.webservicex.GetQuote, net.webservicex.GetQuoteResponse, net.webservicex.ObjectFactory
resultA: <StockQuotes><Stock><Symbol>GOOG</Symbol><Last>639.70</Last><Date>12/28/2011</Date><Time>4:00pm</Time><Change>0.00</Change><Open>N/A</Open><High>N/A</High><Low>N/A</Low><Volume>0</Volume><MktCap>207.2B</MktCap><PreviousClose>639.70</PreviousClose><PercentageChange>0.00%</PercentageChange><AnnRange>473.02 - 645.00</AnnRange><Earns>29.337</Earns><P-E>21.81</P-E><Name>Google Inc.</Name></Stock></StockQuotes>
29.12.2011 9:37:22 org.apache.cxf.jaxb.JAXBUtils logGeneratedClassNames
INFO: Created classes: net.webservicex.GetCitiesByCountry, net.webservicex.GetCitiesByCountryResponse, net.webservicex.GetWeather, net.webservicex.GetWeatherResponse, net.webservicex.ObjectFactory
29.12.2011 9:37:24 org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://www.webserviceX.NET}GlobalWeather#{http://www.webserviceX.NET}GetWeather has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Marshalling Error: net.webservicex.GetWeather is not known to this context
at org.apache.cxf.jaxb.JAXBEncoderDecoder.marshall(JAXBEncoderDecoder.java:261)
When order of clients is changed the second fails.
Is it OK to use one JaxWsDynamicClientFactory to create both clients?
Answer from Daniel Kulp is here How to call 2 CXF dynamic clients?
ClassLoader cl = Thread.currentThread().getContextClassloader();
JaxWsDynamicClientFactory dcf =
JaxWsDynamicClientFactory.newInstance();
Client clientA = dcf.createClient(".....");
Thread.currentThread().setContextClassloader(cl);
dcf = JaxWsDynamicClientFactory.newInstance();
Client clientB = dcf.createClient(".....");
Related
Hi I have complex camel route and in between the route I am sending mesage to MQ using Bean.
.bean("{{tp.mqservice}}")
application.yaml
mqservice: bean:mqService
application-test.yaml
mqservice: mock:result
Below is my PortfolioRouteTest
#ActiveProfiles("test")
#RunWith(CamelSpringBootRunner.class)
#SpringBootTest(classes = MainApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
#MockEndpoints
public class PortfolioTncRouteTest {
#EndpointInject(value = "{{trade-publisher.portfolio-tnc.source-endpoint}}")
private ProducerTemplate producerTemplate;
#EndpointInject(value = "{{trade-publisher.mqservice}}")
private MockEndpoint mock;
}
Junit
#Test
public void portfolioTncRouteTest() throws InterruptedException {
data = ...
Mockito.when(service.search(Mockito.any(....class))).thenReturn(...);
producerTemplate.sendBody(data);
mock.expectedMessageCount(1);
mock.assertIsSatisfied(30000);
}
however when I run the test I am getting below error. Am I missing something?
Stacktrace
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: mock:result
at org.apache.camel.component.bean.RegistryBean.getBean(RegistryBean.java:92)
at org.apache.camel.component.bean.RegistryBean.createCacheHolder(RegistryBean.java:67)
at org.apache.camel.reifier.BeanReifier.createProcessor(BeanReifier.java:57)
at org.apache.camel.reifier.ProcessorReifier.createProcessor(ProcessorReifier.java:485)
at org.apache.camel.reifier.ProcessorReifier.createOutputsProcessorImpl(ProcessorReifier.java:448)
at org.apache.camel.reifier.ProcessorReifier.createOutputsProcessor(ProcessorReifier.java:415)
at org.apache.camel.reifier.ProcessorReifier.createOutputsProcessor(ProcessorReifier.java:212)
at org.apache.camel.reifier.ExpressionReifier.createFilterProcessor(ExpressionReifier.java:39)
at org.apache.camel.reifier.WhenReifier.createProcessor(WhenReifier.java:32)
at org.apache.camel.reifier.WhenReifier.createProcessor(WhenReifier.java:24)
at org.apache.camel.reifier.ProcessorReifier.createProcessor(ProcessorReifier.java:485)
at org.apache.camel.reifier.ChoiceReifier.createProcessor(ChoiceReifier.java:54)
at org.apache.camel.reifier.ProcessorReifier.createProcessor(ProcessorReifier.java:485)
at org.apache.camel.reifier.ProcessorReifier.createOutputsProcessorImpl(ProcessorReifier.java:448)
at org.apache.camel.reifier.ProcessorReifier.createOutputsProcessor(ProcessorReifier.java:415)
at org.apache.camel.reifier.TryReifier.createProcessor(TryReifier.java:38)
at org.apache.camel.reifier.ProcessorReifier.createProcessor(ProcessorReifier.java:485)
at org.apache.camel.reifier.ProcessorReifier.createOutputsProcessorImpl(ProcessorReifier.java:448)
at org.apache.camel.reifier.ProcessorReifier.createOutputsProcessor(ProcessorReifier.java:415)
at org.apache.camel.reifier.ProcessorReifier.createOutputsProcessor(ProcessorReifier.java:212)
at org.apache.camel.reifier.ProcessorReifier.createChildProcessor(ProcessorReifier.java:231)
at org.apache.camel.reifier.SplitReifier.createProcessor(SplitReifier.java:42)
at org.apache.camel.reifier.ProcessorReifier.makeProcessorImpl(ProcessorReifier.java:536)
at org.apache.camel.reifier.ProcessorReifier.makeProcessor(ProcessorReifier.java:497)
at org.apache.camel.reifier.ProcessorReifier.addRoutes(ProcessorReifier.java:241)
at org.apache.camel.reifier.RouteReifier.addRoutes(RouteReifier.java:358)
... 56 more
Use .to instead of .bean so its sending to a Camel endpoint, then you can send to the mock endpoint. When using .bean then its for calling a POJO Java bean only.
Hello everyware i'm envelop an application for extract data from local ip database, where application start the application crash at press button from extract an article, the interessing code error is a subcall at mainactivity2:
public List<String> getAllLabels(){
List<String> labels = new ArrayList();
String selectQuery = "SELECT * FROM " + KEY_ARTICOLO;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
}while (cursor.moveToNext());
}
return labels;
}
Error is:
Process: spa.a1926.federighi.blancmariclo, PID: 8203
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference
at spa.a1926.federighi.blancmariclo.MainActivity2$GestioneDB.getAllLabels(MainActivity2.java:131)
at spa.a1926.federighi.blancmariclo.MainActivity2$1.onClick(MainActivity2.java:50)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
10-30 10:53:22.815 1536-3316/system_process E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
10-30 10:53:22.815 1536-3316/system_process E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
The call in main(mainactivity2) is:
public void onClick(View view) {
GestioneDB db = new GestioneDB(getApplicationContext());
List<String> parolemenu = db.getAllLabels();
ArrayAdapter dataAdapter = new ArrayAdapter(MainActivity2.this, android.R.layout.simple_spinner_item, parolemenu);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
});
I have following processor, when I run it from my route I get the following error. I know exchange body is not null and you can see it in logs below. What is wrong with my usage of SimpleBuilder here ?
public class UpdateCustomerProcessor implements Processor {
public static final Logger log = LoggerFactory.getLogger(UpdateCustomerProcessor.class);
public void process(Exchange exchng) throws Exception {
Customer c = (Customer) exchng.getIn().getBody(Object[].class)[0];
System.out.println("Updating customer " + c.getFirstName() + " " + c.getLastName());
System.out.println(SimpleBuilder.simple("Hello ${body.getFirstName()}").evaluate(exchng, String.class));
exchng.getOut().setBody(new Object[] {});
}
}
log->Updating customer aaa bbb
error-> org.apache.cxf.interceptor.Fault: Failed to invoke method: .getFirstName() on null due to: org.apache.camel.language.bean.RuntimeBeanExpressionException: Failed to invoke method: getFirstName() on null
I can't make sense of the "null"-exception, since exchange in appears to be filled. Nevertheless, your expression looks incorrect - since your exchange.in seems to hold an array, it should be:
SimpleBuilder.simple("Hello ${body[0].firstname}").evaluate(exchng, String.class))
System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The remote name could not be resolved: 'mailrelay'
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailSender.PerformDelivery(IMessage message)
below is my code
mail = new MailMessage();
string[] toAddresses = email.To.EmailAddress.Split(new char[] { ';' });
foreach (string toAddress in toAddresses)
{
if (!string.IsNullOrEmpty(toAddress.Trim()))
{
mail.To.Add(new MailAddress(toAddress));
}
}
string[] ccAddresses = email.CcEmail.Split(new char[] { ';' });
foreach (string ccAddress in ccAddresses)
{
if (!string.IsNullOrEmpty(ccAddress.Trim()))
{
mail.CC.Add(new MailAddress(ccAddress));
}
}
string[] bccAddresses = email.BccEmail.Split(new char[] { ';' });
foreach (string bccAddress in bccAddresses)
{
if (!string.IsNullOrEmpty(bccAddress.Trim()))
{
mail.Bcc.Add(new MailAddress(bccAddress));
}
}
mail.From = new MailAddress(email.From.EmailAddress,email.From.FullName);
mail.Subject = email.Subject;
mail.Body = email.Body;
if (email.Body.Contains("<html>"))
{
mail.IsBodyHtml = true;
}
if (!email.ExcludeAttachment && !string.IsNullOrEmpty(email.AttachmentPath))
mail.Attachments.Add(new Attachment(email.AttachmentPath));
client = new SmtpClient();
client.Host = ConfigurationSettings.AppSettings["SmtpServer"].ToString();
client.Send(mail);
It looks like ConfigurationSettings.AppSettings["SmtpServer"].ToString() is returning "mailrelay"
Check your AppSettings (normally in web.config), find the SmtpServer setting and change it to a machine name, ip address or domain name that is a mail relay that will accept emails from your app (most mail relays are secured to prevent spammers using them).
If "mailrelay" does work on your dev machine, ping it and find out what IP address it is resolving to. It needs to resolve to a machine that your other environment can see too. If it's a local test machine, then chances are that a production server in a hosting environment can't access it.
I am trying to set receiveTimeout and connection timeout for cxfEndpoint in below code .. I got so many spring dsl related answer but i am using camel dsl specifically.
I am trying to set receiveTimeout and connection timeout for cxfEndpoint in below code .. I got so many spring dsl related answer but i am using camel dsl specifically.
I am trying to set receiveTimeout and connection timeout for cxfEndpoint in below code .. I got so many spring dsl related answer but i am using camel dsl specifically.
I am trying to set receiveTimeout and connection timeout for cxfEndpoint in below code .. I got so many spring dsl related answer but i am using camel dsl specifically.
void configure() throws Exception {
super.configure()
CamelContext context=getContext()
String version=context.resolvePropertyPlaceholders('{{'+ CommonConstants.VERSION_PROPERTY+ '}}')
String region=context.resolvePropertyPlaceholders('{{'+ CommonConstants.REGION_PROPERTY + '}}')
String getContextRoot=context.resolvePropertyPlaceholders('{{' + CommonConstants.CONTEXT_ROOT_PROPERTY + '}}')
boolean validateResponse=getContextRoot
//main route exposing a GET
rest("/$version/$region/")
.get("/$getContextRoot")
.produces('application/json')\
.to('direct:validate')
from('direct:validate')
.routeId('validate')
.bean(ValidatorSubRouteHelper.class,'validate')
.to('direct:get-deviceIdentification')
from('direct:get-deviceIdentification')
.routeId('get-deviceIdentification')
//pre-processing closure
.process {
it.out.body = [ it.properties[MessageReferenceConstants.USER_AGENT_HEADER], new CallContext() ]
it.in.headers[CxfConstants.OPERATION_NAME] = context.resolvePropertyPlaceholders('{{'+MessageReferenceConstants.PROPERTY_OPERATION_NAME+'}}')
it.in.headers[Exchange.SOAP_ACTION] = context.resolvePropertyPlaceholders('{{'+MessageReferenceConstants.PROPERTY_SOAP_ACTION+'}}')
Map<String, Object> reqCtx = new HashMap<String, Object>();
HTTPClientPolicy clientHttpPolicy = new HTTPClientPolicy();
clientHttpPolicy.setReceiveTimeout(10000);
reqCtx.put(HTTPClientPolicy.class.getName(), clientHttpPolicy)
it.in.headers[Client.REQUEST_CONTEXT]=reqCtx
}
.to(getEndpointURL())
//In case of SOAPFault from device, handling the exception in processSOAPResponse
.onException(SoapFault.class)
.bean(ProcessResponseExceptionHelper.class,"processSOAPResponse")
.end()
//post-processing closure
.process {
log.info("processing the response retrieved from device service")
MessageContentsList li = it.in.getBody(MessageContentsList.class)
DeviceFamily deviceFamily = (DeviceFamily) li.get(0)
log.debug('device type is '+deviceFamily.deviceType.value)
it.properties[MessageReferenceConstants.PROPERTY_RESPONSE_BODY] = deviceFamily.deviceType.value
}.to('direct:transform')
from('direct:transform')
.routeId('transform')
//transform closure
.process {
log.info("Entering the FilterTransformSubRoute(transform)")
Device device=new Device()
log.debug('device type '+it.properties[MessageReferenceConstants.PROPERTY_RESPONSE_BODY])
device.familyName = it.properties[MessageReferenceConstants.PROPERTY_RESPONSE_BODY]
it.out.body=device
}
.choice()
.when(simple('{{validateResponse}}'))
.to('direct:validateResponse')
if(validateResponse) {
from('direct:validateResponse')
.bean(DataValidator.getInstance('device.json'))
}
}
/**
* Constructs the endpoint url.
* Formatting end point URL for device identification service call
* #return the endpoint url
*/
private String getEndpointURL() {
CamelContext context=getContext()
def serviceURL=context.resolvePropertyPlaceholders('{{'+MessageReferenceConstants.SERVICE_URL+'}}')
def wsdlURL=context.resolvePropertyPlaceholders('{{'+MessageReferenceConstants.WSDL_URL+'}}')
boolean isGZipEnable=CommonConstants.TRUE.equalsIgnoreCase(context.resolvePropertyPlaceholders('{{'+MessageReferenceConstants.GZIP_ENABLED+'}}'))
def serviceClass = context.resolvePropertyPlaceholders('{{'+MessageReferenceConstants.PROPERTY_SERVICE_CLASS+'}}')
def serviceName = context.resolvePropertyPlaceholders('{{'+MessageReferenceConstants.PROPERTY_SERVICE_NAME+'}}')
def url="cxf:$serviceURL?"+
"wsdlURL=$wsdlURL"+
"&serviceClass=$serviceClass"+
"&serviceName=$serviceName"
if(isGZipEnable) {
url+= "&cxfEndpointConfigurer=#deviceIdentificationServiceCxfConfigurer"
}
log.debug("endpoint url is " + url)
url
}
You already find a the cxfEndpointConfigurer option for it.
Now you just need implement the configurer interface like this:
public static class MyCxfEndpointConfigurer implements CxfEndpointConfigurer {
#Override
public void configure(AbstractWSDLBasedEndpointFactory factoryBean) {
// Do nothing here
}
#Override
public void configureClient(Client client) {
// reset the timeout option to override the spring configuration one
HTTPConduit conduit = (HTTPConduit) client.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
// You can setup the timeout option here
policy.setReceiveTimeout(60000);
policy.setConnectionTimeout(30000);
conduit.setClient(policy);
}
#Override
public void configureServer(Server server) {
// Do nothing here
}
}