Server side access data for smartGWT rpc - java

On the server side I want to know how to access data used in an RPCRequest from SmartGwt.
Here is the SmartGwt client code:
private void update() {
RPCRequest request = new RPCRequest();
request.setData("RPC text from client");
request.setActionURL("/Empi-MT/resources/empi/update");
request.setContentType("text/xml");
RPCManager.sendRequest(request,
new RPCCallback() {
public void execute(RPCResponse response, Object obj, RPCRequest request) {
SC.say("Response from the server:" + obj);
}
});
}
Here is the RESTful java server code .
#POST
#Consumes("text/xml")
#Produces("text/xml")
#Path("/update")
public String update() {
return "We got to here";
}
This trivial code works fine, but now I need to know how to access the data that was put into the RPCRequest. How do I do that in the server code?
Thanks,

You look like you may be heading in the wrong direction; if this "update" operation is a CRUD operation on some object, you want to using DataSources - take a look at the QuickStart overview of Data Integration, focusing on RestDataSource.
http://www.smartclient.com/releases/SmartGWT_Quick_Start_Guide.pdf
Also you seem to be starting down the road of using generated REST services, this is almost always wrong - see this FAQ:
http://forums.smartclient.com/showthread.php?t=8159#aExistingRest
Finally if this really is not a CRUD operation, you want to set useSimpleHttp on the RPCRequest, and then the docs for this property explain the different ways data can be sent.
http://www.smartclient.com/smartgwtee/javadoc/com/smartgwt/client/rpc/RPCRequest.html#getUseSimpleHttp()

Related

How to implement Search operation for an Observation Resource Provider for Hapi Fhir server?

