WebService client fails: Tomcat, CXF - java

I am copying the simplest web service example from CXF; it steps through writing an interface, then an implementation file, to say hello to a name provided by the webservice consumer. I changed a package name and the method name because I wanted to see where things showed up; if you name everything HelloWorld you can't see what is method, package, class, etc.
Those instructions include a program to publish the web service. After I do that, putting the URL
http://localhost:9000/helloWorld?wsdl
in a browser displays a wsdl file that contains enough stuff the way I spelled it to convince me that it was generated from my code. I assume, based on this, that both the WSDL generation and the publication worked.
This is the service interface:
package hw;
import javax.jws.WebParam;
import javax.jws.WebService;
#WebService
public interface HelloWorld
{
String sayHi(#WebParam(name="firstName") String firstName);
}
This is the service implementation:
package hwimpl;
import javax.jws.WebService;
#WebService(endpointInterface = "hw.HelloWorld", serviceName = "HelloWorld")
public class HelloWorldImpl
{
static public void say(String msg) { System.out.println(msg); }
public String sayHi(String firstName)
{ say ("sayHi called with " + firstName);
return "Hello " + firstName + " from the World.";
}
}
And this is the publishing program:
package hwimpl;
import javax.xml.ws.Endpoint;
public class PublishHelloWorldService
{
protected PublishHelloWorldService() throws Exception
{
// START SNIPPET: publish
System.out.println("Starting Server");
HelloWorldImpl implementor = new HelloWorldImpl();
String address = "http://localhost:9000/helloWorld";
Endpoint.publish(address, implementor);
// END SNIPPET: publish
}
public static void main(String args[]) throws Exception
{
new PublishHelloWorldService();
System.out.println("Server ready...");
Thread.sleep(5 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}
Now I compile and run this program:
package client;
import hw.HelloWorld;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;
public final class HelloWorldClient
{
private static final QName SERVICE_NAME = new QName("http://server.hw.demo/", "HelloWorld");
private static final QName PORT_NAME = new QName("http://server.hw.demo/", "HelloWorldPort");
private HelloWorldClient()
{
}
public static void main(String args[]) throws Exception
{
Service service = Service.create(SERVICE_NAME);
String endpointAddress = "http://localhost:9000/helloWorld";
// If web service deployed on Tomcat deployment, endpoint should be changed
// to:
// String
// endpointAddress =
// "http://localhost:8080/java_first_jaxws/services/hello_world";
// Add a port to the Service
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
HelloWorld hw = service.getPort(HelloWorld.class);
System.out.println(hw.sayHi("Albert"));
}
}
and I get this error:
Exception in thread "main" javax.xml.ws.WebServiceException: Could not send Message.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:135)
at com.sun.proxy.$Proxy20.sayHi(Unknown Source)
at client.HelloWorldClient.main(HelloWorldClient.java:37)
Caused by: java.net.MalformedURLException: Invalid address. Endpoint address cannot be null.
at org.apache.cxf.transport.http.HTTPConduit.getURL(HTTPConduit.java:872)
at org.apache.cxf.transport.http.HTTPConduit.getURL(HTTPConduit.java:854)
at org.apache.cxf.transport.http.HTTPConduit.setupURL(HTTPConduit.java:800)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:548)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:46)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:516)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:313)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:265)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:124)
... 2 more
I am running the programs -- both publish and client -- from eclipse. The eclipse is set up with proxies for http and https in Window / Preferences; I removed the one for http before running the client, but it did not change the message.
It is in fact a tomcat server; I tried the alternate URL in the publish program with no change.
I don't run tomcat from within eclipse in this case; I run it by itself on my machine and then run the publish program (from eclipse), verify the url that displays the wsdl works correctly, and then run the client program (from eclipse) and get my error.
Can someone tell me what I'm doing wrong? I've seen other posts on this exact error message, but none of the answers were definitive and I appear to have tried them all.

