I googled some information about web services, it seems like a enterprise level application. I found that RESTful design is very cool idea on this. I find that Apache CXF looks cool, it support RESTful design and Java. It is a good choice for beginner to start writing an application using Apache CXF? or any other framework is suggested?
I'd go for Jersey, the RI of JAX-RS (JSR 311), the Java API for RESTful Web Services (i.e. a standard).
I recommend to use JAX-RS because IMHO it is the most neutral framework in terms of telling you how REST should be done. I have not used CXF, only Jersey. It is a very solid implementation and comes with a good client side connector, too (client side not part of JAX-RS yet).
Being neutral with regard to 'how to do REST' is important because there is not yet an acknowledged 'best' way to approach certain aspects (e.g. design of hypermedia).
Congrats to going the REST way - you won't regret it.
Jan
The much simpler implementation for a beginner would be spring 3.0 REST support. Spring MVC 3.0 has REST support and is very much simpler compared to Apache CXF.
Restlet in another RESTful web framework for Java : http://www.restlet.org/
I get started REST with RESTEasy and get it up in 30 minutes. You can use it as stand-alone lib in your favorite servlet container without all this JBoss stuff.
You should try PlayFramework. Just take a loot at a sample route file and you will know how easy it is to use play to implement RESTFul web app:
# ====== Order service =========================
GET /orders Orders.list
GET /orders/{<[0-9]+>id} Orders.show
PUT /orders/{<[0-9]+>id} Order.saveUpdate
POST /orders Orders.saveNew
# ==============================================
And corresponding controller methods:
public class Orders extends Controller {
public static void list() {
List<Order> orders = Order.all();
render(orders);
}
public static void show(long id) {
Order order = Order.findById(id);
notFoundIfNull(order);
render(order);
}
public static void saveUpdate(long id, Order update) {
Order order = Order.findById(id);
notFoundIfNull(order);
order.update(update);
show(id);
}
public static void saveNew(Order order) {
order.save();
show(order.getId());
}
}
There are some utilities enable you to interact with other Web Services:
String url = "https://ajax.googleapis.com/ajax/services/search/web";
Map<String, Object> params = new HashMap<String, Object>();
params.put("v", "1.0");
params.put("q", searchStr);
params.put("key", Play.configuration.get("app.google.key"));
params.put("userip", myIpAddr);
HttpResponse resp = WS.url(url).params(params).get();
return resp.getString();
Related
I am using activiti community version 6.0. I have gone through the documentation but cannot see a REST API to retrieve task-form.
I noticed Activiti uses following request url to get the form definitions:
http://localhost:8080/activiti-app/app/rest/task-forms/{taskId}
I tried using this url along with a restTemplate to access the task forms and resulted in 401 error code.
#Service
public class GetTaskForm {
String baseURL = "http://localhost:8080/activiti-app/app/rest/task-forms/";
public void getTaskForm(String taskId){
String taskURL = baseURL + taskId;
RestTemplate restTemplate = new RestTemplate();
String taskForm = restTemplate.getForObject(taskURL, String.class);
System.out.println(taskForm);
}
}
What would be the best way to achieve this?
Refer this documentation to get task form and if you are sending your request from outside of activiti then as Snickers3192 said you have to pass activiti authorization header in the request.
You are looking for the form definition (JSON) for forms that re built using the Form Modeler in version 6.
The ReST API documented does not support returning this as it is part of the orm engine configuration, If you look at the source in activiti-ui/activiti-app-rest you will find the ReST endpoints for the form engine.
The best place to find documentation for these API is in the Alfresco Enterprise Edition docs as Enterprise edition extends on the activiti-app implementation:
http://docs.alfresco.com/process-services1.7/topics/task_form.html
Obviously there are gaps between community edition and enterprise edition, but this should give you what you need. And, the URL you list should return the form definition as long as you are properly authenticated.
BACKGROUND:
I have a REST API implemented in Java using Jersey. My API uses four verbs: GET, POST, PUT, DELETE.
I find developing REST APIs in java very easy and straight forward.
eg here is an elaborate hello webservice (I say elaborate because there are easier ways, but this is more representative):
import javax.ws.rs.*;
#Path("/myresource")
public class MyResource{
#GET
#Path("name/{name}")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response sayHello(#PathParam("name") String name){
return Response.ok("Hello "+name).build();
}
}
PROBLEM:
I am learning python. I want to convert my Java Jersey REST API into python.
Basically Jersey is Java's implementation of REST (aka JAX-RS: Java API for RESTful Web Services). Does python have a reference implementation of REST? If not, is there any implementation out there that comes close and would be easy to use for someone coming from Java-Jersey?
You may want to check the previous similar question: Recommendations of Python REST (web services) framework?
Python does not have a built-in REST framework, but I personally have had good experiences with Flask and Bottle.
It's very similar in use to Jersey (Bottle example):
#route('/')
#route('/hello/<name>')
def greet(name='Stranger'):
return template('Hello {{name}}, how are you?', name=name)
Handling HTTP verbs:
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()
What is the Java equivalent to Script service (like web service but with JSON instead of XML) in the .net world?
I am looking for a way of creating and invoiking web services using java. I prefer to find a way that will allow me define a method that will act as web service. I don't like the solutions of "dedicated jsp or servlet" for the specific request.
Is there any wat of doing so?
There are a lot of frameworks that help you to do this. I personally prefer Spring.
But you can just search for "Java based RESTful web services frameworks". Here is a list of such framework from Wikipedia: http://en.wikipedia.org/wiki/List_of_web_service_frameworks
Enjoy.
You can use libraries like Jersey or RESTeasy for the implementation of web services. For the consumers, you can use the built in classes of the same libraries or, if you prefer, can use Apache HttpClient
I personally prefer using Jersey + HttpClient combination :)
I would prefer RESTful services which fits for your need of "I prefer to find a way that will allow me define a method that will act as web service." Just with REST annotations You can set a method as a Service.
Code Snippet simple REST
#Path("/rest")
public Class MyFirstService
{
//Method without Path parameters
#GET
#Path("/name")
#Produces("application/json")
public String getMyName()
{
return "My Name:";
}
//Method with Path parameters
#GET
#Path("/name/{id}")
#Produces("application/json")
public String getMyName(#Pathparam("id")String Id)
{
if(Id.equals("1")
return "My Name:";
else
return "None";
}
}
RESTful Services give four major Services as -
GET
PUT
POST
DELETE
I would recommend JEE6, especially if your focus is going to be on REST based services. Glassfish 3 and JBoss 7 are neck and neck now with their implementation, either would be a good choice (though JBoss is my personal preference). With the JAX-RS and JAS-WS specifications you simply annotate your classes and they become web service capable:
Make your bean a SOAP based web service:
#WebService
public class AccountImpl {
// You can explicitly mark the methods you want to make available in your WSDL
#WebMethod
public BigDecimal getBalance() {}
}
Make your bean a REST based web service:
#Path("/rs/account")
public class AccountImpl {
#GET
#Path("/balance")
#Produces("application/json")
public BigDecimal getBalance() {}
}
The code snippet is just an example. You can find more resources online for learning JAX-RS and JAX-WS. Here are a few links:
RESTEasy
Jersey
JAX-WS Tutorial
Note: I included information about JAX-WS for reference only. You indicated you wanted to build JSON services, which implies REST
Is there any way to use soap-rpc web services such that the client is generated via a shared interface? Restful web services do it this way, but what about soap based? Do you always have to use a tool like Axis or CXF to generate your stubs and proxies, or is there something out there that will set it up dynamically?
Thanks.
EDIT #1:
To clarify, I'm looking to do something like this:
Common interface:
#WebService
public interface MyWebService {
#WebMethod
String helloWorld();
}
This common interface can already be used to create the server side component. My question is: can this type of common interface be used on the client side to generate dynamic proxies? Restful web services do it this way (Restlets & CXF) and it seems the .Net world has this type of functionality too.
I would see this tutorial of JAX-WS useful for your purposes:
In the example code the Web Services Client is configured by adding an annotation #WebServiceRef with a property pointing to the WSDL location to the client implementation class and no tools are needed to access the stuff from the Web Service that is referenced.
Was this the way you would like to have it, or did this even answer to right question?
Not exactly sure what you're looking for, but if you don't want to rely on JAX-WS/JAXB-generated artifacts (service interfaces and binding objects), you can make use of the Service and Dispatch APIs. For example:
QName serviceName = new QName(...);
Service service = Service.create(serviceName);
QName portName = new QName(...);
String endpointAddress = "...";
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
SOAPMessage request = ...;
SOAPMessage response = dispatch.invoke(request);
Check Apache CXF. Configuring a Spring Client (Option 1).
When you want to call a webservice, you must have knowledge of methods implemented on it. For that, We need to make stubs OR we can read it from WSDL.
I have created a WS client, using AXIS2 libraries, which is without stubs. The thing is, for each diff. WS we need to create response handles.
You can call any WS method using SOAP envelops and handle the response.
//common interface for response handlers...
//implement this for diff. web service/methods
public interface WSRespHandler{
public Object getMeResp(Object respData);
}
//pass particular handler to client when you call some WS
public class WebServiceClient {
public Object getResp(WSRespHandler respHandler) {
...
return repHandler.getMeResp(xmlData);
}
}
Please check the link below, which shows the example interface for WS client.
http://javalibs.blogspot.com/2010/05/axis2-web-service-client-without.html
For every diff. WS method we can have diff. implementation for WSRespHandler interface, which will help parsing the response.
Not knowing java so well, but being forced to learn some to accomplish a task that I was given, I needed to consume a .Net service that I have already written, I had to do a little research.
I found that 99% of the examples/samples/problems with invoking a method call against a .Net service, or any service for that matter involved using J2EE (ServiceManager) or build classes and a proxy that reflect the service being invoked. Unfortunately for me, none of this would work. I was working "in a box". I could not add new classes, could not WSDL references, did not have J2EE, but DID have access to the standard java libs.
I am used to doing this sort of thing in pretty much every other language but java, but now there was no choice, and java it was.
A lot of digging and figuring out all new terminology, methods, classes, etc, I knew I was getting close, but was having issues with some small items to complete the task.
Then I came across this post: http://www.ibm.com/developerworks/xml/library/x-jaxmsoap/
As long as you have some sort of idea of what you need to send the soap service in term of the soap envelope, the above link will give you the information you need to be able to invoke a service without the classes, wsdl class generators and J2EE, apache or other dependencies.
In an hour from the time I read the mentioned article, I had a class working and about 10 minutes later, converted the code to the "in the box" solution.
Hope this helps
Apache Tuscany might help you, although it may be heavier than you want
http://tuscany.apache.org/
For the last couple of years I've had my head in Python, where there are numerous choices for simple, minimal frameworks that allow me to stand up a website or service easily (eg. web.py). I'm looking for something similar in Java.
What is the simplest, least-moving-parts way of standing up simple services using Java these days? I'm looking for something as simple as:
the ability to receive HTTP requests
the ability to dispatch those requests to handlers (preferably a regular expression based url to handler mapping facility)
the ability to set HTTP headers and generally fully control the request/response
Bonus points if the framework plays well with Jython.
[Update] Thanks for the responses, some of these look quite interesting. I'm not seeing the url dispatch capability in these, however. I'm looking for something similar to Django's url.py system, which looks like:
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
Where you specify a url regular expression along with the handler that handles it.
I liked to worth the Simple HTTP Server from the Simple Framework. It offers a nice Tutorial about how to start as well.
there are several alternatives:
servlets
restlet: lightweight REST framework
jax-rs: using jersey or the restlet module implementing the jax-rs specs
grizzly: NIO based server (with HTTP support + handlers)
apache mina: event-driven, async server (with HTTP support)
all these frameworks come with a built-in server.
EDIT
jax-rs has a similar approach using url templates:
#Path("/users/{username}")
public class UserResource {
#GET
#Produces("text/xml")
public String getUser(#PathParam("username") String userName) {
}
}
then put your handlers in an Application object:
public class MyApplicaton extends Application {
public Set<Class> getClasses() {
Set<Class> s = new HashSet<Class>();
s.add(UserResource.class);
return s;
}
}
another example with JAX-RS:
#GET
#Produces("application/json")
#Path("/network/{id: [0-9]+}/{nid}")
public User getUserByNID(#PathParam("id") int id, #PathParam("nid") String nid) {
}
EDIT 2
Restlet supports a centralized configurations like Django, in your Application object:
// Attach the handlers to the root router
router.attach("/users/{user}", account);
router.attach("/users/{user}/orders", orders);
router.attach("/users/{user}/orders/{order}", order);
Servlets might be the way to go. To do very simple things you only need to override one method of one class. More complicated stuff is of course possible, but you can go a long way with a little work.
Investigate Tomcat or Jetty - both are open source and well supported.
public class HelloWorldServlet extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/plain" );
PrintWriter out = response.getWriter();
out.print( "hello world!" );
}
}
Note: This is more general discussion than answer.
I'm having similar issues coming from Python for 10+ years and diving, as it were, back into Java. I think one thing I'm learning is that the "simplicity" factor of Python is very different from that of Java. Where Python abounds with high-level framework-- things like web.py, Java seems much more lower level. Over the past few months, I've gone from saying "What's the Java way to do this easy in Python thing" to "How does one build up this thing in Java." Subtle, but seems to bring my thoughts around from a Python-centric view to a more Java-centric one.
Having done that, I've realized that standing up a website or service is not simple for a Java outsider, that's because there's a large amount of info I have to (re)grok. It's not as simple as python. You still need a webserver, you need to build a "container" to drop your Java code into, and then you need the Java code (am I wrong on this, everyone? Is there a simpler way?).
For me, working with Scala and Lift has helped- and not even those, but this one thread by David Pollack. This was what I needed to build a Jetty server. Take that, follow the directions (somewhat vague, but might be good enough for you) and then you have a servlet container ready to accept incoming traffic on a port (or 3 ports, in his case). Then you can write some Java code using HTTPServlet or something to go the rest of the way.
Again, this is just what I did to get past that barrier, but I'm still not a Java guru. Good luck.
I've hard about: Apache Mina
But quite frankly I don't even know if it is what you need.
:-/
:)
Jetty is a pretty nice embedded http server - even if it isn't possible to do the mapping like you describe, it should be pretty easy to implement what you are going for.