**My Web service class**
import javax.jws.WebMethod;
import javax.jws.WebService;
/**
* #author edward
*
*/
#WebService
public class HelloWeb {
#WebMethod
public String sayGreeting(String name) {
return "Greeting " + name + "....!";
}
}
My Server java class
import javax.xml.ws.Endpoint;
public class Server {
public static void main(String[] args) {
Endpoint.publish("http://localhost:9090/HelloWeb", new HelloWeb());
System.out.println("Hello Web service is ready");
}
}
Server is running properly, and i am able to access the service using url that returns WSDL code.But i want to access the server using unique URL in java.I have the following client java code.
Client to access HelloWeb Service
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
public class WebClient {
String wsdl = "http://172.21.1.65:9090/HelloWeb?wsdl";
String namespace = "http://helloweb.com";
String serviceName = "HelloWebService";
QName serviceQN = new QName(namespace, serviceName);
{
try{
ServiceFactory serviceFactory = ServiceFactory.newInstance();
Service service = serviceFactory.createService(new URL(wsdl), serviceQN);
}catch (Exception e) {
}
}
}
try this, note that I compiled and ran your server in "test" package, it's important. This is just a basic example to start with JAX-WS.
package test;
import java.net.URL;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class WebClient {
#WebService(name = "HelloWeb", targetNamespace = "http://test/")
public interface HelloWeb {
#WebMethod
String sayGreeting(String name);
}
public static void main(String[] args) throws Exception {
Service serv = Service.create(new URL(
"http://localhost:9090/HelloWeb?wsdl"),
new QName("http://test/", "HelloWebService"));
HelloWeb p = serv.getPort(HelloWeb.class);
System.out.println(p.sayGreeting("John"));
}
}
Related
I was create a soap web service at java. When called from java working fine, but when called from c# its not working, would you please help me? How to call getHelloWorldAsString method from c# with header authentication. Thanks in advance
Here is the java code:
package com.mkyong.ws;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
//Service Implementation Bean
#WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
#Resource
WebServiceContext wsctx;
#Override
public String getHelloWorldAsString() {
MessageContext mctx = wsctx.getMessageContext();
//get detail from request headers
Map<?,?> http_headers = (Map<?,?>) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
List<?> userList = (List<?>) http_headers.get("Username");
List<?> passList = (List<?>) http_headers.get("Password");
String username = "";
String password = "";
if(userList!=null){
//get username
username = userList.get(0).toString();
}
if(passList!=null){
//get password
password = passList.get(0).toString();
}
//Should validate username and password
if (username.equals("abcd") && password.equals("abcd123")){
return "Hello World JAX-WS - Valid User!";
}else{
return "Unknown User!";
}
}
#Override
public String getSum() {
return "10";
}
}
Here is the java calling (this is working):
package com.mkyong.client;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;
import com.mkyong.ws.HelloWorld;
public class HelloWorldClient{
private static final String WS_URL ="http://localhost:8080/ws/HelloWorld?wsdl";
public static void main(String[] args) throws Exception {
try {
URL url = new URL(WS_URL);
QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
/*******************UserName & Password ******************************/
Map<String, Object> req_ctx = ((BindingProvider)hello).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("abcd"));
headers.put("Password", Collections.singletonList("abcd123"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
/**********************************************************************/
System.out.println(hello.getHelloWorldAsString());
System.out.println(hello.getSum());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
C# Client Call:
After adding wsdl to the windows application web service,written following C# code,
webService.HelloWorldImplService ws = new webService.HelloWorldImplService(); Console.WriteLine(ws.getHelloWorldAsString());
I want to get the attribute value from XML output that is being created by my Rest Web Service but without the tags in my Java client. I tried XPath but it doesn't seem to work with URLs, only with XML files that are stored in the drive. And all the answers about XPath are specifically for stored XML files not online. I am using Netbeans. The concept is, web service takes two numbers and provides the sum as an XML. Webservice url that I use in this example http://localhost:8080/WSDemo/rest/book/5/2
Rest Web service
ApplicationConfig.java
package wbs;
import java.util.Set;
import javax.ws.rs.core.Application;
import javax.xml.bind.annotation.XmlRootElement;
#javax.ws.rs.ApplicationPath("rest")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(wbs.GenericResource.class);
}
}
GenericResource.java
package wbs;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlRootElement;
#Path("book")
public class GenericResource {
#Context
private UriInfo context;
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("{n1}/{n2}")
public String getSum(#PathParam ("n1") int a, #PathParam ("n2") int b) {
int c = a+b;
return "<Sum>" + c + "</Sum>";
}
}
Client
Sum.java
package restclient;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
public class Sum {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/WSDemo/rest/";
public Sum(){
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI).path("book");
}
public <T> T getSum(Class<T> responseType, String n1, String n2) throws ClientErrorException {
WebTarget resource = webTarget;
resource = resource.path(java.text.MessageFormat.format("{0}/{1}", new Object[]{n1, n2}));
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public void putXml(Object requestEntity) throws ClientErrorException {
webTarget.request(javax.ws.rs.core.MediaType.APPLICATION_XML).put(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_XML));
}
public void close() {
client.close();
}
}
RestClient.java
package com.emmanouil;
import restclient.Sum;
public class RestClient {
public static void main(String[] args) {
Sum client = new Sum();
String response = client.getSum (String.class,"5" , "2");
System.out.println(response);
client.close();
}
}
Output
I want to clear the tags and get the result (7 in this case). Of course, I can trim the string or any other other similar way but it's something that I don't want to do.
I have a web application I am making using a websocket API to handle the websockets, here is the code for that part
package comm2.hello;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.catalina.session.*;
#ServerEndpoint(value = "/echo")
public class wschat {
private static ArrayList<Session> sessionList = new ArrayList<Session>();
#OnOpen
public void onOpen(Session session) {
try {
sessionList.add(session);
// asynchronous communication
session.getBasicRemote().sendText("hello");
} catch (IOException e) {
}
}
public void send(String text, Session session) throws IOException {
session.getBasicRemote().sendText(text);
}
}
I am trying to have another java class then call into the send method to send messages, using the following code.
package comms;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.Session;
import javax.websocket.Session;
import comm2.hello.*;
public class main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
wschat h = new wschat();
String text = "hello";
//session shouldn't be null but not sure what to make it
Session session = null;
h.send(text,session);
}
}
As you can see, I have the session variable in the main.java class set to null which will thus always produce a null pointer error. This is because I am not sure what to make session equal to, does anyone have any idea what to initialize the session variable to in main.java?
I made web services using JAX-WS. Now I want to test using a web browser, but I am getting an error. Can somebody explain me please help.
My Service class:
package another;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
#WebService(name = "WebService")
public class WebServiceTest {
public String sayHello(String name) {
return "Hello : " + name;
}
public static void main(String[] args) {
WebServiceTest server = new WebServiceTest();
Endpoint endpoint = Endpoint.publish(
"http://localhost:9191/webServiceTest", server);
}
}
I run this class as simple Java program.
And I can see the WSDL in my browser at http://localhost:9191/webServiceTest?wsdl.
And I am trying to call this using the URL http://localhost:9191/webServiceTest?sayHello?name=MKGandhi, but I am not getting any result.
What is wrong here?
I can't tell you why it is not possible to test it in browser.
But at least I can tell you how to test it from your code, cause your webservice works:
package another;
import javax.jws.WebService;
#WebService
public interface IWebServiceTest {
String sayHello(String name);
}
package another;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class Main {
public static void main(String[] args) throws Exception {
String url = "http://localhost:9191/webServiceTest?wsdl";
String namespace = "http://another/";
QName serviceQN = new QName(namespace, "WebServiceTestService");
Service service = Service.create(new URL(url), serviceQN);
String portName = "WebServicePort";
QName portQN = new QName(namespace, portName);
IWebServiceTest sample = service.getPort(portQN, IWebServiceTest.class);
String result = sample.sayHello("blabla");
System.out.println(result);
}
}
You try and test your webservice by using the url http://localhost:9191/webServiceTest?sayHello?name=MKGandhi
Just try this url http://localhost:9191/webServiceTest/sayHello?name=MKGandhi
it should work fine :)
in your url "http://localhost:9191/webServiceTest?sayHello?name=MKGandhi"
try changing the localhost by your ip address.
example : "http://198.251.234.45:9191/webServiceTest?sayHello?name=MKGandhi"
I am new to Web Services with JBoss. A client is connecting to an EJB3 based Web Service
With JBoss AS 5 and JDK 6 using JAX-WS. I am stuck with the following exception:
Exception in thread "main" javax.xml.ws.WebServiceException:
Undefined port type: {http://webservice.samples/}HelloRemote
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:300)
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:306)
at javax.xml.ws.Service.getPort(Service.java:161)
at samples.client.BeanWSClient.getPort(BeanWSClient.java:44)
at samples.client.BeanWSClient.main(BeanWSClient.java:35)
BeanWSClient.java (client is a different project than EJB3 WS):
package samples.client;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import samples.webservice.HelloRemote;
public class BeanWSClient {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
String endpointURI ="http://192.168.22.100:8080/SampleWSEJBProject/HelloWorld?wsdl";
String helloWorld = "Hello world!";
Object retObj = getPort(endpointURI).echo(helloWorld);
System.out.println(retObj);
}
private static HelloRemote getPort(String endpointURI) throws MalformedURLException {
QName serviceName = new QName("http://www.openuri.org/2004/04/HelloWorld", "HelloWorldService");
URL wsdlURL = new URL(endpointURI);
Service service = Service.create(wsdlURL, serviceName);
return service.getPort(HelloRemote.class);
}
HelloRemote.java:
package samples.webservice;
import javax.jws.WebService;
#WebService
//#SOAPBinding(style=SOAPBinding.Style.RPC)
public interface HelloRemote {
public String echo(String input);
}
HelloWorld.java:
package samples.webservice;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
/**
* Session Bean implementation class MyBean
*/
#WebService(name = "EndpointInterface", targetNamespace = "http://www.openuri.org/2004/04/HelloWorld", serviceName = "HelloWorldService")
#SOAPBinding(style = SOAPBinding.Style.RPC)
#Remote(HelloRemote.class)
#Stateless
public class HelloWorld implements HelloRemote {
/**
* #see Object#Object()
*/
#WebMethod
public String echo(String input) {
return input;
}
}
In HelloWorld.java, you should change the name = "EndpointInterface" parameter of the #WebService annotation to name = "HelloRemote"
OR
In BeanWSClient.java, in the getPort(String endpointURI) method, replace
return service.getPort(HelloRemote.class);
with
QName port_name = new QName("http://www.openuri.org/2004/04/HelloWorld","HelloWorldPort");
return service.getPort(port_name, HelloRemote.class);
add endpointInterface in #WebSevice annotation, if you dont mention endpoint interface give fully qualified portname while using getPort method.
try adding:
-Djava.endorsed.dirs=${jbossHome}/lib/endorsed/
as a vm argument when you execute BeanWSClient. (where jbossHome is of-course your jboss home).
the problem was, as far as i recall, jboss overwritten the sun implementation of WSService, and you need to set your class loading to load the jboss implementation before the sun's implementation.
because sun's implementation is in rt.jar you need to use endorsed lib.
Try to use this method:
//inicia classe
public void test(){
String url = "http://localhost:8080/soujava_server/HelloWorld?wsdl";
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}