Not sure this is your problem.
I've sometimes had problems with eclipse not being able to run tomcat applications on a running tomcat as you describe in your example.
What I sometimes have to do when working with tomcat and eclipse is either
have a running tomcat (windows service) and then export my eclipse application to that tomcat
stop the running tomcat on that port from windows services and start the tomcat from inside eclipse when running the program.
For some reason eclipse seems to have problems with an already running tomcat.

Related

Openshift: Trying to create java.websocket using JBoss Application Server

I am new to open shift, so bear with me. I have gotten open shift on my eclipse, and I have set up a JBoss Application Server 7. I want to make a server endpoint java class as described here. How do I do this? I noticed that, first of all, there is no java.websocket jar files in the open shift project that I created in eclipse. So I decided to import it and added to the build path. (This jar file I copied from glassfish's javax.websocket-api.jar). But whenever I would commit it and push my java class, it would give me a bunch of errors and mu open shift domain won't work.
So what am I doing wrong? Is it that the jar file that I imported is wrong (i.e. it isn't compatible with JBoss)?
Another thing that eclipse is telling me is that there is this error: "Faceted Project Problem (Java Version Mismatch) (1 item)"
Here is my server endpoint class:
package serverendpointdemo;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/serverendpointdemo")
public class ServerEndPointDemo {
#OnOpen
public void handleOpen () {
System.out.println("JAVA: Client is now connected...");
}
#OnMessage
public String handleMessage (String message) {
System.out.println("JAVA: Received from client: "+ message);
String replyMessage = "echo "+ message;
System.out.println("JAVA: Send to client: "+ replyMessage);
return replyMessage;
}
#OnClose
public void handleClose() {
System.out.println("JAVA: Client is now disconnected...");
}
#OnError
public void handleError (Throwable t) {
t.printStackTrace();
}
}
Thank you for your help!

subethasmtp server not printing messages from client

When I run the client it's supposed to send an email to my server and then I want my email server to print out the email details (to, from, port, message) to console. For some reason after running the client, nothing apparent happens on the server.
server
package example;
import org.subethamail.smtp.server.SMTPServer;
public class EmailServer {
public static void main(String[] args) {
MyMessageHandlerFactory myFactory = new MyMessageHandlerFactory();
SMTPServer smtpServer = new SMTPServer(myFactory);
smtpServer.setPort(25000);
smtpServer.start();
}
}
server output
run: [main] INFO org.subethamail.smtp.server.SMTPServer - SMTP server
*:25000 starting [org.subethamail.smtp.server.ServerThread *:25000] INFO org.subethamail.smtp.server.ServerThread - SMTP server *:25000
started
client
package example;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.subethamail.smtp.client.*;
public class EmailClient {
public static void main(String[] args) {
try {
SMTPClient sc = new SMTPClient();
sc.close();
sc.connect("localhost", 25000);
sc.sendReceive("test");
} catch (IOException ex) {
Logger.getLogger(EmailClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
client output
run: BUILD SUCCESSFUL (total time: 0 seconds)
Version is 3.1.7 from https://code.google.com/p/subethasmtp/downloads/list
The server requires MyMessageHandlerFactory which I copied from: https://code.google.com/p/subethasmtp/wiki/SimpleExample
OK, let's check the source code (always a good idea) and see what happens.
You send "test" via
SMTPClient sc;
sc.sendReceive("test"); // which is actually sent to your SMTPServer as "test\r\n"
Now, considering that this is a new SMTP conversation (see RFC5321 for everything you always wanted to know but were afraid to ask about such things) and "test" isn't a valid command VERB at this point in the conversation, you would expect to see an error returned by sendReceive().
But since you're ignoring the SMTPClient.Response#75 returned from what should have been
Response resp=SMTPClient.sendReceive()
you're missing out on both
resp.code (which I am sure is 500 - Permanent Negative Completion reply / Syntax - see the RFC above) and
resp.message describing the reason your command could not be fulfulled
both of which are returned from CommandHandler#93.

Axis Sample AddressBook exception

I have 2 questions
I am trying to run a axis 2 sample. In the last part of the instruction file, there is this line which it says, should be run in the terminal(ubuntu), is not working
java -Djava.ext.dirs=%AXIS2_HOME%\lib;%JAVA_HOME%\jre\lib\ext -cp target/classes org.apache.axis2.jaxws.addressbook.AddressBookClient.class
I am not an expert in this field, and I am not familiar with ubuntu commands. I feel that this is not an ubuntu command
The error I get is, "Invalid Job"
Can someone convert this into an ubuntu command?
Since it was not working, I built the jar using,
mvn clean install
Then I copied the jar file to the servicejars directory under repository, in axis2
Then the axis server says that the jar does not contain the WebServices annotation
"No #WebService annotated service implementations found in the jar: file:/home/dodan/Programs/axis2-1.6.0/repository/servicejars/jaxws-addressbook-1.6.0-client.jar. Service deployment failed."
So I added it to the original java file which did not have that annotation(and the import too)
Yet the axis2 server still sys that there is not webservices annotation
2. Can somebody say whether I have missed anything?
here is the java file I changed
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.jws.WebService;
import java.util.Map;
/**
* Simple JAX-WS Dispatch client for the address book service implementation.
*/
#WebService
public class AddressBookClient {
private static String NAMESPACE = "http://addressbook.jaxws.axis2.apache.org";
private static QName QNAME_SERVICE = new QName(NAMESPACE, "service");
private static QName QNAME_PORT = new QName(NAMESPACE, "port");
private static String ENDPOINT_URL = "http://localhost:8080/axis2/services/AddressBookImplService.AddressBookImplPort";
private static String ADD_ENTRY_BODY_CONTENTS =
"<ns1:addEntry xmlns:ns1=\"http://addressbook.jaxws.axis2.apache.org\">" +
"<ns1:firstName xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myFirstName</ns1:firstName>" +
"<ns1:lastName xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myLastName</ns1:lastName>" +
"<ns1:phone xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myPhone</ns1:phone>" +
"<ns1:street xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myStreet</ns1:street>" +
"<ns1:city xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myCity</ns1:city>" +
"<ns1:state xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myState</ns1:state>" +
"</ns1:addEntry>";
private static String FIND_BODY_CONTENTS =
"<ns1:findByLastName xmlns:ns1=\"http://addressbook.jaxws.axis2.apache.org\">" +
"<ns1:lastName xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myLastName</ns1:lastName>" +
"</ns1:findByLastName>";
public static void main(String[] args) {
try {
System.out.println("AddressBookClient ...");
Service svc = Service.create(QNAME_SERVICE);
svc.addPort(QNAME_PORT, null, ENDPOINT_URL);
// A Dispatch<String> client sends the request and receives the response as
// Strings. Since it is PAYLOAD mode, the client will provide the SOAP body to be
// sent; the SOAP envelope and any required SOAP headers will be added by JAX-WS.
Dispatch<String> dispatch = svc.createDispatch(QNAME_PORT,
String.class, Service.Mode.PAYLOAD);
// Invoke the Dispatch
System.out.println(">> Invoking sync Dispatch for AddEntry");
String response = dispatch.invoke(ADD_ENTRY_BODY_CONTENTS);
System.out.println("Add Entry response: " + response);
System.out.println(">> Invoking Dispatch for findByLastName");
String response2 = dispatch.invoke(FIND_BODY_CONTENTS);
System.out.println("Find response: " + response2);
} catch (Exception e) {
System.out.println("Caught exception: " + e);
e.printStackTrace();
}
}
}
You're using Windows syntax for environment variables.
Instead of %AXIS_HOME%, you would use $AXIS_HOME.
That said, you do not need any version of Axis to learn about web services these days. JAX-WS implementations exist in the JDK for Java 6 and newer.
There's a lot of tutorials around for it.

How to browse the file system of a server machine when connecting with a client (java)

I'm in the process of making a proof of concept to dissociate the business code from the gui for the ps3 media server (http://www.ps3mediaserver.org/). For this I've got a project hosted at source forge (http://sourceforge.net/projects/pms-remote/). The client should be a simple front end to configure the server from any location within a network having the rights to connect to the server.
On the server side, all service have been exposed using javax.jws and the client proxy has been generated using wsimport.
One of the features of the current features (actually, the only blocking one), is to define the folders that will be shared by the server. As the client and server are now running as a single application on the same machine, it's trivial to browse its file system.
Problem: I'd like to expose the file system of the server machine through web services. This will allow any client (the one I'm currently working on is the same as the original using java swing) to show available folders and to select the ones that will be shown by the media server. In the end the only thing I'm interested in is an absolute folder path (string).
I thought I'd find a library giving me this functionality but couldn't find any.
Browsing the files using a UNC path and accessing a distant machine doesn't seem feasible, as it wouldn't be transparent for the user.
For now I don't want to worry about security issues, I'll figure these out once the rest seems feasible.
I'd be grateful for any input.
Thanks, Philippe
I've ended up creating a pretty simple web service letting either list all root folders or all child folders for a given path.
It's now up to the client to have a (GUI) browser to access this service.
package net.pms.plugin.webservice.filesystem;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import net.pms.plugin.webservice.ServiceBase;
#WebService(serviceName = "FileSystem", targetNamespace = "http://ps3mediaserver.org/filesystem")
public class FileSystemWebService extends ServiceBase {
#WebMethod()
public List<String> getRoots() {
List<String> roots = new ArrayList<String>();
for(File child : File.listRoots()) {
roots.add(child.getAbsolutePath());
}
return roots;
}
#WebMethod()
public List<String> getChildFolders(#WebParam(name="folderPath") String folderPath) throws FileNotFoundException {
List<String> children = new ArrayList<String>();
File d = new File(folderPath);
if(d.isDirectory()) {
for(File child : d.listFiles()) {
if(child.isDirectory() && !child.isHidden()) {
children.add(child.getAbsolutePath());
}
}
} else {
throw new FileNotFoundException();
}
return children;
}
}
For people wanting to use this, here's the ServiceBase class as well
package net.pms.plugin.webservice;
import javax.xml.ws.Endpoint;
import org.apache.log4j.Logger;
public abstract class ServiceBase {
private static final Logger log = Logger.getLogger(ServiceBase.class);
protected boolean isInitialized;
/**
* the published endpoint
*/
private Endpoint endpoint = null;
/**
*
* Start to listen for remote requests
*
* #param host ip or host name
* #param port port to use
* #param path name of the web service
*/
public void bind(String host, int port, String path) {
String endpointURL = "http://" + host + ":" + port + "/" + path;
try {
endpoint = Endpoint.publish(endpointURL, this);
isInitialized = true;
log.info("Sucessfully bound enpoint: " + endpointURL);
} catch (Exception e) {
log.error("Failed to bind enpoint: " + endpointURL, e);
}
}
/**
* Stop the webservice
*/
public void shutdown() {
log.info("Shut down " + getClass().getName());
if (endpoint != null)
endpoint.stop();
endpoint = null;
}
}
From the client, you might be able to leverage the output of smbclient -L. On the server, a suitable servlet might do.

Web Services using jdk 1.6

Hi All
I am new to web services. I have written a java class.
But I am not getting how to deploy it. I mean do i need web server or app server . As this is simple java class i can not make WAR file to deploy it . So what is the method to deploy it and which server should i use. I am using JDK 1.6
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.ws.Endpoint;
#WebService
public class WiseQuoteServer {
#SOAPBinding(style = Style.RPC)
public String getQuote(String category) {
if (category.equals("fun")) {
return "5 is a sufficient approximation of infinity.";
}
if (category.equals("work")) {
return "Remember to enjoy life, even during difficult situatons.";
} else {
return "Becoming a master is relatively easily. Do something well and then continue to do it for the next 20 years";
}
}
public static void main(String[] args) {
WiseQuoteServer server = new WiseQuoteServer();
Endpoint endpoint = Endpoint.publish(
"http://localhost:9191/wisequotes", server);
The best answer to your question would be the tutorial of JAX-WS

Categories

Resources