Difference Between org.restlet.Client and org.restlet.resource.ClientResource - restlet

What are the main differences between org.restlet.Client and org.restlet.resource.ClientResource?
I've seen the classes used semi-interchangeably, so I'm mainly just looking for a general rule for when one should be used over the other.

org.restlet.Client is the low-level API to execute REST requests with Restlet. org.restlet.resource.ClientResource internally uses this class to actually access RESTful applications. So ClientResource is generally the class to use in order to execute client requests to such applications.
One very interesting feature you should consider with ClientResource is the ability to use annotated interfaces as described below.
public interface MyRestfulService {
#GET
Contact getContact(String id);
}
Now how to use the interface:
ClientResource cr = new ClientResource("http://...");
MyRestfulService service = cr.wrap(MyRestfulService.class);
Contact contact = service.getContact("id");
As you can see, everything is now hidden to you (conversion, conneg...).
Hope it helps you.
Thierry

Related

Discuss Advantages of multiple endpoints in WCF service

One guy explained this way but not very clear to how to implement it.
From experience:
Using different binding, for example one BasicHttpBinding for Java clients while using WsHttpBinding for .NET clients. Also HTTPS for some and HTTP for others...
Dividing and exposing different contracts/interfaces. For example you have one interface that exposes many operations and you have a cut down interface which does basic things and you publish the second to outside so internal clients use the endpoint for extended interface but external clients use the other one.
For example
interface IFoo
{
void DoBasic();
}
interface IFooInternal : IFoo
{
void DoMore();
}
Now you have One class implementing both:
public class Foo : IFooInternal
{
....
}
And now you expose only one to outside while implementation is in the same class.
the things which i do not understand how to design my service contract in such a way that few operation i will expose to other client and extended feature i will expose to internal client. so if possible just make me understand giving me a small program & code that how it can be possible through multiple endpoints in WCF service. thanks

Differences between Proxy and Decorator Pattern

