Multiple get methods in single Resource class with Restlet - java

here is my code :
this is my application class >>>
import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;
import firstSteps.UserResource;
public class FirstStepsApplication extends Application {
#Override
public synchronized Restlet createRoot() {
Router router = new Router(getContext());
router.attach("/hello", UserResource.class);
router.attach("/isuserloggedin",UserResource.class);
return router;
}
}
this is resource class >>>
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* Resource which has only one representation.
*
*/
public class UserResource extends ServerResource {
#Get
public String userLogin() {
return "This is userLogin method";
}
#Get
public boolean isUserLoggedIn(){
return false;
}
}
/hello & /isuserloggedin are mapped to same to resource class but
what i want is : when there is /hello then userLogin method should be called
and when there is /isuserloggedin then isUserLoggedIn must be called .
is this possible ??
or am i going wrong?
if this is not possible then any one can tell me any other alternative ?

In Restlet 2.1 (try M7 or above), it is possible to dispatch two HTTP GET calls to two Java methods in the same resource class. This is done by leveraging query parameters like this:
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* Resource which has only one representation.
*
*/
public class UserResource extends ServerResource {
#Get
public String userLogin() {
return "This is userLogin method";
}
#Get("?loggedIn")
public boolean isUserLoggedIn(){
return false;
}
}
However, as pointed already, you would be better off using a separate resource class.

Some time has passed since my last experience with Restlet, anyway, if you are implementing a fully REST API, I would expect the two to be separate resources if they really need to be. Otherwise, a resource should be mapped to exactly one representation, IMHO.
What is the benefit of having two URIs mapped to one resource class, instead of having two, each implementing the GET method? It seems to add a bit of ambiguity there, with no benefit.
I would return the status (logged or not) information in the user representation.
Now, for sake of completeness, I find a bit difficult to understand your API semantics: can I ask for the logged status of any user, or just mine? It's not very clear, but I understand that it was not the main point.
Just as a nice reading, you may want to have a look at some popular REST api to see how they manage issues similar to yours, ie. I like Github Users' API particularly.
Hope it helps.

Related

Why can't classes that use EJB #Schedule be abstract Classes?

I need to schedule a task and I'm using EJB #Schedule to do so. It's working fine, however I thought I might try to generalize my design so that I can extend from some abstract scheduler, inherit certain functionality, and specify additional functionality in the sub classes extending the abstract class. This way, when I need additional schedulers that perform similar actions, I don't have to rewrite a bunch of code. I wrote it, didn't get any errors, and I thought all was well, and then when I tried to restart my server,
I got:
EJB class com.schedule.SubmissionScheduler must not be defined as abstract : mcftEAR#mcftWeb.war#SubmissionSchedule in the console.
Maybe I don't know enough about how the #Schedule annotation works, but I can't think of any reason abstract classes won't be allowed for this. Any insight would be appreciated
import java.util.List;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
public abstract class SubmissionScheduler {
public abstract SubmissionScheduler getInstance();
#Schedule(hour= "0")
public void every24Hours() {
// Pull all forms and submit every 24 hours
List<Form> forms = getFormsThatAreReadyForSubmission();
// Loop through the list of forms and submit
if (forms != null || !forms.isEmpty()) {
for (Form form : forms) {
form.getFormDao().submit());
}
}
}
...Then I have another class which extends this one.
EDIT: In addition to not being able to make it an abstract class, it won't allow for the class to be final either...Why??
Basically you need an instance of your bean to run any function - in your case scheduled function.
It is impossible to run a function from abstract class cause it's abstract - a container cannot create instance to run your code. So it have to be non abstract to create instance and run a method.

Prevent using some APIs of a depending package

We have some code wrapping API of a third-party package, and now we don't want our team members to mistakenly use the third-party package directly, is there any way to prevent it? (Such as add some kind of checking in UT). Example:
Code in a third-party package (so we cannot change it):
class OrigProvider {
public static String getSomething() { return sth;}
}
Code in my package (we need to third-party package):
class MyProvider {
public static String getSomething() {
sth = OrigProvider.getSomething;
process(sth);
return sth;
}
}
And in our code, if someone incorrectly use OrigProvider.getSomething, our program will be wrong silently, so how to guarantee no one use the OrigProvider.getSomething?
Thanks in advance!

