How is async interface connected to GWT.create? - gwt

When I create a sample project with GWT 2.6, I end up with the following code for RPC proxy initialisation:
private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
GreetingService is defined as:
#RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String greetServer(String name) throws IllegalArgumentException;
}
and GreetingServiceAsync is defined as:
public interface GreetingServiceAsync {
void greetServer(String input, AsyncCallback<String> callback)
throws IllegalArgumentException;
}
The signature of GWT.Create is:
public static <T> T create(Class<?> classLiteral)
Given all of this, I would expect the assignment of GWT.create to greetingService to fail. Because greetingService is of type GreetingServiceAsync and GWT.create would return GreetingService which has no relation to Async version. I would expect the Java compiler to mark this assignment as invalid, but it is not doing it.
Where is the link between the Async interface and its non async version? Java compiler obviously knows this, but I could not see it in the project source code.

about the fact that it compiles without error: notice how the parameters's type to GWT.create() does not make use of the T type parameter; so what the signature says is: you can pass any class, and it can return any type of object (T is shorthand for T extends Object), there's no connection between the GreetingService.class passed as argument and the GreetingServiceAsync returned, at least not in the GWT.create() method signature.
the connection is in the GWT compiler (actually, in the generator for RPC, which is triggered for every class passed to GWT.create() that extends RemoteService), and it's simply based on a naming rule: return the type whose name is the one of the argument class suffixed with Async. Of course checks are made: both have to be interfaces, and the methods in the async interface have to be the same as the one in the "non async" interface, except the return type of the non-async is moved to a type argument of an additional AsyncCallback parameter. BTW, this specific case is the only reason that GWT.create() still has this signature where the return type is not related to the parameter type.

Related

Same QueryParams In All JAX-RS Endpoints

I have a requirement that a few QueryParams should be present in absolutely all JAX-RS endpoints of my application.
Is there a way to specify somewhere, only once, these parameters? Or do I have to repeat myself in all method endpoints?
Thank you!
I would implement a ContainerRequestFilter and handle the parameters there. You can add the result to the ContainerRequestContext:
#Provider
public class MyFilter implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Object result = // handle the parameter
requestContext.setProperty("myParam", result);
}
}
Your implementation will of course depend on your needs.
You can inject the context into your resource classes like:
#Context
private ContainerRequestContext containerRequestContext;
See also:
Jersey 2 filter uses Container Request Context in Client Request Filter

Public, private and protected access qualifiers for D classes

I'm a C++ programmer starting with D and I'm having some trouble understanding the access qualifiers for D classes. Consider the following example:
import std.stdio;
class Foo {
private void aPrivateMethod()
{
writeln("called aPrivateMethod");
}
protected void aProtectedMethod()
{
writeln("called aProtectedMethod");
}
public void aPublicMethod()
{
this.aPrivateMethod();
this.aProtectedMethod();
}
}
void main(string[] args)
{
Foo foo = new Foo();
foo.aPublicMethod(); // OK to call it from anywhere
foo.aPrivateMethod(); // Must not be allowed to call it outside Foo
foo.aProtectedMethod(); // Should only be callable from within Foo and derived classes
}
I would expect the previous code to fail compilation, since it is calling private and protected methods of class Foo in an external function. However, this is not the case, since the example above compiles and runs without errors or warnings on DMD v2.063.2. Clearly the keywords have different meaning from those of C++.
My questions are:
1) How to make a method and/or variable private to a class so that only the class in question can access it.
2) How to make a method and/or variable protected, so that only the class in question and its derived classes can access it.
the access modifiers are module/file level (only exception is protected)
to remove access to a class put it in its own mudule:
foo.d
import std.stdio;
class Foo {
private void aPrivateMethod()
{
writeln("called aPrivateMethod");
}
protected void aProtectedMethod()
{
writeln("called aProtectedMethod");
}
public void aPublicMethod()
{
this.aPrivateMethod();
this.aProtectedMethod();
}
}
main.d
import foo;
void main(string[] args)
{
Foo foo = new Foo();
foo.aPublicMethod(); // OK to call it from anywhere
foo.aPrivateMethod(); // compile error: Must not be allowed to call it outside foo.d
foo.aProtectedMethod(); // compile error: Should only be callable from within foo.d, Foo and derived classes
}
D has a slightly different meaning to terms public private and protected than C++
Private means that only members of the enclosing class can access the member, or members and functions in the same module as the enclosing class. Private members cannot be overridden. Private module members are equivalent to static declarations in C programs.
Package extends private so that package members can be accessed from code in other modules that are in the same package. This applies to the innermost package only, if a module is in nested packages.
Protected means that only members of the enclosing class or any classes derived from that class, or members and functions in the same module as the enclosing class, can access the member. If accessing a protected instance member through a derived class member function, that member can only be accessed for the object instance which can be implicitly cast to the same type as ‘this’. Protected module members are illegal.
Public means that any code within the executable can access the member.

GWT - The response could not be deserialized