Can you give any good explanation what is the difference between Proxy and Decorator?
The main difference I see is that when we assume that Proxy uses composition and Decorator uses aggregation then it seems to be clear that by using multiple (one or more) Decorators you can modify/ add functionalities to pre-existing instance (decorate), whereas Proxy has own inner instance of proxied class and delegates to it adding some additional features (proxy behaviour).
The question is - Does Proxy created with aggregation is still Proxy or rather Decorator? Is it allowed (by definition in GoF patterns) to create Proxy with aggregation?
The real difference is not ownership (composition versus aggregation), but rather type-information.
A Decorator is always passed its delegatee. A Proxy might create it himself, or he might have it injected.
But a Proxy always knows the (more) specific type of the delegatee. In other words, the Proxy and its delegatee will have the same base type, but the Proxy points to some derived type. A Decorator points to its own base type. Thus, the difference is in compile-time information about the type of the delegatee.
In a dynamic language, if the delegatee is injected and happens to have the same interface, then there is no difference.
The answer to your question is "Yes".
Decorator Pattern focuses on dynamically adding functions to an object, while Proxy Pattern focuses on controlling access to an object.
EDIT:-
Relationship between a Proxy and the real subject is typically set at compile time, Proxy instantiates it in some way, whereas Decorator is assigned to the subject at runtime, knowing only subject's interface.
Here is the direct quote from the GoF (page 216).
Although decorators can have similar implementations as proxies, decorators have a different purpose. A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.
Proxies vary in the degree to which they are implemented like a decorator. A
protection proxy might be implemented exactly like a decorator. On the other
hand, a remote proxy will not contain a direct reference to its real subject but only
an indirect reference, such as "host ID and local address on host." A virtual proxy
will start off with an indirect reference such as a file name but will eventually
obtain and use a direct reference.
Popular answers indicate that a Proxy knows the concrete type of its delegate. From this quote we can see that is not always true.
The difference between Proxy and Decorator according to the GoF is that Proxy restricts the client. Decorator does not. Proxy may restrict what a client does by controlling access to functionality; or it may restrict what a client knows by performing actions that are invisible and unknown to the client. Decorator does the opposite: it enhances what its delegate does in a way that is visible to clients.
We might say that Proxy is a black box while Decorator is a white box.
The composition relationship between wrapper and delegate is the wrong relationship to focus on when contrasting Proxy with Decorator, because composition is the feature these two patterns have in common. The relationship between wrapper and client is what differentiates these two patterns.
Decorator informs and empowers its client.
Proxy restricts and disempowers its client.
Decorator get reference for decorated object (usually through constructor) while Proxy responsible to do that by himself.
Proxy may not instantiate wrapping object at all (like this do ORMs to prevent unnecessary access to DB if object fields/getters are not used) while Decorator always hold link to actual wrapped instance.
Proxy usually used by frameworks to add security or caching/lazing and constructed by framework (not by regular developer itself).
Decorator usually used to add new behavior to old or legacy classes by developer itself based on interface rather then actual class (so it work on wide range of interface instances, Proxy is around concrete class).
Key differences:
Proxy provides the same interface. Decorator provides an enhanced interface.
Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.
Decorator can be viewed as a degenerate Composite with only one component. However, a Decorator adds additional responsibilities - it isn't intended for object aggregation.
Decorator supports recursive composition
The Decorator class declares a composition relationship to the LCD (Lowest Class Denominator) interface, and this data member is initialized in its constructor.
Use Proxy for lazy initialization, performance improvement by caching the object and controlling access to the client/caller
Sourcemaking article quotes the similarities and differences in excellent way.
Related SE questions/links:
When to Use the Decorator Pattern?
What is the exact difference between Adapter and Proxy patterns?
Proxy and Decorator differ in purpose and where they focus on the internal implementation. Proxy is for using a remote, cross process, or cross-network object as if it were a local object. Decorator is for adding new behavior to the original interface.
While both patterns are similar in structure, the bulk of the complexity of Proxy lies in ensuring proper communications with the source object. Decorator, on the other hand, focuses on the implementation of the added behavior.
Took a while to figure out this answer and what it really means. A few examples should make it more clear.
Proxy first:
public interface Authorization {
String getToken();
}
And :
// goes to the DB and gets a token for example
public class DBAuthorization implements Authorization {
#Override
public String getToken() {
return "DB-Token";
}
}
And there is a caller of this Authorization, a pretty dumb one:
class Caller {
void authenticatedUserAction(Authorization authorization) {
System.out.println("doing some action with : " + authorization.getToken());
}
}
Nothing un-usual so far, right? Obtain a token from a certain service, use that token. Now comes one more requirement to the picture, add logging: meaning log the token every time. It's simple for this case, just create a Proxy:
public class LoggingDBAuthorization implements Authorization {
private final DBAuthorization dbAuthorization = new DBAuthorization();
#Override
public String getToken() {
String token = dbAuthorization.getToken();
System.out.println("Got token : " + token);
return token;
}
}
How would we use that?
public static void main(String[] args) {
LoggingDBAuthorization loggingDBAuthorization = new LoggingDBAuthorization();
Caller caller = new Caller();
caller.authenticatedUserAction(loggingDBAuthorization);
}
Notice that LoggingDBAuthorization holds an instance of DBAuthorization. Both LoggingDBAuthorization and DBAuthorization implement Authorization.
A proxy will hold some concrete implementation (DBAuthorization) of the base interface (Authorization). In other words a Proxy knows exactly what is being proxied.
Decorator:
It starts pretty much the same as Proxy, with an interface:
public interface JobSeeker {
int interviewScore();
}
and an implementation of it:
class Newbie implements JobSeeker {
#Override
public int interviewScore() {
return 10;
}
}
And now we want to add a more experienced candidate, that adds it's interview score plus the one from another JobSeeker:
#RequiredArgsConstructor
public class TwoYearsInTheIndustry implements JobSeeker {
private final JobSeeker jobSeeker;
#Override
public int interviewScore() {
return jobSeeker.interviewScore() + 20;
}
}
Notice how I said that plus the one from another JobSeeker, not Newbie. A Decorator does not know exactly what it is decorating, it knows just the contract of that decorated instance (it knows about JobSeeker). Take note here that this is unlike a Proxy; that, in contrast, knows exactly what it is decorating.
You might question if there is actually any difference between the two design patterns in this case? What if we tried to write the Decorator as a Proxy?
public class TwoYearsInTheIndustry implements JobSeeker {
private final Newbie newbie = new Newbie();
#Override
public int interviewScore() {
return newbie.interviewScore() + 20;
}
}
This is definitely an option and highlights how close these patterns are; they are still intended for different scenarios as explained in the other answers.
A Decorator adds extra responsibility to an object, while a proxy controls access to an object, they both use composition. If your wrapper class messes with the subject, it is obviously a proxy. Let me explain by a code example in PHP:
Code Example
Given is the following CarRepository:
interface CarRepositoryInterface
{
public function getById(int $id) : Car
}
class CarRepository implements CarRepositoryInterface
{
public function getById(int $id) : Car
{
sleep(3); //... fake some heavy db call
$car = new Car;
$car->setId($id);
$car->setName("Mercedes Benz");
return $car;
}
}
CarRepository-Proxy
A Proxy is often used as lazy loading or a cache proxy:
class CarRepositoryCacheProxy implements CarRepositoryInterface
{
private $carRepository;
private function getSubject() : CarRepositoryInterface
{
if($this->carRepository == null) {
$this->carRepository = new CarRepository();
}
return $this->carRepository;
}
/**
* This method controls the access to the subject
* based on if there is cache available
*/
public function getById(int $id) : Car
{
if($this->hasCache(__METHOD__)) {
return unserialize($this->getCache(__METHOD__));
}
$response = $this->getSubject()->getById($id);
$this->writeCache(__METHOD__, serialize($response));
return $response;
}
private function hasCache(string $key) : bool
{
//... implementation
}
private function getCache(string $key) : string
{
//... implementation
}
private function writeCache(string $key, string $result) : string
{
//... implementation
}
}
CarRepository-Decorator
A Decorator can be used as long as the added behavior does not "control" the subject:
class CarRepositoryEventManagerDecorator implements CarRepositoryInterface
{
private $subject, $eventManager;
/**
* Subjects in decorators are often passed in the constructor,
* where a proxy often takes control over the invocation behavior
* somewhere else
*/
public function __construct(CarRepositoryInterface $subject, EventManager $eventManager)
{
$this->subject = $subject;
$this->eventManager = $eventManager;
}
public function getById(int $id) : Car
{
$this->eventManager->trigger("pre.getById");
//this method takes no control over the subject
$result = $this->subject->getById($id);
$this->eventManager->trigger("post.getById");
return $result;
}
}
Proxy provides the same interface to the wrapped object, Decorator provides it with an enhanced interface, and Proxy usually manages the life cycle of its service object on its own, whereas the composition of Decorators is always controlled by the client.
Let me explain the patterns first and then come to you questions.
From the class diagram and meanings, they are very similar:
Both have the same interface as its delegatee has.
Both add/enhance the behavior of its delegatee.
Both ask the delegatee to perform operations(Should not work with null delegatee).
But they have some difference:
Different intents:
Proxy enhances the behavior of delegatee(passed object) with quite different domain knowledge from its delegatee. Eg, a security proxy adds security control of the delegatee. A proxy to send remote message needs to serialize/deserialize data and has knowlege on network interfacing, but has nothing to do with how to prepare source data.
Decorator helps on the same problem domain the delegatee works on. Eg, BufferedInputStreaman(an IO decorator) works on input, which is the same problem domain(IO) as its delegatee, but it cannot perform without a delegatee which provides IO data.
Dependency is strong or not:
Decorator relies on delegate to finish the behavior, and it cannot finish the behavior without delegatee(Strong). Thus we always use aggration over composition.
Proxy can perform faked behavior even it does not need a delegatee(Weak). Eg, mockito(unit test framework) could mock/spy a behavior just with its interface. Thus we use composition to indicate there's no strong dependency on real object.
Enhance multipletimes(as mentioned in question):
Proxy: we could utilize proxy to wrap real object once not several times.
Decorator: A decorator can wrap the real object several times or can wrap the object which is already wrapped by a decorator(which could be both a different decorator or the same decorator). Eg, for an order system, you can do discount with decorators.
PercentageDiscountDecorator is to cut 50% off, and DeductionAmountDiscountDecorator is to deduct 5$ directly if the amount is greater than 10$(). So,
1). When you want to cut 50% off and deduct 5$, you can do: new DeductionAmountDiscountDecorator(new PercentageDiscountDecorator(delegatee))
2). When you want to deduct 10$, you can do new DeductionAmountDiscountDecorator(new DeductionAmountDiscountDecorator(delegatee)).
The answer to the question has nothing to do with the difference between Proxy and Decorator. Why?
Design patterns just patterns for people who are not good at OO skills to make use of OO solutions. If you are familiar with OO, you don't need to know how many design patterns there(Before design patterns invented, with the same prolbem skilled people could figure out the same solution).
No two leaves are exactly the same, so as the problems you encount. People will always find their problems are different from the problems given by design patterns.
If your specified problem is really different from both problems that Proxy and Decorator work on, and really needs an aggregation, why not to use? I think to apply OO to your problem is much more important than you label it a Proxy or Decorator.

