Why are static GWT fields not transferred to the client? - gwt

ConfigProperty.idPropertyMap is filled on the server side. (verified via log output)
Accessing it on the client side shows it's empty. :-( (verified via log output)
Is this some default behaviour? (I don't think so)
Is the problem maybe related to the inner class ConfigProperty.IdPropertyMap, java.util.HashMap usage, serialization or some field access modifier issue?
Thanks for your help
// the transfer object
public class ConfigProperty implements IsSerializable, Comparable {
...
static public class IdPropertyMap extends HashMap
implements IsSerializable
{
...
}
protected static IdPropertyMap idPropertyMap = new IdPropertyMap();
...
}
// the server service
public class ManagerServiceImpl extends RemoteServiceServlet implements
ManagerService
{
...
public IdPropertyMap getConfigProps(String timeToken)
throws ConfiguratorException
{
...
}
}
added from below after some good answers (thanks!):
answer bottom line: static field sync is not implemented/supported currently. someone/me would have to file a feature request
just my perspective (an fallen-in-love newby to GWT :-)):
I understand pretty good (not perfect! ;-)) the possible implications of "global" variable syncing (a dependency graph or usage of annotations could be useful).
But from a new (otherwise experienced Java EE/web) user it looks like this:
you create some myapp.shared.dto.MyClass class (dto = data transfer objects)
you add some static fields in it that just represent collections of those objects (and maybe some other DTOs)
you can also do this on the client side and all the other static methods work as well
only thing not working is synchronization (which is not sooo bad in the first place)
BUT: some provided annotation, let's say #Transfer static Collection<MyClass> myObjList; would be handy, since I seem to know the impact and benefits that this would bring.
In my case it's rather simple since the client is more static, but would like to have this data without explicitely implementing it if the GWT framework could do it.

static variables are purely class variable It has nothing to do with individual instances. serialization applies only to object.
So ,your are getting always empty a ConfigProperty.idPropertyMap

The idea of RPC is not that you can act as though the client and the server are exactly the same JVM, but that they can share the objects that you pass over the wire. To send a static field over the wire, from the server to the client, the object stored in that field must be returned from the RPC method.
Static properties are not serialized and sent over the wire, because they do not belong to a single object, but to the class itself.
public class MyData implements Serializable {
protected String name;//sent over the wire, each MyData has its own name
protected String key;
protected static String masterKey;//All objects on the server or client
// share this, it cannot be sent over RPC. Instead, another RPC method
// could access it
}
Note, however, that it will only be that one instance which will be shared - if something else on the server changes that field, all clients which have asked for a copy will need to be updated

Related

Dealing with state in factory implementations

What pattern would one use if you have multiple factory implementations, each of which requires different state information to create new objects?
Example:
IModelParameters: contains all the inputs and outputs to a complex calculation
IModelParameterFactory: has methods for getting and saving IModelParameter objects.
The issue is that one factory implementation might be getting your parameters from a database, with some state needed for retrieval, (i.e. a UserID), another might be getting your inputs from a file, in which case you don't have a UserID, but you do need a file name.
Is there another pattern that works better in this case? I've looked at some dependancy injection tools/libraries, and haven't seen anything that seems to address the situation.
Have you tried to put the requeriments in a class?
Every factory implementation has their own requeriments, but all requeriments classes derives form a base requeriment class (Or impements a requeriments interface). This allows you to have the same interface for all factory implementations, you just must do a cast to the correct requeriments class in every factory implementation.
Yes, casts are ugly and error-prone, but this method provides an uniform an extensible interface for your factory.
It's hard to say without seeing some code, but you may want to look into implementing a Repository Pattern. The Repository implementation would be responsible for retrieving the data that the factory then used to build its object(s). You could inject the repository interface into your factory:
public class ModelParameterFactory : IModelParameterFactory
{
private readonly IModelParameterRepository Repository;
public ModelParameterFactory(IModelParameterRepository repository)
{
Repository = repository;
}
...interface methods use the injected repository...
}
Then you would have, say a DatabaseModelParameterRepository and a FileModelParameterRepository. But I'm guessing you also have logic around which of those you would need to inject, so that calls for another factory:
public class ModelParameterRepositoryFactory : IModelParameterRepositoryFactory
{
public ModelParameterRepositoryFactory(...inputs needed to determine which repository to use...)
{
...assign...
}
...determine which repository is required and return it...
}
At this point, it might make more sense to inject IModelParameterRepositoryFactory into the ModelParameterFactory, rather than inject the IModelParameterRepository.
public class ModelParameterFactory : IModelParameterFactory
{
private readonly IModelParameterRepositoryFactory RepositoryFactory;
public ModelParameterFactory(IModelParameterRepositoryFactory repositoryFactory)
{
RepositoryFactory = repositoryFactory;
}
...interface methods get repository from the factory...
}
Whether you use a DI container or not, all logic regarding which repository to use and which factory to use are now moved into the relevant factory implementations, as opposed to the calling code or DI configuration.
While not terribly complex, this design nonetheless does give me pause to wonder whether your ModelParameterFactory and ModelParameters are too generic. You might benefit from teasing them into separate, more specific classes. The result would be a simpler and more expressive design. The above should work for you if that is not the case, however.
In my point of view, a state is something that you store in memory, such as static object, global variable, cache or session. Usually in DI, such states are not maintained, but being passed as a parameter. Example:
public IEnumerable<Records> GetRecordByUserId(string userId){ /*code*/ }
The userId is being passed instead being maintained in the repository.
However, when you want to make them as configuration-like instead of passing each time you do query, I think you can inject it as a wrapper class. See my question for more info. However, I don't recommend this design at repository, but I do recommend at service level.