I am trying to understand how the RESTful Server in Hapi Fhir works and I wanted to implement some #Search methods for Observation resources.
Currently, I have this #Read operation, which successfully works when trying to access the resource (like this: http://localhost:8080/NewFHIRServer/fhir) from the browser:
#Read()
public Observation readObservationById(#IdParam IdDt theId) {
for (Entry<Long, Deque<Observation>> entry : myPatientIdToObservations.entrySet())
{
for (Observation obs : entry.getValue()) {
if (obs.getId().equals(theId)) {
return obs;
}
}
}
throw new ResourceNotFoundException(theId);
}
However, when I try to do something similar for the #Search operation, I am getting errors. I would like to be able to get the response by running the search like this (or similar):
Bundle response = client
.search()
.forResource(Observation.class)
.where(Observation.SUBJECT.hasId("Patient/1"))
.execute();
What parameters do I need to have in my #Read method in order to make this possible? The error I am getting right now is the following:
The FHIR endpoint on this server does not know how to handle GET
operation[Observation] with parameters [[subject]]
and it is obvious why it doesn't work, because my header looks like this:
public Observation searchObservationById(#IdParam IdDt theId)
I have been looking at examples to try to figure this out and I don't quite understand what the syntax in this parameter means:
public List<Patient> getPatient(#RequiredParam(name = Patient.SP_FAMILY) StringParam theFamilyName)...
How would you make the query in order to use this last example?
Thank you
To implement a search method, you need to use #Search instead of #Read on the method. You then use zero-or-more parameters annotated with #OptionalParam or #RequiredParam.
To make your specific example work, you need a search method which implements the _id search parameter, e.g.
#Search
public List<Patient> getPatient(#RequiredParam(name = Patient.SP_RES_ID) StringParam theId) {
}

Is it possible to get a #PathParam or #QueryParam from the MessageBodyReaderContext in a RestEASY MessageBodyReaderInterceptor?

My service:
#POST
public String setData(#QueryParam("id") Long is, MyObject payload) {
...
}
or
#POST
public String setData(#PathParam("id") Long is, MyObject payload) {
...
}
My interceptor on the server:
Object read(MessageBodyReaderContext context) throws IOException, WebApplicationException {
Class mypayloadtype = context.getType;
InputStream mypayloadinpustream = context.getInputStream();
Long myidparam = ???????? // how to get the query or path param here?
}
EDIT: To be a bit more concrete:
What I'd like to do is to grab the XML and store it based on the parameters in a separate audit system. Maybe PreProcessInterceptor / PostProcessInterceptor are the better choices?
Any hints or alternative ways to get the param when the xml is still available for preprocessing?
Miguel
I just stumbled over the same problem today. I needed the #PathParams and #QueryParams in the read() method and ended up with something like this:
public class MyInterceptor implements PreProcessInterceptor, MessageBodyReaderInterceptor
{
private static ThreadLocal<UriInfo> uri = new ThreadLocal<UriInfo>();
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
{
uri.set(request.getUri);
...
}
public Object read(MessageBodyReaderContext context)
{
String param = uri.get().getPathParameters().getFirst("myidparam");
...
}
}
Although when thinking about it now - I'm not quite sure, if just using PreProcessInterceptor/PostProcessInterceptor will also do the trick for my (and maybe your) problem. I'll have another look tomorrow.
I am not an expert on the topic but to me it seems as if the MessageBodyReaderContext interface does not really know if it is on the server or the client side, so it cannot expose the request or its parameters / path parts etc.
So as far as I know this is not possible.
If your code knows that it lives on the server side of the rest
communication, maybe you can use a servlet filter to store the request
in a ThreadLocal and then access it from there while the request is
handled, somewhat similar to RequestContextFilter / RequestContextHolder from the spring framework? (Then the request object does not know anything about the annotations of your service, but instead one has to extract the information manually from the request. This means to have the same information in two places, so there has to be a better solution ...)
Edit: after looking at some examples I get the vague feeling that if you want to read the input stream to create an object and add path parameters to it, MessageBodyReaderInterceptor is simply not the way to go. Instead set up a MessageBodyReader which constructs the object from the request body data, and this then will be passed into the public String setData(#PathParam("id") Long is, MyObject payload), assuming that this method is annotated with a #Consumes which matches the #ConsumeMime annotation for the MessageBodyReader. There you might be able in the setData to set the missing id on the object read from the request body. Some examples related to this seem to be here: How to get full REST request body using Jersey? (but for Jersey, not jBoss :-/)
However I am not sure if that works for you, and I also feel I completely overestimated my ability to answer this question appropriately, so I hope someone more knowledgeable comes in with a better solution.

Desktop program communicating with server

I am in the process of moving the business logic of my Swing program onto the server.
What would be the most efficient way to communicate client-server and server-client?
The server will be responsible for authentication, fetching and storing data, so the program will have to communication frequently.
it depends on a lot of things. if you want a real answer, you should clarify exactly what your program will be doing and exactly what falls under your definition of "efficient"
if rapid productivity falls under your definition of efficient, a method that I have used in the past involves serialization to send plain old java objects down a socket. recently I have found that, in combination with the netty api, i am able to rapidly prototype fairly robust client/server communication.
the guts are fairly simple; the client and server both run Netty with an ObjectDecoder and ObjectEncoder in the pipeline. A class is made for each object designed to handle data. for example, a HandshakeRequest class and HandshakeResponse class.
a handshake request could look like:
public class HandshakeRequest extends Message {
private static final long serialVersionUID = 1L;
}
and a handshake response may look like:
public class HandshakeResponse extends Message {
private static final long serialVersionUID = 1L;
private final HandshakeResult handshakeResult;
public HandshakeResponse(HandshakeResult handshakeResult) {
this.handshakeResult = handshakeResult;
}
public HandshakeResult getHandshakeResult() {
return handshakeResult;
}
}
in netty, the server would send a handshake request when a client connects as such:
#Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
Channel ch = e.getChannel();
ch.write(new HandshakeRequest();
}
the client receives the HandshakeRequest Object, but it needs a way to tell what kind of message the server just sent. for this, a Map<Class<?>, Method> can be used. when your program is run, it should iterate through the Methods of a class with reflection and place them in the map. here is an example:
public HashMap<Class<?>, Method> populateMessageHandler() {
HashMap<Class<?>, Method> temp = new HashMap<Class<?>, Method>();
for (Method method : getClass().getMethods()) {
if (method.getAnnotation(MessageHandler.class) != null) {
Class<?>[] methodParameters = method.getParameterTypes();
temp.put(methodParameters[1], method);
}
}
return temp;
}
this code would iterate through the current class and look for methods marked with an #MessageHandler annotation, then look at the first parameter of the method (the parameter being an object such as public void handleHandshakeRequest(HandshakeRequest request)) and place the class into the map as a key with the actual method as it's value.
with this map in place, it is very easy to receive a message and send the message directly to the method that should handle the message:
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
try {
Message message = (Message) e.getMessage();
Method method = messageHandlers.get(message.getClass());
if (method == null) {
System.out.println("No handler for message!");
} else {
method.invoke(this, ctx, message);
}
} catch(Exception exception) {
exception.printStackTrace();
}
}
there's not really anything left to it. netty handles all of the messy stuff allowing us to send serialized objects back and forth with ease. if you decide that you do not want to use netty, you can wrap your own protocol around java's Object Output Stream. you will have to do a little bit more work overall, but the simplicity of communication remains intact.
It's a bit hard to say which method is "most efficient" in terms of what, and I don't know your use cases, but here's a couple of options:
The most basic way is to simply use "raw" TCP-sockets. The upside is that there's nothing extra moving across the network and you create your protocol yourself, the latter being also a downside; you have to design and implement your own protocol for the communication, plus the basic framework for handling multiple connections in the server end (if there is a need for such).
Using UDP-sockets, you'll probably save a little latency and bandwidth (not much, unless you're using something like mobile data, you probably won't notice any difference with TCP in terms of latency), but the networking code is a bit harder task; UDP-sockets are "connectionless", meaning all the clients messages will end up in the same handler and must be distinguished from one another. If the server needs to keep up with client state, this can be somewhat troublesome to implement right.
MadProgrammer brought up RMI (remote method invocation), I've personally never used it, and it seems a bit cumbersome to set up, but might be pretty good in the long run in terms of implementation.
Probably one of the most common ways is to use http for the communication, for example via REST-interface for Web services. There are multiple frameworks (I personally prefer Spring MVC) to help with the implementation, but learning a new framework might be out of your scope for now. Also, complex http-queries or long urls could eat your bandwidth a bit more, but unless we're talking about very large amounts of simultaneous clients, this usually isn't a problem (assuming you run your server(s) in a datacenter with something like 100/100MBit connections). This is probably the easiest solution to scale, if it ever comes to that, as there're lots of load-balancing solutions available for web servers.

Is there a way to generate boilerplate code for RESTful stacks?

As I get more into RESTful APIs, the (good) simplicity of the approach means that you generate a LOT of boilerplate code, and code that has to match in three or four different places, e.g. for a Jersey-based stack:
HTML on the web page which provides controls (a button Create Foo)
JS on the web page which formulates the JSON and the request to create a Foo
A FooRest class method to handle the request and create a Foo
A Foo class to instantiate, which will manipulate the data structure
Are there tools which provide a starting point for some or all of this code automatically, possibly starting from something straightforward like a JSON data structure? E.g., provide:
card: {
methods: [GET],
}
handOfCards: {
methods: [GET POST PUT DELETE],
}
and at the very least end up with Ajax requests, CardRest and HandOfCardsRest classes with the specified methods stubbed out, and Card and HandOfCards classes with properties or getters/setters?
Have you tried Backbone.js? It is a JavaScript library that handles REST Ajax requests for you. It allows you to define your models to wrap the data and provides setters, getters, save and delete functions, etc.
It also allows you to bind the models to views which generate the UI HTML.
I think nearly any *rails application does all of this for you. Grails is my favorite right now, and once you get the initial setup done (a single command) you create domain classes with another command.
Once those are created, you can generate both views (html) and controllers for handling all of these actions with a single command, and the boiler plate is sufficient for a lot of initial sites. It will even create test cases for you, although you'll need to define what the actual tests do. You can program it by convention very easily, or create your own mappings from URLs -> controller actions. It has a ton of plugin support and easily handles remote submission of forms (via javascript) built in.
It doesn't take a json data structures for creation, but the domains are very easily created (using groovy) and it autowires getter/setters, service injections, etc as it is based on the Spring Framework.
Your goal should probably not be code generation of boilerplate but actually writing less code.
Spark is a Java micro web framework based on Sinatra.
Here's some example code:
import static spark.Spark.*;
import spark.*;
public class HelloWorld {
public static void main(String[] args) {
get(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. Show something ..
}
});
post(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. Create something ..
}
});
put(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. Update something ..
}
});
delete(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. annihilate something ..
}
});
options(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. appease something ..
}
});
}
}
An alternate (or addition) to Juan's answer, you might want to check out Knockback.js , which takes the best of Knockout and adds the best of Backbone.js . Backbone has support for RESTful API's via it's "sync" functions. Quoting their website:
The method signature of Backbone.sync is sync(method, model,
[options])
method – the CRUD method ("create", "read", "update", or "delete")
model – the model to be saved (or collection to be read)
options – success and error callbacks, and all other jQuery request options
You might want to try a different approach altogether and try somethink like project lombok. It will at least let you nix all your getters and setters.