API modularization in Restlet

I have developed a web application based on Restlet API. As I am adding more features over time, I need sometimes to reuse similar group of REST API under different endpoints, which provides slightly different context of execution (like switching different instances of databases with same schema). I like to refactor my code to make the API reusable and reuse them at different endpoints. My initial thinking was to design an Application for each reusable API and attach them on the router:
router.attach("/context1",APIApplication.class)
router.attach("/foo/context2",APIApplication.class)
The API should be agnostic of configuration of the REST API. What is the best way to pass context information (for example the instance of database) to the Application API? Is this approach viable and correct? What are the best practices to reuse REST API in Restlet? Some code samples would be appreciated to illustrate your answer.
Thanks for your help.
I have see this basic set-up running using a Component as the top level object, attaching the sub applications to the VirtualHost rather than a router, as per this skeleton sample.
public class Component extends org.restlet.Component
{
public Component() throws Exception
{
super();
// Client protocols
getClients().add(Protocol.HTTP);
// Database connection
final DataSource dataSource = InitialContext.doLookup("java:ds");
final Configuration configuration = new Configuration(dataSource);
final VirtualHost host = getDefaultHost();
// Portal modules
host.attach("/path1", new FirstApplication());
host.attach("/path2", new SecondApplication(configuration));
host.attach("/path3", new ThirdApplication());
host.attachDefault(new DefaultApplication(configuration));
}
}
We used a custom Configuration object basically a pojo to pass any common config information where required, and used this to construct the Applications, we used separate 'default' Contexts for each Application.
This was coded originally against restlet 1.1.x and has been upgraded to 2.1.x via 2.0.x, and although it works and is reasonably neat there may possibly be an even better way to do it in either versions 2.1.x or 2.2.x.

