I need to create a rest server and client.
I stumbled upon this tutorial which uses sockets. I want to be able to use REST calls, possibly HTTP, because the clients will be actually in different languages.
Instead of using Socket api from java.net.* what should i use ? if i use Socket API can I use c++ and php to communicate with this server? or should i go with REST?
any directions appreciated.
There's a lot of things you can use to create rest services, and then they can be consumed by almost anything. Of particular awesomeness is the ability to hit them in your web browser, just because we're all so familiar with them.
When I need a 'quick and dirty' rest solution, I use Restlet - I won't claim it's the only solution, but it's the easiest I've ever worked with. I've literally said in a meeting "I could have XYZ up in 10 minutes." Someone else in the meeting called me on it, and sure enough, using Restlet I was able to get a functioning REST server running with the (very simple) features I said I would get in the meeting. It was pretty slick.
Here's a barebones server that has one method, returning the current time. Running the server and hitting 127.0.0.1:12345/sample/time will return the current time.
import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;
/**
* This Application creates an HTTP server with a singple service
* that tells you the current time.
* #author corsiKa
*/
public class ServerMain extends Application {
/**
* The main method. If you don't know what a main method does, you
* probably are not advanced enough for the rest of this tutorial.
* #param args Command line args, completely ignored.
* #throws Exception when something goes wrong. Yes I'm being lazy here.
*/
public static void main(String...args) throws Exception {
// create the interface to the outside world
final Component component = new Component();
// tell the interface to listen to http:12345
component.getServers().add(Protocol.HTTP, 12345);
// create the application, giving it the component's context
// technically, its child context, which is a protected version of its context
ServerMain server = new ServerMain(component.getContext().createChildContext());
// attach the application to the interface
component.getDefaultHost().attach(server);
// go to town
component.start();
}
// just your everyday chaining constructor
public ServerMain(Context context) {
super(context);
}
/** add hooks to your services - this will get called by the component when
* it attaches the application to the component (I think... or somewhere in there
* it magically gets called... or something...)
*/
public Restlet createRoot() {
// create a router to route the incoming queries
Router router = new Router(getContext().createChildContext());
// attach your resource here
router.attach("/sample/time", CurrentTimeResource.class);
// return the router.
return router;
}
}
And here's the 'current time resource' that it uses:
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* A resource that responds to a get request and returns a StringRepresentaiton
* of the current time in milliseconds from Epoch
* #author corsiKa
*/
public class CurrentTimeResource extends ServerResource {
#Get // add the get annotation so it knows this is for gets
// method is pretty self explanatory
public Representation getTime() {
long now = System.currentTimeMillis();
String nowstr = String.valueOf(now);
Representation result = new StringRepresentation(nowstr);
return result;
}
}
JAX-RS is the API for REST in Java. There are a lot of implementations, but the main ones are Jersey (the reference implementation), Apache's CXF and Restlet.
Usually, you don't create a server. You create a web application and deploy it on the server or servlet container. Some servlet containers are embedable into your web application, e.g. Jetty. Poppular free servlet containers are Tomcat, Glassfish, Jetty, etc.
For Restlet, it is not a servlet container. It is a framework that allow you to create a wep application with RESTful styles. So this should not be confused.
If you decide to use servlet container, then the problem is how you can create a web application with the RESTful styles. REST is not a technology - it is a design principle. It is a concept of how you should create the interface.
The design of REST is stateless so you do not need to store the state of the transaction. All information from a request should be sufficient to produce a respose to client.
There are several servlet framework that allows you to implment the REST styles easily. Some of them are very sophisticated, e.g. Spring framework.
Download JBoss 7. Problem solved.
Heres a restful service:
#Path("/myservice")
public class MyService {
#GET
#Produces(MediaTypes.TEXT_PLAIN)
public String echoMessage(#QueryParam("msg") String msg) {
return "Hello " + msg;
}
}
Create a WAR. Deploy. Open up browser and go http://myserver/myapp/myservice?msg=World. Done!
I would say go with an HTTP based RESTful service. It's rapidly becoming a defacto standard. Check my answer to this similar question for pros and cons.
This is the best one out there. Spring MVC which has lot of REST capabilities in itself. This takes just a single jar file to be included. And you are all set to use all it's capabilities. Even as simple as the below guy explained in JBOSS and much more flexibility as well.
http://java.dzone.com/articles/spring-30-rest-example
I use JBoss 6 with RestEasy. I have created a tutorial located here. I hope this helps you.
You're also welcome to see my very simple example for REST server implementation here.
Related
I have two web servers A and C. Because of rules, policies etc A cannot communicate directly with C' (Crequires requests to have special security headers andA` does not support this)
I want to create a "proxy" called B in Java, to facilitate communication between A and B but I having trouble with it conceptually.
When you create a proxy, don't you have to change the hard coded URLs on all your services to now travel through the proxy? And then I suppose you must pass your destination as a query parameter somehow, for example
http://proxy.com/?destination=mydestination.com
Is this how a proxy would work?
(I have found a few similar questions but they do not resolve the fundamental question I am having i.e. How packets reaches Destination throgh proxy servers?)
Don't write your own proxy from scratch that will be a redo, there are a plenty of proxy implementations out there
Spring framework
Spring Boot implementation for (Netflex/Zuul) https://github.com/Netflix/zuul / https://spring.io/guides/gs/routing-and-filtering/
Standard Servlet
https://github.com/mitre/HTTP-Proxy-Servlet
in case if you are intrested in how you can build up your own proxy , here is a simple example using spring framework (Servlet implementation is not that far from spring implementation)
#RestController
public class ProxyController {
/**
* request handler for all the requests on the registered context intended to be proxied
*
* #param request
* #return
*/
#RequestMapping("/**")
public String defaultGateway(HttpServletRequest request) {
// edit the original request headers,body etc
String originalPath = request.getRequestURI();
// then fire another HTTP request using the same URI
return "ProxiedResult"; // return back the result you get from
}
}
the example above is a start point on how to implements HTTP proxy or how it is working there are many things to cover which is droped off like security for instance
I am totally new to the whole Google Cloud Endpoint/Google App Engine world. If you have gone through the Hello World example that Google provides(and you probably have), you might remember that there are 2 classes that are auto-generated for you: MyBean and MyEndpoint.
These are something like this:
/**
* The object model for the data we are sending through endpoints
*/
public class MyBean {
private String myData;
public String getData() {
return myData;
}
public void setData(String data) {
myData = data;
}
}
And,
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.DJ.example.com",
ownerName = "backend.myapplication.DJ.example.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) {
MyBean response = new MyBean();
response.setData("Hi, " + name);
return response;
}
}
Now, I examined the code in index.html(which gets opened on deploying the backend). I found the following call in the javascript:
gapi.client.myApi.sayHi({'name': name}).execute(
Now, I can see that myApi is the name through annotation and sayHi() is the corresponding method, What I don't understand is the concept of exposing an API and annotation is aiding in that. There isn't any information about exposing APIs.
Could anyone help me understand this?
I think your question can be divided in 3 parts:
1/ What is exposing an API?
Basically, you are offering an access to your business logic through an Interface (the API), with full control on what you want to show or not. This Stack Exchange answer is a great explanation: https://softwareengineering.stackexchange.com/questions/203844/what-does-it-mean-to-expose-something
2/ What are these annotations in the auto-generated endpoints class?
If I can summarize it like that, Google endpoint is a "framework" which generates "default" APIs based on your java beans. By default you get CRUD operations in the API, but you can modify and/or enrich the endpoint to offer more complex business logic. The Endpoints classes that are generated include specific annotations that are used by the framework (in particular while generating a corresponding servlet) and define the URI you will call to interact with the methods of the APIs. See https://cloud.google.com/appengine/docs/java/endpoints/
3/ What is this gapi.client call?
gapi stands for Google API Client Library. It is the library that is offered by Google to interact with Endpoints from a web browser. See https://developers.google.com/api-client-library/javascript/
You could use other methods to call the Endpoint APIs, like jquery Ajax methods (http://api.jquery.com/jquery.ajax/), since Endpoints follow the REST architectural style. Note that you can call your endpoints from other "clients" than a web browser, e.g. an Android or iOS App. In these cases, you would not use the Google API Client Library but some other libraries.
I hope this clarifies a bit. Do not hesitate to ask for more details.
I have the task of creating a web service that takes requests from multiple clients. I am new to web services so i used this tutorial:
http://www.java-forums.org/blogs/web-service/1145-how-create-java-web-service.html
This is exactly what i am looking for. A web service with no java ee.
It is preferable that is stick with java se, it's a policy that is prefered to be kept.
Now i would like to go one step further and implement the service so that it processes requests from multiple clients that operate on a shared resource.
Ideally i would like something like this:
Client client = new Client();
client.processRequest(string);
And the web service will process the requests in the order they arrive. The requests will come in as an request is processed so it will be kept in a stack.
The problem is i just on't know how to send the response back to the specific client. The response will be a string. The only thing i came up with, at least in principle, is to send a object that remembers where it came from but that just seems the web services job.
I have searched the internet but did not find a solution.
If possible using only SE please help.
If you think it is not possible without EE you can say so, but i would very much like an answer using only SE
I think what you are trying to implement is an Asynchronous Webservice. The following link tells you how to implement it in Java SE.
http://java.dzone.com/articles/asynchronous-java-se-web
You can do this using the Endpoint.publish methods in Java SE. First, you create a simple "endpoint interface":
package com.example;
import javax.jws.WebService;
#WebService
public interface ExampleService {
String getDateTime();
}
Then you specify that interface in an implementation class. As you can see, both classes must be annotated with #WebService.
package com.example;
import java.io.IOException;
import java.net.URL;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import javax.xml.ws.Service;
import javax.xml.namespace.QName;
#WebService(endpointInterface = "com.example.ExampleService",
serviceName = "ExampleService",
portName = "timeService",
targetNamespace = "http://example.com/time")
public class ExampleServiceImpl
implements ExampleService {
public String getDateTime() {
return String.format("%tc", System.currentTimeMillis());
}
public static void main(String[] args)
throws IOException {
// Create server
Endpoint endpoint =
Endpoint.publish("http://localhost:8080/example",
new ExampleServiceImpl());
URL wsdl = new URL("http://localhost:8080/example?wsdl");
// Create client
Service service = Service.create(wsdl,
new QName("http://example.com/time", "ExampleService"));
ExampleService e = service.getPort(ExampleService.class);
// Test it out
System.out.println(e.getDateTime());
endpoint.stop();
}
}
By default, JAX-WS will treat all public methods of an endpoint interface as web methods (since that is commonly what developers will want). You can have more control by placing the #WebMethod annotation on only the methods you want exposed as web services.
See the JAX-WS specification for all the details.
I've written an an API giving some methods like
runApp();
stopApp();
doSomethingElse();
currently I have a jar file with which I run these methods.
I want to be able to invoke these method by http.
For example, going to : http://localhost:8080/something/runApp
will invoke runApp() method.
I've heard that this should be done with webservices, and particularly REST API.
Is webservices the only way to achieve this?
And if so, can someone summarize the simplest ways to implement this ability, or point me to an existent summary?
Thanks.
Here's a RESTful API example based on your pseudocode, with JAX-RS:
#Path("/something")
public class MyApp {
#GET
#Path("/runApp")
public Response runApp() {
return Response.ok("Running app").build();
}
#GET
#Path("/stopApp")
public Response stopApp() {
return Response.ok("Stopping app").build();
}
#GET
#Path("/doSomethingElse") {
return Response.ok("Doing something else").build();
}
}
Which when built and deployed into any JEE5 or JEE6 web capable container will allow you to access services those services at:
http://localhost:8080/something/runApp
http://localhost:8080/something/stopApp
http://localhost:8080/something/doSomethingElse
Assuming your server is running on localhost:8080, of course. Having said that, nothing in this example is really RESTful, and would be better implemented using JAX-WS.
You've pretty much described exactly what a web service is. Code gets run when you hit a particular URL with a particular type of request.
As to how to build a web service in Java, there's a huge amount of documentation out there on the web (and SO) on that. You should not have any trouble finding useful articles.
I want to build a website that is basically a blog with a little bit of custom java code to be run via ajax calls on the server.
My initial thoughts were to build the blog in wordpress or drupal or something similar, then run a very simple java webapp to receive the ajax requests. However, having no experience with Java webapps, I am not sure of a framework made for such simple tasks. Nor have I ever used wordpress/drupal/etc to know how easy it would be to integrate these java ajax calls.
Then I thought, perhaps I should just run some Java CMS instead of drupal, wordpress, etc. This should allow me to easily integrate my ajax hooks. But again, I have no experience with any Java CMS's to know which would work well.
Can someone with some Java webapp experience give their recommendation?
Second time in two posts I have made the same recommendation (!) but maybe look at the free Community edition of Liferay portal server? It runs on Java (easy on tomcat+mysql) and has blogs and CMS and other features included. There is also the option of modifying the source code (subject to the license) to add your custom behaviour.
What exactly are you looking to do in Java that you couldn't accomplish in PHP if you were to use Wordpress or Drupal?
Wordpress is rather easy to setup. If you have any web app experience at all and minor knowledge of PHP then you shouldn't have any problems.
Spring MVC is a fairly straightforward Java web app framework. You can run it on Google App Engine with relative ease and there's a lot of documentation / support online.
One thing to consider is that your AJAX calls will need to be made to the same domain that your CMS is on. If you're creating two separate web apps then they need to appear to be on the same domain.
It's a bit difficult to give any detailed advice not knowing what your particular requirements are but I hope this helped a little.
I think you shouldn't use any framework. Just create a servlet. Because even if you use a framework, you still have to understand what a servlet is. These code are from oracle's site, modify doGet to do your processing. Or you could change it to doPost.
import java.io.*;
// Packages for Servlets
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
/**
* Initializes the servlet. The method is called once, automatically, by the
* Java Web Server when it loads the servlet. The init() method should save
* ServletConfig object so that it can be returned by the getServletConfig()
* method.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
/**
* Method to process HTTP GET requests. In this method a Simple HTML page
* displaying "Hello Oracle World" is built and presented to user.
* The parameters of doGet() method is
* 1) HttpServletRequest object, which encapsulates the data from the client
* 2) HttpServletResponse object, which encapsulates the response to the client
**/
public void doGet(HttpServletRequest p_req, HttpServletResponse p_res)
throws ServletException, IOException {
// Sets the content type of the response
p_res.setContentType("text/html");
// Create a ServletOutputStream to write the output
ServletOutputStream l_out = p_res.getOutputStream();
// Use ServletOutputStream to print the Hello Oracle World String in
// the HTML page
l_out.println("<HTML><HEAD><TITLE>Hello Oracle World</TITLE></HEAD>");
l_out.println("<BODY BGCOLOR =\"lightgrey\"><CENTER><BR><BR>");
l_out.println("<TABLE BORDER=4 BGCOLOR =\"blue\">");
l_out.println("<TR><TD align =\"center\" valign=\"center\" >");
l_out.println("<FONT face=\"Arial,helvetica\" color =red size=5>");
l_out.println(" Hello Oracle World </FONT></TD></TR></TABLE>");
l_out.println("</BODY></HTML>");
l_out.close(); // Close the ServletOutputStream
}
/**
* Override the getServletInfo() method which is supposed to return information
* about the Servlet, e.g. the servlet name, version, author and copyright
* notice. This is not required for the function of the HelloWorld servlet but
* can provide valuable information to the user of a servlet who sees the
* returned text in the administration tool of the Web Server.
**/
public String getServletInfo() {
return "Hello World servlet 1.0 by Reghu";
}
public void destroy() {
super.destroy();
}
}