i am in this situation:
#RemoteServiceRelativePath("create_event")
public interface CreateEventService extends RemoteService {
String[] createeventServer(LinkedList<LinkedList<String>> input) throws IllegalArgumentException;
}
public interface CreateEventServiceAsync {
void createeventServer(LinkedList<LinkedList<String>> input, AsyncCallback<String[]> callback)
throws IllegalArgumentException;
}
public class CreateEventServiceImpl extends RemoteServiceServlet implements CreateEventService {
public String[] createeventServer(LinkedList<LinkedList<String>> input) throws IllegalArgumentException {
String[] arr = new String[2];
...
return arr;
}
Why does this cause error "The response could not be deserialized"?
p.s. I have tried to execute the project with app engine and without it, but the problem is the same.
To problems with serializable objects, you can try this check list:
Verify that the class has a default constructor (without arguments)
Verify that the class implements Serializable or IsSerializable or
implements an Interface that extends Serializable or extends a class
that implement Serializable
Verify that the class is in a client.* package or …
Verify, if the class is not in client.* package, that is compiled in
your GWT xml module definition. By default is present. If your class
is in another package you have to add it to source. For example if
your class is under domain.* you should add it to xml as . Be aware
that the class cannot belong to server package! More details on GWT
page:
http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideModuleXml
If you are including the class from another GWT project you have to
add the inherits to your xml module definition. For example if your
class Foo is in the package com.dummy.domain you have to add to the
module definition. More details here:
http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideInheritingModules
If you are including the class from another GWT project released as
a jar verify that the jar contains also the source code because GWT
recompile also the Java source for the classes passed to the Client.
Font: http://isolasoftware.it/2011/03/22/gwt-serialization-policy-error/

GWT RequestFactory: inheriting interfaces into a RequestContext

I have my OrganizationRequestContext interface, which works great:
#Service(OrganizationDAO.class)
public interface OrganizationRequestContext extends RequestContext
{
Request<OrganizationProxy> findOrganization(Long id);
InstanceRequest<OrganizationProxy, Void> persist();
InstanceRequest<OrganizationProxy, Void> remove();
}
Now I want to take those last two functions and put them in a PersistentRequestContext of my own design so that I can treat all of my RequestContexts the same in my client code:
public interface PersistableRequestContext<T extends BaseProxy>
{
InstanceRequest<T, Void> persist();
InstanceRequest<T, Void> remove();
}
...
#Service(OrganizationDAO.class)
public interface OrganizationRequestContext extends RequestContext, PersistentRequestContext<OrganizationProxy>
{
Request<OrganizationProxy> findOrganization(Long id);
}
But this fails validation: the server complains that
[ERROR] com.activegrade.shared.data.PersistableRequestContext is not a RequestContext
If I make PersistableRequestContext extend RequestContext, then the server complains that it is not linked to any particular DAO service.
Is there any way to extend a common interface besides RequestContext in my various RequestContext interfaces?
This issue has been fixed in GWT 2.4. Thanks Google!
http://code.google.com/p/google-web-toolkit/issues/detail?id=6035

Using structuremap with log4net wrapper

I have the following interface:
public interface ILogger
{
void Debug(string message, params object[] values);
void Info(string message, params object[] values);
void Warn(string message, params object[] values);
void Error(string message, params object[] values);
void Fatal(string message, params object[] values);
}
and the following implementation:
public class Log4netLogger : ILogger
{
private ILog _log;
public Log4netLogger(Type type)
{
_log = LogManager.GetLogger(type);
}
public void Debug(string message, params object[] values)
{
_log.DebugFormat(message, values);
}
// other logging methods here...
}
My idea was to use structuremap to instantiate the Log4netLogger class with using the Type of the class that did the logging. However, I can't for the life of me figure out how to pass the type of the calling class to structuremap so that it can be passed to the constructor of the logging implementation. Any advice on how to do that (or a better way) would be most appreciated.
We use a similar ILogger wrapper around log4net and typically use constructor injection. We use an interceptor as a factory method responsible for creating the Logger. Here is our typical registry for logging setup.
public class CommonsRegistry : Registry
{
public CommonsRegistry()
{
For<ILogger>()
.AlwaysUnique()
.TheDefault.Is.ConstructedBy(s =>
{
if (s.ParentType == null)
return new Log4NetLogger(s.BuildStack.Current.ConcreteType);
return new Log4NetLogger(s.ParentType);
});
var applicationPath = Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location);
var configFile = new FileInfo(Path.Combine(applicationPath, "log4net.config"));
XmlConfigurator.ConfigureAndWatch(configFile);
}
}
The parent type null check is necessary when there are dependencies on concrete types.
The rest is optional log4net setup stuff.
One thing I do like about this setup is the ability to use a null loggers for unit testing.
If the type parameter is context-specific, I don't think this is going to work as shown. If you need to pass something context specific in the constructor, you are likely going to have to create a factory interface and implementation that returns an instance of the ILogger:
public interface ILoggerFactory
{
ILogger Create(Type type);
}
public class LoggerFactory : ILoggerFactory
{
public ILogger Create(Type type)
{
return new Log4netLogger(type);
}
}
It might be possible to bootstrap StructureMap to supply the instance you want based on the type, but that assumes a limited number of types that you know in advance.
I really need to get out of the habit of answering my own question, but for those who run across it, here's the answer.
return ObjectFactory.With(type).GetInstance<T>();
I actually have a wrapper to structuremap (to avoid exposing the structuremap dependency to my app) that looks like the following:
public static class ServiceManager
{
public static T Get<T>()
{
return ObjectFactory.GetInstance<T>();
}
public static T Get<T>(Type type)
{
return ObjectFactory.With(type).GetInstance<T>();
}
}
Any time in the code I need a logger, I call the following:
ServiceManager.Get<ILogger>(GetType()).Info("Logging page view...");