Adding REST methods to WCF Data Services?

I need to extend my WCF Data Service to include additional methods, not only the database tables..
But it doesn't seem to be working correctly.
Firstly i want to ask if this is legal? or frowned upon?
The reason i need to do it is i need add additional REST methods that will make a call to ASP.NET Membership services (the tables are in the db) to validate a login i.e.
public bool IsValidLogin(string username, string password)
{
return System.Web.Security.Membership.ValidateUser(username, password);
}
Here is what i have (i have simplied the IsValidLogin for testing).
[WebGet(UriTemplate = "TestMe")]
public bool IsValidLogin()
{
return true;
}
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("IsValidLogin", ServiceOperationRights.All);
Now when i go to
http://localhost/MyDataAccess/MyService.svc/IsValidLogin
It seems to work i get an true back in the form of XML. But i have set a URI so i thought i could do this
http://localhost/MyDataAccess/MyService.svc/TestMe
But it fails? I am really confused, any ideas?
Also for it to work I needed to add this line, but a little but confused here
config.SetServiceOperationAccessRule("IsValidLogin", ServiceOperationRights.All);
Any help really appreciated
Not commenting on the REST dicsussion above, just posting a link on documentation on how to do so called "service operations": http://msdn.microsoft.com/en-us/library/cc668788.aspx
The ServiceOperation notion is a tacked on capability to provide exactly the escape you needed when you wanted to do something other than read data from a table.
Unfortunately, the default path in WCF REST has lead you to misunderstand how RESTful systems are supposed to work. REST is not just about exposing some data at URLs.
You really have two choices, either stick with RPC style of distributed computing that WS-*/SOAP based WCF provides or spend some time learning what REST is really all about. There are some links here to get you started.
I can't tell you what is the right approach for your scenario. What I can tell you is that you are not going to learn how to do REST from using the current WCF REST implementation. I'm not saying it is impossible to do, you just will be doing a lot of swimming upstream.