An example of a Google Web Toolkit (GWT) Create Read Update and Delete (CRUD) Application

Hello
Does anybody know of any examples of a Google Web Took (GWT) - based Create Read Update and Delete application.
That is, an application which uses the GWT to manipulate and display the contents of a database.
Thanks
There are not too many such examples online.
But this is how I usually do it:
Lets assume that you want to get all the contents of a certain table from the database:
in GreentingService.java do following:
public interface GreentingServiceextends RemoteService
{
ArrayList getEverything();
}
in GreentingServiceSync.java do following:
public interface GreentingService
{
void getEverything(AsyncCallback callback);
}
finally in GreentingServiceImpl do following:
public class GreentingServiceIMPL extends RemoteSericeServlet implments GreentingService
{
public ArrayList<String> getEverything()
{
String query="Select * from....";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn=DriverManager.getConnection(url,user,password);
Statement stmt = conn.createStatement();
//get stuff out of daatabase here and retun as an arraylist
}
}
this is how you will call this method and use the data:
public Someclass implements EntryPoint
{
public void onModuleload()
{
SQLRunnerAsync sql = (SQLRunnerAsync) GWT.create(SQLRunner.class);
AsyncCallback> callback = new AsyncCallback>(){
#Override
public void onFailure(Throwable caught) {
//do nothing
}
#Override
public void onSuccess(ArrayList<String> result) {
for(int i = 0; i < result.size(); i++)
{
}
}};
sql.getEverything(callback);
...............
}//onModulelOad
}//class
Following is a great tutorial:
http://altair.cs.oswego.edu/~tenberge/tenbergen.org/misc/DB-Access-in-GWT-The-Missing-Tutorial.pdf
GWT is a client side technology, so basically gives you only the UI. Any CRUD process would happen in the server side, which could be any J2EE code.
Anyway you can take a look to the StockWatcher Example which gives you a good approach to your question (you need to implement the server side storage)
Also take a look to the RequestFactory documentation
Does it help you?
This is a skeleton CRUD application, I this would be helpful for someone looking answer for the same question
http://code.google.com/p/gwtcrudapp/
This is a web-based CRUD-Application that I've wrote for my employer over the last few years and now got permission to open-source it:
https://github.com/fhcampuswien/atom
It uses GWT for the front-end and Hibernate to persist the data in the backend. The data-structure only needs to be defined in one central place (the DomainObject classes), since both GUI and backend are written in a generic way that is not dependent on the data-structure.
I'd love to hear comments or answer questions about it if anybody finds the time to take a look.

Categories

Resources