I want to send a request over TCP transport to a proxy service, when use this code to send my soap xml
Socket clientSocket = new Socket("host", port);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("soap xml instance");
clientSocket.close();
it works fine and my business is continues.
But when i send two xml without closing the socket like this:
Socket clientSocket = new Socket("host", port);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("soap xml instance");
outToServer.writeBytes("another soap instance");
clientSocket.close();
it always throws this exception:
TID: [0] [ESB] [2013-06-28 13:36:10,838] ERROR
{org.apache.axis2.transport.tcp.TCPWorker} - Error while processing
TCP request through the Axis2 engine
{org.apache.axis2.transport.tcp.TCPWorker}
org.apache.axiom.om.OMException:
com.ctc.wstx.exc.WstxParsingException: Illegal processing instruction
target ("xml"); xml (case insensitive) is reserved by the specs. at
[row,col {unknown-source}]: [2,5]
at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:296)
at org.apache.axiom.om.impl.llom.OMDocumentImpl.buildNext(OMDocumentImpl.java:135)
at org.apache.axiom.om.impl.llom.OMNodeImpl.getNextOMSibling(OMNodeImpl.java:122)
at org.apache.axiom.om.impl.llom.OMElementImpl.getNextOMSibling(OMElementImpl.java:343)
at org.apache.axiom.om.impl.traverse.OMChildrenIterator.getNextNode(OMChildrenIterator.java:36)
at org.apache.axiom.om.impl.traverse.OMAbstractIterator.hasNext(OMAbstractIterator.java:58)
at org.jaxen.util.DescendantAxisIterator.hasNext(DescendantAxisIterator.java:101)
at org.jaxen.expr.DefaultStep.evaluate(DefaultStep.java:152)
at org.jaxen.expr.DefaultLocationPath.evaluate(DefaultLocationPath.java:140)
at org.jaxen.expr.DefaultAbsoluteLocationPath.evaluate(DefaultAbsoluteLocationPath.java:113)
at org.jaxen.expr.DefaultXPathExpr.asList(DefaultXPathExpr.java:102)
at org.jaxen.BaseXPath.selectNodesForContext(BaseXPath.java:674)
at org.jaxen.BaseXPath.selectNodes(BaseXPath.java:213)
at org.jaxen.BaseXPath.evaluate(BaseXPath.java:172)
at org.apache.synapse.util.xpath.SynapseXPath.stringValueOf(SynapseXPath.java:297)
at org.apache.synapse.mediators.builtin.PropertyMediator.getResultValue(PropertyMediator.java:299)
at org.apache.synapse.mediators.builtin.PropertyMediator.mediate(PropertyMediator.java:95)
at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:71)
at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:114)
at org.apache.synapse.core.axis2.ProxyServiceMessageReceiver.receive(ProxyServiceMessageReceiver.java:154)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
at org.apache.axis2.transport.tcp.TCPWorker.run(TCPWorker.java:68)
at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662) Caused by: com.ctc.wstx.exc.WstxParsingException: Illegal processing instruction
target ("xml"); xml (case insensitive) is reserved by the specs. at
[row,col {unknown-source}]: [2,5]
at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.java:606)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:479)
at com.ctc.wstx.sr.BasicStreamReader.readPIPrimary(BasicStreamReader.java:3903)
at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2037)
at com.ctc.wstx.sr.BasicStreamReader.closeContentTree(BasicStreamReader.java:2886)
at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2629)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1062)
at org.apache.axiom.util.stax.wrapper.XMLStreamReaderWrapper.next(XMLStreamReaderWrapper.java:225)
at org.apache.axiom.util.stax.dialect.DisallowDoctypeDeclStreamReaderWrapper.next(DisallowDoctypeDeclStreamReaderWrapper.java:34)
at org.apache.axiom.util.stax.wrapper.XMLStreamReaderWrapper.next(XMLStreamReaderWrapper.java:225)
at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(StAXOMBuilder.java:681)
at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:214)
... 25 more
I used appending '\n', "\r\n" to my message but non of them make that work.
Also i tried that used the method that explined in this link.How to Send SOAP Messages Using TCP Transport and it worked fine.
But i could not use that kind of api in my project. How can i get rid of this problem.
I was able to send TCP messages to ESB using a sample client but you have to make sure you send an XML element.
First make sure you have enabled transport reciver for tcp in axis2.xml (repository/conf/axis2/axis2.xml)
<transportReceiver name="tcp" class="org.apache.axis2.transport.tcp.TCPTransportListener" >
========================My Proxy Service which recives TCP messages ===========
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="TCPProxy"
transports="https,http"
statistics="disable"
trace="disable"
startOnLoad="true">
<target>
<inSequence>
<log level="full"/>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
<parameter name="transport.tcp.port">6789</parameter>
<parameter name="transport.tcp.contentType">application/xml</parameter>
<description/>
</proxy>
==Client that send messages to TCP server ====
import java.io.*;
import java.net.*;
class TCPClient {
String host = "localhost";
int port = 6789;
Socket socket = null;
public static void main(String args[]) throws Exception{
String name ="Amani";
TCPClient client = new TCPClient();
String message = "<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\">\n" +
"<soapenv:Header/>\n" +
"<soapenv:Body>\n" +
" <p:greet xmlns:p=\"http://greet.service.amani.org\">\n" +
" <in>" + name + "</in>\n" +
" </p:greet>\n" +
"</soapenv:Body>\n" +
"</soapenv:Envelope>";
client.SendToServer("<test></test>");
client.close();
}
TCPClient(String _host, int _port) throws Exception{
host = _host;
port = _port;
socket = new Socket(host, port);
}
TCPClient() throws Exception{
socket = new Socket(host, port);
}
void SendToServer(String msg) throws Exception{
//create output stream attached to socket
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
//send msg to server
outToServer.print(msg + '\n');
outToServer.flush();
}
String RecieveFromServer() throws Exception{
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new InputStreamReader (socket.getInputStream()));
//read line from server
String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
return res;
}
void close() throws IOException{
socket.close();
}
}
Related
Im trying to connect to Kafka with JMS. I followed this guide to use the Payara Kafka Connector. This worked on Wildfly. But I cant get it to work on OpenLiberty.
The server.xml:
<resourceAdapter id="kafkajmsra" location="${shared.resource.dir}kafka-rar-0.5.0.rar"/>
<jmsTopicConnectionFactory jndiName="JMSTopicFactory">
<properties.kafkajmsra
bootstrapServerConfig="kafka:9092"/>
</jmsTopicConnectionFactory>
<jmsTopic id="kafkaTopic" jndiName="JmsTopic">
<properties.kafkajmsra topicName="demoTopic" />
</jmsTopic>
With those configurations I get a NullPointerException if I try to inject those components. The JNDI names can be found but not with these parameters.
#Resource(lookup = "JMSTopicFactory")
private TopicConnectionFactory jmsTopicFactory;
#Resource(lookup = "JMSTopic")
private Topic jmsTopic;
Am I missing something in the server.xml?
I tried using the default JMS Connector. It does connect to Kafka, but the connection gets refused and on the kafka side it tells me this:
[2020-05-31 20:05:27,134] WARN [SocketServer brokerId=1] Unexpected error from /172.20.0.4; closing connection (org.apache.kafka.common.network.Selector)
org.apache.kafka.common.network.InvalidReceiveException: Invalid receive (size = -1091633152)
at org.apache.kafka.common.network.NetworkReceive.readFrom(NetworkReceive.java:103)
at org.apache.kafka.common.network.KafkaChannel.receive(KafkaChannel.java:448)
at org.apache.kafka.common.network.KafkaChannel.read(KafkaChannel.java:398)
at org.apache.kafka.common.network.Selector.attemptRead(Selector.java:678)
at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:580)
at org.apache.kafka.common.network.Selector.poll(Selector.java:485)
at kafka.network.Processor.poll(SocketServer.scala:893)
at kafka.network.Processor.run(SocketServer.scala:792)
at java.lang.Thread.run(Thread.java:748)
EDIT:
I changed the server.xml to look like this now:
<resourceAdapter id="kafkajmsra" location="${shared.resource.dir}/kafka-rar-0.4.0.rar"/>
<connectionFactory jndi="java:app/KafkaConnectionFactory"
interfaceName="fish.payara.cloud.connectors.kafka.api.KafkaConnectionFactory"
resourceAdapter="liberty/wlp/usr/shared/resources/kafka-rar-0.4.0.rar">
</connectionFactory>
and the java code looks like this:
#ApplicationScoped
public class TopicProducer {
private static final Logger LOG = LoggerFactory.getLogger(TopicProducer.class);
public TopicProducer() throws Exception {
LOG.info("Starting TopicProducer");
}
#Resource(lookup = "java:app/KafkaConnectionFactory")
KafkaConnectionFactory kafkaConnectionFactory;
public void send(final String msg) {
try (KafkaConnection connection = kafkaConnectionFactory.createConnection()) {
LOG.info("Send message: {}", msg);
connection.send(new ProducerRecord("demoTopic", msg));
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
}
But now I get a NullPointerException on the #Resource. My guess is that the resource adapter cannot be found.
I am having trouble logging an outgoing SOAP message from the server. The handleMessage method does not overwrite the message content as expected. How would I store the outgoing SOAP to the message?
public class OutgoingSoapInterceptor extends AbstractPhaseInterceptor<Message> {
private static final Logger logger = LoggerFactory.getLogger(OutgoingSoapInterceptor.class.getName());
public OutgoingSoapInterceptor ()
{
super(Phase.PRE_STREAM);
}
#Override
public void handleMessage(Message message) throws Fault {
logger.debug("outbound soap handleMessage");
OutputStream os = message.getContent ( OutputStream.class );
CacheAndWriteOutputStream cwos = new CacheAndWriteOutputStream ( os);
message.setContent ( OutputStream.class, cwos );
cwos.registerCallback ( new LoggingOutCallBack ( ) );
}
}
There is a simpler way to log the SOAP messages using CXF LoggingInInterceptor and LoggingOutInterceptor
LogUtils.setLoggerClass(org.apache.cxf.common.logging.Log4jLogger.class);
yourService = new YourService(wsdlURL, SERVICE_NAME);
port = yourService.getServicePort();
Client client = ClientProxy.getClient(port);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
Or configuring interceptors in <cxf:bus> with spring
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/core
http://cxf.apache.org/schemas/core.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<cxf:bus>
<cxf:features>
<cxf:logging />
</cxf:features>
</cxf:bus>
<jaxws:endpoint ... />
</beans>
See more examples in How to log Apache CXF Soap Request and Soap Response using Log4j
I'm trying to send an email invoked from code.
#Stateless
public class MailBean {
private static Logger LOGGER = Logger.getLogger(MailBean.class);
private String EMAIL_REGEX = "^(([a-zA-Z0-9_\\-\\.]+)#([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\\-\\.]+)#([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+)*$";
#Resource(name = "java:jboss/mail/Default")
private Session mailSession;
#Asynchronous
public void send(String addresses, String topic, String textMessage) {
try {
MimeMessage message = new MimeMessage(mailSession);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));
message.setSubject(topic);
message.setText(textMessage);
Transport transport = mailSession.getTransport();
transport.connect();
transport.send(message);
} catch (MessagingException ex) {
LOGGER.error("Cannot send mail to " + addresses + ". Error: " + ex.getMessage(), ex);
}
}
public boolean isValidEmailAddress(String email) {
if (email == null)
return false;
else
return email.matches(EMAIL_REGEX);
}
}
My Wildfly 8.1 Server is configured as follows:
<subsystem xmlns="urn:jboss:domain:mail:2.0">
<mail-session name="mail-session-default" jndi-name="java:jboss/mail/Default">
<smtp-server outbound-socket-binding-ref="mail-smtp"
ssl="false"
username="john#doe.com"
password="****"/>
</mail-session>
</subsystem>
The socket outbound like this:
<outbound-socket-binding name="mail-smtp">
<remote-destination host="mail.doe.com" port="25"/>
<outbound-socket-binding>
The reported error is
(EJB default - 2) L:38 Cannot send mail to jane#doe.com. Error: 550 5.7.1 Command rejected
: com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Command rejected
As in the example I try to send an email from my account john#doe.com to jane#doe.com. Not to another domain.
On startup, wildfly does not report any errors with this configuration.
[org.jboss.as.mail.extension] (MSC service thread 1-5) L:136 JBAS015400: Bound mail session [java:jboss/mail/Default]
Any clue why that fails? In general I wonder why Java-Mail behaves not like a regular mail client.
Noting is wrong with your configuration or javamail implementation.
Just mail server is rejecting commands from you/your sever/...
There are many reason why mail server would do this, but in most cases all are related to preventing spam.
see related threads on SO about this as wel, and they are all related to mail server configuration.
for more see:
https://serverfault.com/questions/453638/plesk-postfix-smtp-550-5-7-1-command-rejected-for-one-external-sender
https://serverfault.com/questions/540159/remote-host-said-550-5-7-1-message-content-rejected
My Silverlight Client and REST Web Server(Implented using ASP.NET Handlers) both are on same domain.
Both HTTP and HTTPS protocol bindings are configured in IIS 7.0
When Request a URI using HTTPS , i Get Error " Message: "Security error."
But Same URI works just fine on HTTP request without any error
private void btnLoginWebRequest_Click(object sender, RoutedEventArgs e)
{
bool httpResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
bool httpsResult = WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
this.Dispatcher.BeginInvoke(()=>
{
WebClient webClient = new WebClient();
webClient.Headers["CustomHeader"] = String.Format("myHeaders={0}", "Value");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri(#"https://xxx.xx.xxx.xxx/MyRESTApi/UserGroups"));
});
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
}
}
I Get a Error and e.Error contains the following Error information
{System.Security.SecurityException: Security error.
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)}
[System.Security.SecurityException]: {System.Security.SecurityException: Security error.
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)}
Data: {System.Collections.ListDictionaryInternal}
InnerException: null
Message: "Security error."
StackTrace: " at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)\r\n at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)"
crossdomain.xml is as follows :-
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" secure="true"/>
<allow-http-request-headers-from domain="*" headers="*" secure="true"/>
</cross-domain-policy>
clientaccesspolicy.xml is as follows :-
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="https://"/>
<domain uri="http://"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
I Have seen many threads related to similar error on stack overflow but not able to resolve this issue by any of the solutions provided in those threads. Am i missing something?
I have a client which connects to a Web service to get some information. I have a requirement where I have to send the same information to multiple services using different ports. To solve this without modifying the client code I found MULE ESB, which is supposed to do exactly what I need.
I've found a guide where I could connect one client to one service using MULE ESB and one port, but I cant find a way to chain the services so they all listen to one port but have different themselves.
This is how it's supposed to look like:
UPDATE :
here is my current Mule Applications config :
<mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="CE-3.2.1" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd ">
<flow name="flows1Flow1" doc:name="flows1Flow1">
<http:inbound-endpoint exchange-pattern="request-response" address="http://localhost:4433/miniwebservice" mimeType="text/xml" doc:name="HTTP"/>
<http:outbound-endpoint exchange-pattern="request-response" address="http://localhost:4434/miniwebservice?wsdl" mimeType="text/xml" doc:name="HTTP"/>
</flow>
</mule>
Here is the WebService :
Client :
package miniwebservice;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class TestWsClient
{
public static void main( final String[] args ) throws Throwable
{
String url = ( args.length > 0 ) ? args[0] : "http://localhost:4434/miniwebservice";
Service service = Service.create(
new URL( url + "?wsdl" ),
new QName( "http://miniwebservice/", "HalloWeltImplService" ) );
HalloWelt halloWelt = service.getPort( HalloWelt.class );
System.out.println( "\n" + halloWelt.hallo( args.length > 1 ? args[1] : "" ) );
}
}
Server :
package miniwebservice;
import javax.xml.ws.Endpoint;
public class TestWsServer
{
public static void main( final String[] args )
{
String url = ( args.length > 0 ) ? args[0] : "http://localhost:4434/miniwebservice";
Endpoint.publish( url, new HalloWeltImpl() );
}
}
InterfaceImpl :
package miniwebservice;
import javax.jws.WebService;
#WebService( endpointInterface="miniwebservice.HalloWelt" )
public class HalloWeltImpl implements HalloWelt
{
public String hallo( String wer )
{
return "Hallo " + wer;
}
}
interface :
package miniwebservice;
import javax.jws.*;
#WebService
public interface HalloWelt
{
public String hallo( #WebParam( name = "wer" ) String wer );
}
If I start the Server and the Mule aplication and try to reach http://localhost:4434/miniwebservice?wsdl ower http://localhost:4433/miniwebservice I get the folowing Exception in my Browser (FireFox 8.0) :
Couldn't create SOAP message due to exception: XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.
I just started to work with Mule so I thouth that this would be enouth to get redirect mule to the Service to get the wsdl but its seems like its a bit complicatet.
Disclaimers:
This is not the final solution to the whole problem, which includes dispatching to several services and aggregating results, but a step in the right direction.
This is not representative of how web service proxying is done in Mule (which is way simpler) but a barebone approach to HTTP request routing so aggregation can be added.
Since you want to forward HTTP GET requests to the ?wsdl processor and HTTP POST SOAP request to the web service, you need to handle the target HTTP method and request URI propagation yourself:
<flow name="flows1Flow1">
<http:inbound-endpoint exchange-pattern="request-response"
address="http://localhost:4433/miniwebservice" />
<message-properties-transformer scope="outbound">
<add-message-property key="http.method" value="#[header:INBOUND:http.method]" />
</message-properties-transformer>
<logger level="INFO" category="ddo" />
<http:outbound-endpoint exchange-pattern="request-response"
address="http://localhost:4434#[header:INBOUND:http.request]" />
</flow>
(tested and validated with TestWsClient and TestWsServer)