Entity to DTO conversion in a J2EE application using an enum?

This is one of those topics I don't even know how to search in google (tried already, most of the results were for C#), so here I go:
I'm messing around with our huge application, trying to get to work a brand new DAO/Entity/Service/DTO.. euh...thing. I've been left more or less on my own, and, again, more or less, I'm getting to understand some of the hows and maybe one or two of the whys.
The thing is that I got all, the way "up", from the DB to the Service:
I got a DAO class which executes a query stored on an Entity class. After executing it, it returns the Entity with the values.
The service receives the Entity and, somehow, transforms the Entity to a DTO and returns it to whenever is needed.
My problem is with the "somehow" thing the code goes like this:
DTOClass dto = ClassTransformerFromEntityToDTO.INSTANCE.apply(entityQueryResult);
I went into ClassTransformerFromEntityToDTO and found this:
public enum ClassTransfomerFromEntityToDTO implements Function<EntityClass,DTO Class> ) {
INSTANCE;
#Override
public DTOClass apply(EntityClass entityInstance) {
/*Code to transform the Entity to DTO and the return*/
}
}
The class that this... thing, implements, is this:
package com. google .common . base;
import com. google .common . annotations. GwtCompatible ;
import javax. annotation .Nullable ;
#GwtCompatible
public abstract interface Function <F , T >
{
#Nullable
public abstract T apply (#Nullable F paramF) ;
public abstract boolean equals (#Nullable Object paramObject) ;
}
I'm in the classic "everyone who where at the beginning of the project fled", and no one knows why is this or what is this (The wisest one told me that maybe it had something to do with Spring), so, I have two main questions (which can be more or less answered in the same side):
1) What's this? What's the point of using an enum with a function to make a conversion?
2) What's the point of this? Why can I just make a class with a single function and forget about this wizardry?
not sure there's much to answer here... And I'm adding an answer to illustrate my thoughts with some code I've seen, but that you have is horrible. I've actually seem similar stuff. My guess is that that codes actually precedes Spring. It's used as some sort of Singleton.
I have seen code like this, which is worse:
public interface DTO {
find(Object args)
}
public class ConcreteDTO1 implements DTO {
...
}
public class ConcreteDTO2 implements DTO {
...
}
public enum DTOType {
CONCRETE_DTO1(new ConcreteDTO1(someArgs)),
CONCRETE_DTO2(new ConcreteDTO2(someOtherArgs))
private DTO dto;
public DTOType(DTO dto) {
this.dto = dto;
}
public DTO dto() {
return dto;
}
}
and then the DTOs are basically accessed through the Enum Type:
DTOType.CONCRETE_DTO1.dto().find(args);
So everyone trying to get hold of a DTO accesses it through the enum. With Spring, you don't need any of that. The IoC container is meant to avoid this kind of nonsense, that's why my guess is that it precedes Spring, from some ancient version of the app when Spring was not there. But it could be that someone was wired to do such things regardless of whether Spring was already in the app or not.
For that kind of stuff you're trying to do, you're better of with the Visitor pattern. Here's an example from a different answer: passing different type of objects dynamically on same method
It's me. From the future.
Turns out that this construct is a propossed Singleton Implementation, at least on "Effective Java 2nd edition".
So, yeah, Ulise's guess was well oriented.

What is the right way to organize Jersey resources using inheritance and generics?

