RESTful services on AEM - java

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.

Related

Creating and Running RESTful Web Service on GlassFish

I created a simple RESTful web service on the GlassFish server and run it according to this tutorial in the IntelliJ IDE. This runs fine based on the instruction provided. I have 2 additional questions,
a. The tutorial uses a service class provide below,
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#Path("/helloworld")
public class HelloWorld {
#GET
#Produces("text/plain")
public String getClichedMessage() {
return "Hello World";
}
}
I can access that from the URL provided,
http://localhost:8080/AppointmentManager_war_exploded/helloworld
Afterward, I add a new class in the same directory,
#Path("/")
public class App {
#GET
#Produces("text/plain")
public String getMessage() {
return "Hello, Berlin";
}
}
I expected to see the message "Hello, Berlin" in the browser from the opening URL http://localhost:8080/AppointmentManager_war_exploded/, but, instead, I get the error provided,
HTTP Status 404 - Not Found
type Status report
messageNot Found
descriptionThe requested resource is not available.
GlassFish Server Open Source Edition 5.0
What is the issue here?
b. How do I change the part of URL AppointmentManager_war_exploded to something else, say, appointment etc? The artifact tab in the project setting is provided below,
I edited it, but, the change it not corresponded as expected.
I changed the project to maven build after the tutorial, but, the issue is not created for that. If someone interested, you can try too as it will take a minute to run.
Thank you.
First
I expected to see the message "Hello, Berlin" in the browser from the opening URL http://localhost:8080/AppointmentManager_war_exploded/, but, instead, I get the error provided
In MyApplication class that provided by tutorial you should also add your new class:
#ApplicationPath("/")
public class MyApplication extends Application{
#Override
public Set<Class<?>> getClasses() {
HashSet h = new HashSet<Class<?>>();
h.add(HelloWorld.class);
h.add(App.class); // Add your new class here
return h;
}
}
Then you will be able to see expected page on http://localhost:8080/AppointmentManager_war_exploded/
Second
How do I change the part of URL AppointmentManager_war_exploded to something else, say, appointment etc?
URL contains name of your artifact AppointmentManager_war_exploded. This artifact automatically copied to glassfish application directory. You can check glassfish\domains\domain1\applications\__internal.
Just change it just in project structure window here:
Update
Don't forget to change start URL in configuratin settings for app:

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/

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

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 :) )

JAX-RS, GlassFish, Eclipse. A simple web service doesn't work

I am trying to run a simple "Hello World" RESTful web service on my machine. I use Eclipse Kepler and GlassFish 4.0. I am able to deploy the service and I see it on the admin pages of GlassFish but when I try to access to it I get the following error: "HTTP Status 404 - Not Found".
Herein the code of the simple service:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
#Path("hello")
public class HelloRest {
#SuppressWarnings("unused")
#Context
private UriInfo context;
/**
* Default constructor.
*/
public HelloRest() {
// TODO Auto-generated constructor stub
}
/**
* Retrieves representation of an instance of HelloRest
* #return an instance of String
*/
#GET
#Produces("application/xml")
public String getXml() {
// TODO return proper representation object
return "<greeting>Hello REST</greeting>";
}
/**
* PUT method for updating or creating an instance of HelloRest
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("application/xml")
public void putXml(String content) {
}
}
In order to access to the service I try the following URL: http://127.0.0.1:8080/hello-rest/hello, where hello-rest is the name of the Eclipse project and the root path suggested by the admin page of GlassFish.
Your code seems to be ok, so the problem most likely is that you have not defined the base url for your service. You need to tell JAX-RS (Jersey is the implementation in GlassFish) which url pattern it must intercept as your endpoint (base url).
One way of achieving this is using an Application Class which can be added to any package in the project (you could alternatively define the necessary in a web.xml file which I won't cover). The following is the code:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("your-base-url")
public class ApplicationConfig extends Application {
}
You use the #ApplicationPath annotation to define your base url.
You can then access your service at http://127.0.0.1:8080/hello-rest/your-base-url/hello
#GET
#Produces("application/xml")
#path("/getxml")
public String getXml() {
// TODO return proper representation object
return "<greeting>Hello REST</greeting>";
}
Your url should be http://localhost:8080/hello-rest/hello/getxml
You should mention the path at the method level , so the request is redirected to appropriate method.
You can use SOAPUI to test the service. Please make sure you have choose the correct method.
Method as 'GET'
End point as 'hostname:8080'
Resource as 'hello-rest/hello/getxml'
If you face the same issue. Please attach more logs / exception in tomcat console.

Paypal Broadleaf integration

Hi,
Currently I'm using Broadleaf Commerce 2.2.0 and want to integrate paypal. I have gone through the documentation of broadleaf commerce for paypal setup (http://docs.broadleafcommerce.org/2.2/PayPal-Environment-Setup.html).
I have created paypal sanbox account also and provided the link in broadleaf as its mention, but when I'm clicking on paypal image its not redirecting to "/payapl/checkout page"
I'll get the below error in browser
HTTP ERROR 404
Problem accessing /paypal/checkout. Reason:
Not Found
and when i see my eclipse console I'll find the following error.
[ WARN] 12:12:17 PageNotFound - No mapping found for HTTP request with
URI [/paypal/checkout] in DispatcherServlet with name 'marketplace'
Is anyone know why i'm getting this error???
Thanks & Regards,
Ankit Aggarwal
I try do follow the same documentation and also configure paypal advance configration and now i'm able to access paypal getway.
Its little tricky here in fact i spent couple of hr. to understand the error which i was getting in browser finally i came to know its due to some packages which i was unable to call under my new paypal controller class. :P
So your controller class will look like this
package com.mycompany.controller.paypal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.broadleafcommerce.core.checkout.service.exception.CheckoutException;
import org.broadleafcommerce.core.payment.service.exception.PaymentException;
import org.broadleafcommerce.core.pricing.service.exception.PricingException;
import org.broadleafcommerce.vendor.paypal.web.controller.BroadleafPayPalController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class PayPalController extends BroadleafPayPalController
{
#RequestMapping({"/paypal/checkout"})
public String paypalCheckout(HttpServletRequest request)
throws PaymentException
{
return super.paypalCheckout(request);
}
#RequestMapping({"/paypal/process"})
public String paypalProcess(HttpServletRequest request, HttpServletResponse response, Model model, #RequestParam String token, #RequestParam("PayerID") String payerID)
throws CheckoutException, PricingException
{
return super.paypalProcess(request, response, model, token, payerID);
}
}
Previously i was now importing all the packages and i was getting same issue with paypal which you are getting. once i import all the packages its works like a charm for me.
Now please check and let me know if you got any error while doing so?
Regards,
Ankit Patni

Categories

Resources