How to publish WebService using Endpoint.publish() method? - java

I am making a basic Hello World Web Service with help of some tutorials online.
I made a basic Java Project(non dynamic) in Eclipse. On running the code as Java Application and visiting the URL "http://localhost:9292/ws/hello" I receive"localhost page isn't working-ERR_EMPTY_RESPONSE" on my browser.Following is the code. Please let me know what am I doing wrong.
SayHello.java
package com.example.hello;
import javax.jws.WebMethod;
import javax.jws.WebService;
#WebService
public class SayHello {
#WebMethod
public String getHello(String name) {
return "Hello " + name;
}
}
LaunchService.java
package com.example.hello;
import javax.xml.ws.Endpoint;
public class LaunchService {
public static void main(String[] args) {
Endpoint.publish("http://localhost:9292/ws/hello", new SayHello());
}
}

#WebService and associated annotations are used for JAX-WS which are SOAP Web services. Requests to the service are made via POST so that is why your GET does not work. GET for ?WSDL is request for service descriptor.
With SOAP client it will work fine (e.g. SOAP UI)
if you want to build REST service then use JAX-RS or Restlet or something else
(2 years late to the party but I thought I might help someone :) )

Related

Accessing JAX-WS Published Endpoint is Not Working

I am trying to create a Web service using JAX-WS. I do have a very basic Java project with the following:
EmployeeService .java
import javax.jws.WebMethod;
import javax.jws.WebService;
#WebService
public class EmployeeService {
#WebMethod
public String getEmployee(String id) {
return "Vlad Danila";
}
}
Exporter.java
import javax.xml.ws.Endpoint;
import services.EmployeeService;
public class Exporter {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/hello",
new EmployeeService());
System.out.println("Successfull!");
}
}
Running the above will throw no error and print "Successfull!".
However, accessing http://localhost:8080/hello on browser gives This page isn’t working.
What am I missing?
I did an example with your code, and it works.. you have to add this to the browser to see
http://localhost:9999/ws/hello?wsdl
This is the url on my case. Then consume it with soap ui or another ws client.
The error you see its cause you are doing a get request on that url and not a soap request.
You don't give much context about what you are doing. JAX-WS is supposed to run in container. Do you run in container which is JEE compatible. See this tutorial, especially the last part:
https://docs.oracle.com/javaee/6/tutorial/doc/bnayn.html#gjyge
If you want something simple, I would recommend to make a spring-boot app, which will work out of the box for you. Forget about heavy JEE containers and try to run a simple spring-boot app which have integrated server inside the spring-boot app.
Here is a link to follow: https://spring.io/guides/gs/rest-service/

RESTful services on AEM

I am trying to expose some RESTfull webservices on AEM. I have followed the instructions in this blog. Below is my service class. Simple requests like /helloservice/sayhi works perfectly, but the method that take path parameter and query parameters (/withparameter/{userid} and /query?q=xyz&prod=abc) return 404 error page. Please help me with this.
I am using AEM 5.6 and Java 7
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import com.foo.bar.service.SampleResource;
#Service
#Component(metatype=true)
#Path("/helloservice")
public class SampleResourceImpl implements SampleResource{
#GET
#Path("/sayhi")
#Produces({MediaType.APPLICATION_JSON})
public String helloWorld(){
return "Hello World";
}
#GET
#Path("/getoperation")
#Produces({MediaType.TEXT_PLAIN})
public String getServiceOperation(){
return "Hello getoperation!";
}
#GET
#Path("/withparameter/{userid}")
#Produces({MediaType.TEXT_PLAIN})
public String getWithParameter(#PathParam("userid") String userid){
return "Path parameter : "+userid;
}
#GET
#Path("/query")
#Produces({MediaType.TEXT_PLAIN})
public String getURLParameters(#QueryParam("q") String q, #QueryParam("prod") String prod){
return "Query params : "+q+", "+prod;
}
}
Any help appreciated, Thanks!
There's an ongoing discussion about using JAX-RS in systems based on Apache Sling (which includes AEM) at https://issues.apache.org/jira/browse/SLING-2192 . From that discussion, https://github.com/wcm-io-caravan/caravan-jaxrs looks to me like a good solution to use JAX-RS resources in an OSGi environment. That project's integration tests run on Sling so there's a fair chance that it works on AEM.
This is wrong usage of Sling architecture.
If you want to implement some RESTful service (querying by path, etc) you need to implement specific resource provider.
There is an example. You may need to understand some basic concepts behind it but still its 10 times better in Sling's world than JAX-RS.
Cognifide has implemented alternative solution which is called Knot.X.
It allows to easly write micro services (and rest APIs). It was written for AEM, but it can be used with any CMS/CRM.
Informations, code examples and docs can be found here: http://knotx.io/
I passed the parameters as querystring, then with "UriInfo" from javax.ws.rs.core worked for me:
#GET
#Path("/data")
#Produces({MediaType.APPLICATION_JSON})
public JSONArray getData(#Context UriInfo info) throws JSONException {
String path = info.getQueryParameters().getFirst("p");
String nodename = info.getQueryParameters().getFirst("nn");
Some paths and methods of requests are blocked by default on AEM. Go to "Apache Sling Servlet/Script Resolver and Error Handler" on config to allow this /services and go to "Apache Sling Referrer Filter" to remove blocked HTTP methods.

integration SQL to a web service in Java

I created a simple web service. Well now that's done, I have to complicate things: connect to a MySQL database and communicate with it via the web service!
I can not find on the internet how to make this connection to my web service (I know very well do so when there is no web service and it is a simple Java application). But the problem that in web service I don't have a main, just methods.
That's a part of my code:
package impression;
import java.sql.*;
import java.util.Date;
import javax.jws.Oneway;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
#WebService(serviceName = "impression")
public class impression {
#WebMethod(operationName = "EnvoiMessage")
public String messageReception(#WebParam(name = "msg") String msg) {
msg="Demande recu!";
return msg;
}
/**
* Web service operation
*/
#WebMethod(operationName = "affichageDemande")
#Oneway
public void affichageDemande() {
//here i want to display the table created im my database
}
}
I will be grateful if you could help me.
I suggest you read this thread. EJB3: How to inject DataSource in EJB3 during Junit testing as raw POJO
That is what you need. An injected datasource, then you can do as you do in "regular java with a main method" :-).
Good luck