I'm developing an app with Jersey where I have many resources. Although main functionality of these resources varies, they share lots of common methods (like list, read, update and etc). The app runs on Google App Engine and uses Guice for dependency injection.
My first approach was to have a generic AbstactResource which contains all common logic, and it's respectively extended by all other resources which add their required custom methods.
public class AbstractResource<T> {
#GET
public ListPage<T> list(#QueryParam("limit") Integer limit,
#QueryParam("start") Integer start) {
// ... implementation
}
#GET
#Path("/{id}")
public T get(#PathParam("id") Long id) {
// ... implementation
}
And sample resource looks like:
public class TenantResource extends AbstractResource<Tenant> {
// custom resource related methods here
}
Everything works fine in this case. The problems appear when I add one more level of abstraction. Let's say if I want to store history and changelogs only for some of my resources. I've created one more abstract class extending AbstractResource called AudiatableResource which adds the required functionality.
public abstract class AuditableResource<T extends AuditableModel>
extends AbstractResource {
// here I override update and create methods to save changelogs
}
As you see the type parameter in this case has changed (now it extends AuditableModel).
New concrete resources will look like:
public class PropertyResource extends AuditableResource<Tenant> {
// custom resource related methods here
}
In this case everything still works, but this time I'm getting lots of warning messages on start-up:
WARNING: Return type T of method public T com.pkg.AbstractResource.get(java.lang.Long) is not resolvable to a concrete type
WARNING: Return type T of method public T com.pkg.AbstractResource.getNew() is not resolvable to a concrete type
WARNING: Return type com.pkg.data.ListPage<T> of method public com.pkg.ListPage<T> com.pkg.AbstractResource.list(java.lang.Integer,java.lang.Integer) is not resolvable to a concrete type
I really wonder if this approach is correct using Jersey and if I can just ignore this messages. It would be interesting to know how resources are organized in cases when there are large number of them.
One way to go is to separate the definition of the resources from the implementation.
Have very simple resource classes, defining the different services you want to offer. This way, the API you expose through rest is easily located and audited. The different methods are probably delegates to an implementation class
Implement the business logic of your resources in the implementations, where you might want to use inheritance to factor common behavior.
The reason you get those messages at runtime is that jersey uses runtime information about types in the resource. Generic type information being erased at compile time, it cannot get the actual return type of the generic class methods. If you provide a REST "facade" to your implementation, you can make this explicit.
public class Facade {
private final PropertyResource propertyResource;
public Facade() {
propertyResource = new PropertyResource();
}
#GET
#Path("somepath")
public Tenant something() {
return propertyResource.something();
}
}

Centralized way of organizing urls in Jersey?

Forgive me if I am asking an obvious question (maybe I missed it in the docs somewhere?) but has anyone found a good way to organize their URLs in Jersey Java framework?
I mean organizing them centrally in your Java source code, so that you can be sure there are not two classes that refer to the same Url.
For example django has a really nice regex-based matching.
I was thinking of doing something like an enum:
enum Urls{
CARS ("cars"),
CAR_INFO ("car", "{info}");
public Urls(String path, String args)
...
}
but you can imagine that gets out of hand pretty quickly if you have urls like:
cars/1/wheels/3
where you need multiple path-ids interleaved with one another...
Any tips?
From my experiences with Jersey, when I tried to annotate two places with the same #Path, I had compilation errors and it wouldn't run. This might not always be the case, so the following might help:
You can get an application.wadl file from your Jersey app by simply requesting it from you web resource:
$ curl http://localhost:8080/application.wadl
or if you prefixed your web services under /ws/
$ curl http://localhost:8080/ws/application.wadl
The application.wadl file is an XML file that shows you all of your resources in your running application, as well as what methods you can call on a resource. See the following resource on how this file is laid out.
Well - I assume you have a #Path on each resource? This means you don't have to keep track of URLs across your entire application, rather just within each class - which is relatively easy if you annotate the interface.
Using enums won't work - you can only put contants into an annotation, but using a class holding final static String could work.
public class UrlConst {
public final static RESOURCE_MY_RESOURCE="/resource";
public final static RESOURCE_MY_RESOURCE2="/resource";
public final static OP_GET_ALL="/";
public final static OP_GET_BY_ID="/{id}";
}
#Path(UrlConst.RESOURCE_MY_RESOURCE)
public interface MyResource {
#GET
#Path(UrlConst.OP_GET_ALL)
#Produces(MediaType.APPLICATION_XML)
public ObjectList getAll();
#GET
#Path(UrlConst.OP_GET_BY_ID)
#Produces(MediaType.APPLICATION_XML)
public Object get(#PathParam("id") int id);
}
#Path(UrlConst.RESOURCE_MY_RESOURCE2)
public interface MyResource2 {
#GET
#Path(UrlConst.OP_GET_ALL)
#Produces(MediaType.APPLICATION_XML)
public ObjectList getAll();
#GET
#Path(UrlConst.OP_GET_BY_ID)
#Produces(MediaType.APPLICATION_XML)
public Object get(#PathParam("id") int id);
}
etc.

Categories

Resources