EXT GWT BaseModel needs to have DTO reference?

I am very new to GWT.
I am using ext-gwt widgets.
I found many places in my office code containing like,
class A extends BaseModel{
private UserAccountDetailsDto userAccountDetailsDto = null;
//SETTER & GETTER IN BASEMODEL WAY
}
Also, the DTO reference is unused.
public class UserAccountDetailsDto implements Serializable{
private Long userId=null;
private String userName=null;
private String userAccount=null;
private String userPermissions=null;
//NORMAL SETTER & GETTER
}
Now, I am able to get the result from GWT Server side Code and things Work fine, but when I comment the DTO reference inside the class A, I am not getting any Result.
Please explain me the need of that.
Thanks
Well the problem is in implementation of GXT BaseModel and GWT-RPC serialization.
BaseModel is based around special GXT map, RpcMap. This map has defined special serialization rules, which let's avoid RPC type explosion, but as side effect, only some simple types stored in map will be serialized. E.g. you can put any type inside the map, but if you serialize/deserialize it, only values of type Integer, String ,Double,Byte, Float and Short (and arrays of this types) will be present. So the meaning behind putting reference to the DTO inside BaseModel, is to tell GWT-RPC that this type is also have to be serialized.
Detailed explanation
Basically GWT-RPC works like this:
When you define an interface for service, GWT-RPC analyzes all the classes used in parameters/ return type, to create serializers/deserializers. If you return something like Map<Object,Object> from your service, GWT-RPC will have to create a serializer for each class which implements Map and Serializable interfaces, but also it will generate serializers for each class which implements Serializable. In the end it is quite a bad situation, because the size of your compiled js file will be much biggger. This situation is called GWT-RPC type explosion.
So, in the BaseModel, all values are stored in RpcMap. And RpcMap has custom written serializer (RpcMap_CustomFieldSerializer you can see it's code if you interested how to create such things), so it doesn't cause the problem described above. But since it has custom serializer GWT dosn't know which custom class have been put inside RpcMap, and it doesn't generate serializers for them. So when you put some field into your BaseModel class, gwt knows that it might need to be able to serialize this class, so it will generate all the required stuff for this class.
Porting GXT2 Application code using BaseModel to GXT3 Model is uphill task. It would be more or less completely rewrite on model side with ModelProviders from GXT3 providing some flexibility. Any code that relies on Model's events, store, record etc are in for a rewrite.

Variables in GWT server side code

I'm fairly new to GWT and have never worked with Java Servlets before. I know how to make RPCs but I was wondering if there are any concurrency issues with declaring member variables in my RPC's ServiceImpl/RemoteServiceServlet class. I.e. From multiple "simultaneous" RPCs overwriting the same variable, similar to what happens with threads when a variable isn't declared volatile.
I also need to use an extra thread in my server side code, so I was wondering if there's any problems (outside of the usual thread safety problems) with declaring some of the servlet's members as static so the other thread can access the variables without a reference to the servlet instance. Is it possible for more than one instance of the same RemoteServiceServlet class to be running at the same time?
E.g.
public class MyServiceImpl extends RemoteServiceServlet implements MyService {
// Which of these variable declarations are a bad idea in a servlet?
private String someVariable;
private static String anotherVariable;
volatile private static String multiThreadedVariable;
public void init() { ... }
...
}
Thanks.
A Servlet is a singleton, therefore there is only one instance of the MyServiceImpl class. By introducing these state variables you will run into thread-safety issues not because there might be more than one MyServiceImpl instance, but because there is only one instance that will service ALL of your requests. Unless you synchronize access to these variables, you will have thread-safety issues, so I recommend removing them completely (most likely you don't even need them).

EntityProxies with immutable ValueProxy properties -> "could not locate setter"

I'm trying to wrap my mind around RequestFactory, but I'm having some problems. I have an entityproxy that has a property which is a valueproxy of an immutable type (joda-time LocalDate), and I'm having problems using this entityproxy in any calls to the server.
I've made the property read-only by only including a getter for the property in the entityproxy, and only including getters for the primitive properties in the valueproxy.
However, as far as I can tell, If I use an entityproxy as an argument in a call to a service method, any referenced valueproxy is automatically marked as edited and all its properties are included in the delta?
This in turn causes ReflectiveServiceLayer to throw an exception about a missing setter on LocalDate.
I've been toying with the idea of implementing a ServiceLayerDecorator which overrides "setProperty" to get around this, but I'm not sure if that's a good solution. Is there any "proper" way to fix this? Ideally, I'd like AbstractRequestContext not to include immutable properties in calls to the server.
I'm using GWT 2.3
edit: I created a workaround like this, but I'm still unsure of whether this is the correct approach:
public class ImmutablePropertyFixServiceLayer extends ServiceLayerDecorator {
#Override
public void setProperty(Object domainObject, String property, Class<?> expectedType, Object value) {
Method setter = getTop().getSetter(domainObject.getClass(), property);
if (setter != null) {
super.setProperty(domainObject, property, expectedType, value);
} else {
//System.out.println(domainObject.getClass().getName() + "." + property + " doesn't have a setter");
}
}
}
EntityProxy objects have some way they can be easily retreived on the server, so when sending an object back to the server, just the ID is required. ValueProxy objects on the other hand can only be sent as the combination of all of their sub-values. When sending an immutable value back to the server, the server code doesn't know how to turn a proxy back into a server-side value.
I'd be concerned with your solution that you might not be correctly getting the same date on the server as was sent from the client.

GWT RequestFactory and multiple types

My GWT app has ten different kinds of entities. Right now I use plain old DTOs and transport them over GWT-RPC. This works well for cases like startup - I can pack them all into a single request.
I'm looking at switching to RequestFactory because there are many times throughout the lifetime of the app (30 minutes, on average) when I just have to update one type of entity, and the unifying/bandwidth-saving features of RequestFactory are appealing. BUT: I don't see a way to download all of my initialization data in a single request when the app loads. I don't want to have to make ten requests to fetch all of the init data for my ten entity types.
Is there a way to make a GeneralRequestContext, or something? I'd even be happy with a solution like:
public interface InitDataProxy extends EntityProxy
{
public UserProxy getInitUsers();
public OrganizationProxy getInitOrganizations();
...
}
public interface GeneralRequestContext extends RequestContext
{
Request<InitDataProxy> getInitData();
}
But this won't work because I don't want to have to actually back InitDataProxy with anything, I just want to use it to combine a bunch of different types of Proxies in a single request.
So: Is there a way to receive multiple, unrelated types of EntityProxy in a single request?
I would also be happy enough making a normal gwt-rpc request to go outside of RequestFactory for this data, but I don't want to have to implement duplicate DTOs to run next to RequestFactory's proxies, and write custom code to copy the DTOs into them!
The InitDataProxy could extend ValueProxy instead, which doesn't require that the object on the server have any kind of id or version semantics. The domain-side InitData type could be an interface, possibly implemented with an anonymous type.
interface InitData {
User getUser();
Organization getOrgatization();
}
class InitService {
static InitData makeInitData() {
return new InitData() { ..... };
}
}
#ProxyFor(InitData.class)
interface InitDataProxy extends ValueProxy {
UserProxy getUser();
OrganizationProxy getOrganization();
}
#Service(InitService.class)
interface Init extends RequestContext {
Request<InitDataProxy> makeInitData();
}