Request/Response pattern in SOA implementation

In some enterprise-like project (.NET, WCF) i saw that all service contracts accept a single Request parameter and always return Response:
[DataContract]
public class CustomerRequest : RequestBase {
[DataMember]
public long Id { get; set; }
}
[DataContract]
public class CustomerResponse : ResponseBase {
[DataMember]
public CustomerInfo Customer { get; set; }
}
where RequestBase/ResponseBase contain common stuff like ErrorCode, Context, etc. Bodies of both service methods and proxies are wrapped in try/catch, so the only way to check for errors is looking at ResponseBase.ErrorCode (which is enumeration).
I want to know how this technique is called and why it's better compared to passing what's needed as method parameters and using standard WCF context passing/faults mechanisms?
The pattern you are talking about is based on Contract First development. It is, however not necessary that you use the Error block pattern in WCF, you can still throw faultexceptions back to the client, instead of using the Error Xml block. The Error block has been used for a very long time and therefore, a lot of people are accustom to its use. Also, other platform developers (java for example) are not as familiar with faultExceptions, even though it is an industry standard.
http://docs.oasis-open.org/wsrf/wsrf-ws_base_faults-1.2-spec-os.pdf
The Request / Response pattern is very valuable in SOA (Service Oriented Architecture), and I would recommend using it rather than creating methods that take in parameters and pass back a value or object. You will see the benefits when you start creating your messages. As stated previously, they evolved from Contract First Development, where one would create the messages first using XSDs and generate your classes based on the XSDs. This process was used in classic web services to ensure all of your datatypes would serialize properly in SOAP. With the advent of WCF, the datacontractserializer is more intelligent and knows how to serialize types that would previously not serialize properly(e.g., ArrayLists, List, and so on).
The benefits of Request-Response Pattern are:
You can inherit all of your request and responses from base objects where you can maintain consistency for common properties (error block for example).
Web Services should by nature require as little documentation as possible. This pattern allows just that. Take for instance a method like public BusScheduleResponse GetBusScheduleByDateRange(BusDateRangeRequest request); The client will know by default what to pass in and what they are getting back, as well, when they build the request, they can see what is required and what is optional. Say this request has properties like Carriers [Flag Enum] (Required), StartDate(Required), EndDate(Required), PriceRange (optional), MinSeatsAvailable(Option), etc... you get the point.
When the user received the response, it can contain a lot more data than just the usual return object. Error block, Tracking information, whatever, use your imagination.
In the BusScheduleResponse Example, This could return Multiple Arrays of bus schedule information for multiple Carriers.
Hope this helps.
One word of caution. Don't get confused and think I am talking about generating your own [MessageContract]s. Your Requests and Responses are DataContracts. I just want to make sure I am not confusing you. No one should create their own MessageContracts in WCF, unless they have a really good reason to do so.