Different web service object after each call

I am new with Java EE and SOAP. I have tried to create a simple web service application and its client (environment: NetBeans 7.2.1 IDE, GlassFish Server 3.1, Java 1.6).
Web service code:
package simplews;
import javax.jws.*;
#WebService(serviceName = "SimpleWebService")
public class SimpleWebService {
String something = null;
#WebMethod(operationName = "setSomething")
#Oneway
public void setSomething(#WebParam(name = "smth") String smth) {
something = smth;
}
#WebMethod(operationName = "getSomething")
public String getSomething() {
return something;
}
}
Client application code:
package simpleclientapp;
import simplews.*;
public class SimpleClientApp {
public static void main(String[] args) {
SimpleWebService_Service service = new SimpleWebService_Service();
SimpleWebService port = service.getSimpleWebServicePort();
port.setSomething("trololo");
String smth = port.getSomething();
System.out.println(smth);
}
}
Unfortunately, the client application printed out null. After short investigation I have realised, that on the server side a new SimpleWebService object is created for each client call (sounds like stateless approach).
What is wrong here? Why the client port does not refer to the same WS object for each call?
Web services are stateless by nature. In order to keep state between requests, you have to persist the data (in a file,database etc.).
You're right, JAX-WS web services are stateless by default and you can't rely on something thatviolates this premise. Follow a different approach in storing such values. You can read this doc Java TM API for XML Web Services (JAX-WS) Stateful Web Service with JAX-WS RI, if you really want to follow the direction in your post.

HTTP WebService

is it possible to call Web service by using HTTP Client ?
if yes give me some examples. How can i get list of Methods present in that web service?
for example :
I am using this Web Service WSDL link
it has two functions FahrenheitToCelsius and CelsiusToFahrenheit
Note :
i know how to call webservice by using Web Client but i need to perform call webService by using HTTP Client
Yes, you can. E.g. with Apache HttpClient 4.2.1.
import java.io.File;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
public class HttpClientPost {
public static void main(String[] args) throws ClientProtocolException, IOException {
String request = "<soapenv:Envelope response xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/><soapenv:Body>" +
"<tem:CelsiusToFahrenheit><tem:Celsius>100</tem:Celsius>" +
"</tem:CelsiusToFahrenheit></soapenv:Body></soapenv:Envelope>";
Content response = Request.Post("http://www.w3schools.com/webservices/tempconvert.asmx")
.bodyString(request, ContentType.TEXT_XML).execute().returnContent();
System.out.println("response: " + response);
}
}
For the methods look at the elements named operation within the WSDL file.
It sure is, as long as the web service is exposed by the HTTP protocol. But you'd have to parse the response yourself, and construct valid requests yourself. Much easier to use a framework like Apache Axis, which has all of this automated.
You should also note that this web service is using the SOAP protocol, which should be accounted for when you're trying to use it.

Categories

Resources