Deserialization of ArrayList GWT - gwt

In my application I'm getting some data from a file located in the server. The data is stored in a text file (.obj), so I'm using an rpc to read the file and get the data. The file is read using a third party library http://www.pixelnerve.com/processing/libraries/objimport/ I'm sending the data to the client using ArrayLists, basicly I'm sending this: ArrayList[ArrayList[Vertex3dDTO]] where Vertex3dDTO is an serializable object with contains float parameters. ArrayList[Vertex3dDTO] is contained in another serializable class Face3dDTO, and ArrayList[Face3dDTO] is in the serializable class Group3dDTO.
package com.nyquicksale.tailorapp.shared;
import java.io.Serializable;
public class Vertex3dDTO implements Serializable {
float x,y,z;
public Vertex3dDTO(){
}
public Vertex3dDTO(float x, float y, float z){
this.x = x;
this.y = y;
this.z = z;
}
}
public class Face3dDTO implements Serializable {
ArrayList<Vertex3dDTO> vL = new ArrayList<Vertex3dDTO>();
Vertex3dDTO normal = new Vertex3dDTO();
Vertex3dDTO color = new Vertex3dDTO();
public Face3dDTO(){
}
public Face3dDTO(ArrayList<Vertex3dDTO> v) {
for(Vertex3dDTO v3dDTO : v){
vL.add(v3dDTO);
}
updateNormal();
}
public class Group3dDTO implements Serializable {
ArrayList<Face3dDTO> fL = new ArrayList<Face3dDTO>();
String name;
public Group3dDTO(){
}
public Group3dDTO(ArrayList<Face3dDTO> f) {
for(Face3dDTO f3dDTO : f){
fL.add(f3dDTO);
}
}
}
Now, everything is working well in development mode, but when I tested the application in hosted mode, everything I receive as response is: //OK[0,1, ["java.util.ArrayList/4159755760"],0,7]
So, I've been checked some other questions and seems the problem is about deserialization, but I've not found anything concrete.
The question is what do I have to do to get the app working well in hosted mode?

To successfully use RPC, your object needs to implement Serializable and should also have a default no arg constructor

Have you made sure this is a serialization problem? You can write a simple RPC test method to pass an array list of your DTO's over the wire in hosted mode.
If I were to bet money on a guess, I would say the problem is those array lists are sent empty in hosted mode. The .obj file read could be the problem. Perhaps in hosted mode the path of file doesn't match as in dev mode(different server configurations perhaps?), since file operations are in a try catch block an exception is most likely swallowed.
Long word short, Did you make sure those array lists are not sent empty in hosted mode?

Your object may well be Serializable, but that doesn't equate to something usable by Remote Procedure Calls. You need to implement Serializable, have a default contructor with no arguments (that calls super() if necessary), and a serial version ID, like so:
public class MyObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1796729355279100558L;
private Float someValue;
public MyObject() {
super();
}
public MyObject(Float someValue) {
super();
this.someValue = someValue;
}
public Float getSomeValue() {
return someValue;
}
public void setSomeValue(Float someValue) {
this.someValue = someValue;
}
}

Related

Scala constructors using val not playing nicely with serialization framework

I'm having an issue with some Scala code and am trying to rule out a bad class design (well, constructor design) before I begin to treat it as a networking issue.
So I have a model Scala class called Hail:
class Hail(val handle : String, val message : String) extends BaseMessage {
def this() {
this("default_user", "default_message")
}
}
abstract class BaseMessage extends AbstractMessage(true) {
}
// This is a 3rd party open source class written in Java
public abstract class AbstractMessage implements Message
{
private transient boolean reliable = true;
protected AbstractMessage()
{
}
protected AbstractMessage( boolean reliable )
{
this.reliable = reliable;
}
public Message setReliable(boolean f)
{
this.reliable = f;
return this;
}
public boolean isReliable()
{
return reliable;
}
}
// This is also a 3rd party open source class written in Java
public interface Message
{
public Message setReliable(boolean f);
public boolean isReliable();
}
At runtime, instances of this class get serialized (to binary), sent over the wire to a server, where they are deserialized (back into Hail instances) and processed.
So I have client code that looks like this:
val h1 : Hail = new Hail("user1", "Hello!")
val h2 : Hail = new Hail("user2", "Aloha!")
val h3 : Hail = new Hail("user3", "Bien venu mes amigos")
client.send(h1)
client.send(h2)
client.send(h3)
When the server receives these messages, it prints out their handle/message combos to STDOUT. The messages I receive are as follows:
Server received a Hail: default_user, default_message
Server received a Hail: default_user, default_message
Server received a Hail: default_user, default_message
Instead of what I would be expecting:
Server received a Hail: user1, Hello!
Server received a Hail: user1, Aloha!
Server received a Hail: user3, Bien venu mes amigos
Again, this could be a networking/serialization/server-side issue. But before I go down that route I want to make sure my Hail class has been written correctly.
The serialization framework I'm using requires all messages (such as Hail) to have no-arg constructors (hence the one I provided above). So it seems to me that something is wrong with my other constructor, and perhaps the server defaults to calling the no-arg constructor because it can't use anything else.
I decompiled my Hail class and see the following:
#ScalaSignature(bytes="<lots of bytes here omitted for brevity")
public class Hail
extends BaseMessage
{
private final String handle;
public String handle()
{
return this.handle;
}
public String message()
{
return this.message;
}
public Hail()
{
this("default_user", "default_message");
}
public Hail(String handle, String message) {}
}
Right away several things are curious/suspicious to me:
Although I see a private final String handle (which is desired!), I don't see a reciprocal private final String message field...
Also, the 2nd constructor (public Hail(String handle, String message)) is empty/undefined. This is probably the root of my issues.
So I ask, how can I refactor Hail's source so that the following end result is bytecode that would decompile to:
#ScalaSignature(bytes="<lots of bytes here omitted for brevity")
public class Hail
extends BaseMessage
{
private final String handle;
public String handle()
{
return this.handle;
}
public String message()
{
return this.message;
}
public Hail()
{
this("default_user", "default_message");
}
public Hail(String handle, String message)
{
this.handle = handle;
this.message = message;
}
}
Any ideas?
The problem is that the serializer server-side uses the no-arg constructor, and then change the values of mutable parameters in the class.
However, scala vals are not mutable, so they are compiled as final parameters of your class, and as such cannot be mutated. So the objects are instantiated with the default values, and then keep those values, since they cannot be mutated.
I would recommend using a scala-compatible serializer, but a simpler solution is to allow the properties to be mutated by declaring them as vars instead of vals.

How do I combine a Controlled Lifetime relationship type (i.e. Owned<T>) with a delegate factory?

In my application, I have a service that requires a constructor parameter not resolved by Autofac, that I instantiate using a delegate factory:
public class Service
{
public Service(string parameter /*, ... other dependencies */)
{
}
public delegate Service Factory(string parameter);
}
This works great! I really love this feature.
I also like the Controlled Lifetime relationship, so I can let my component depend on a Func<Owned<ISomething>> like this:
public class Component
{
private Func<Owned<ISomething>> _somethingFactory;
/* constructor omitted for brevity */
public void DoSomethingUseful()
{
using (var ownedSomething = _somethingFactory())
{
/* Lots of useful code here */
}
}
}
My problem is that now I want to combine the two. I can't have an instance of Func<Owned<Service>> injected, because it needs that parameter, so my current solution is to abstract the factory away into another service, say IServiceFactory:
public interface IServiceFactory
{
Service Create(string parameter);
}
...implemented as such:
public class ServiceFactory : IServiceFactory
{
private Service.Factory _internalFactory;
public ServiceFactory(Service.Factory internalFactory)
{
_internalFactory = internalFactory;
}
public Service Create(string parameter)
{
return _internalFactory(parameter);
}
}
My component then becomes this:
public class Component
{
Func<Owned<IServiceFactory>> _serviceFactoryFactory;
/* ... */
}
The need for such a field name leaves a bad taste in my mouth to the point that I suspect there must be a cleaner way to handle this case.
Is there another way?
You could change your injected factory to include the string parameter:
private Func<string, Owned<ISomething>> _somethingFactory;
Then you can pass the string to the factory when you want to create a new instance:
public void DoSomethingUseful()
{
using (var ownedSomething = _somethingFactory("my parameter"))
{
/* Lots of useful code here */
}
}
I've created a .NET Fiddle with a small working sample.

Could you explain me one OOP confusion?

I am creating a program for testing a website. Site has a registration process, which I am testing.
I have created a class named "Client", which should store the information about the client (name, family name, e-mail etc.).
Since I am testing, I use random number generator to generate a name for the client (I have the list of names, one of which is chosen randomly).
Obviously, I should create a method "generateName ()".
But the question is: in which class I should create it?
Lots of programmers would create the method in the Client class. And would do something like that:
client = new Client ();
client.generateName ();
But I have read, that this approach is incorrect - because the client does not generate name for himself. Program does.
Based on that information, I do as follows:
class Program
{
private void generateName ();
}
...
class Client
{
...
public void name ( String name )
{
this.name = name;
}
}
program = new Program ();
program.launch();
client = new Client ();
client.name ( program.generateName () );
But as I know, this approach is not used by the developers.
Could you clarify, how to know "what is right and what is wrong" here? And what information source should I use as an arbitrary for the cases of this kind?
It sounds like generateName() could be a static method in Client, since it's independent of instances:
class Client {
private String name;
public Client(String name) {
this.name = name;
}
public static String generateRandomName() {
String generatedName = ...;
return generatedName;
}
}
You could the simply pass it's value to the Client object as you currently are, or via the constructor:
client = new Client(Client.generateRandomName());
Otherwise, I'd suggest a ClientNameGenerator to handle name generation, to keep inline with SRP and to raise cohesion. This would be the better choice, seeing how you may be needing more name generation methods in the future:
class ClientNameGenerator {
public String generateRandomName() {
String generatedName = ...;
return generatedName;
}
//other name generation methods...
}
You can now use a ClientNameGenerator object to manage the generation of client names:
ClientNameGenerator nameGenerator = new ClientNameGenerator();
client = new Client(nameGenerator.generateRandomName());
Anytime you need to generate a name, simply use the ClientNameGenerator object you created.
There are a number of places which might be appropriate locations for this functionality.
You could have it as a private method on the Client class, used by a static factory method for generating Clients with a random name.
public class Client {
....
public static Client randomlyNamed() {
return new Client(randomName());
}
private static String randomName() {
return ...;
}
}
But that private method might be better extracted to a more appropriate class for generating random Strings...
public class Client {
private static final int defaultNameLength = 8;
....
public static Client randomlyNamed() {
return new Client(Strings.randomString(defaultNameLength));
}
}
public class Strings
private static String randomString(int length) {
return ...;
}
}
You could then expand the static method into a general purpose ClientBuilder class, with an instance method named something like 'withRandomName()'.
public class Client {
...
}
public class ClientBuilder {
private static final int defaultNameLength = 8;
...
public ClientBuilder randomlyNamed() {
this.name = Strings.randomString(defaultNameLength);
}
public Client build() {
return new Client(name);
}
}
public class Strings
private static String randomString(int length) {
return ...;
}
}
An alternative would be an implementation of a NamingStrategy (e.g. ``) object which is given to a ClientBuilder object.
public class RandomNames implements NamingStrategy {
private static final int defaultNameLength = 8;
public String name() {
return String.randomString(defaultNameLength);
}
}
public class ClientBuilder {
private final NamingStrategy nameSource;
public ClientBuilder(NamingStrategy nameSource) {
this.nameSource = nameSource;
}
public Client build() {
return new Client(nameSource.name());
}
}
The pure way to go would be to have a separate class ClientGenerator that produces clients. Because generating clients is not typical client behavior and in your application model a client is no more than a passive data container for client properties. However, generating clients is an activity in "the client domain". Therefor it would be defendable to create a static method Client.NewClient(), like the .NET feamework does with Guid. On the other hand, a guid's very nature is to be generated, it does not represent something in the real world. It IS a spawnable id. So the comparison may not be all that ligitimate.
A common similar mistake (or impurity if you wish) is a Save method on an object. Instead one should have a Persister class that does the job. Or a Manager. Because Save is something you can do to or with the class, not behavior of the class ifself.

Overriding Getters and Setters in tinkerpop Frames annotated model

I'm working on a new piece of software and I'd like the values in the database to be encrypted. We are using OrientDB and are trying to implement the project using the tinkerpop libraries. Here I'm stuck a little bit.
For one function, I need to pull a list of all vertices of a type and return them. I have my annotated interface for the person object, and I added methods to encrypt and decrypt necessary fields right now. But when I decrypt them, it persists the decrypted values back to the database.
Is there a way to either override the getters and setters to handle the encryption/decryption at that point or do I need to detach the models from the db before performing my decryption?
Here's my code for my interface:
public interface iPerson {
#Property("firstName")
public void setFirstName(String firstName);
#Property("firstName")
public String getFirstName();
#Property("lastName")
public String getLastName();
#Property("lastName")
public void setLastName(String lastName);
#Property("id")
public String getId();
#Property("id")
public void setId(String id);
#Property("dateOfBirth")
public String getDateOfBirth();
#Property("dateOfBirth")
public void setDateOfBirth(String dateOfBirth);
#JavaHandler
public void encryptFields() throws Exception;
#JavaHandler
public void decryptFields() throws Exception;
public abstract class Impl implements JavaHandlerContext<Vertex>, iPerson {
#Initializer
public void init() {
//This will be called when a new framed element is added to the graph.
setFirstName("");
setLastName("");
setDateOfBirth("01-01-1900");
setPK_Person("-1");
}
/**
* shortcut method to make the class encrypt all of the fields that should be encrypted for data storage
* #throws Exception
*/
public void encryptFields() throws Exception {
setLastName(Crypto.encryptHex(getLastName()));
setFirstName(Crypto.encryptHex(getFirstName()));
if(getDateOfBirth() != null) {
setDateOfBirth(Crypto.encryptHex(getDateOfBirth()));
}
}
/**
* shortcut method to make the class decrypt all of the fields that should be decrypted for data display and return
* #throws Exception
*/
public void decryptFields() throws Exception {
setLastName(Crypto.decryptHex(getLastName()));
setFirstName(Crypto.decryptHex(getFirstName()));
if(getDateOfBirth() != null) {
setDateOfBirth(Crypto.decryptHex(getDateOfBirth()));
}
}
}
}
(I assume) Data is persisted to the database when a Vertex's property is set. If you want to store encrypted values in the database, then you need to ensure the value is encrypted when the property is set.
If you want to override the default behaviour of the #Property getter/setter methods (so that you can add en/decryption), I'd recommend using a custom handler (e.g. #JavaHandler).
For example:
IPerson
#JavaHandlerClass(Person.class)
public interface IPerson extends VertexFrame {
#JavaHandler
public void setFirstName(String firstName);
#JavaHandler
public String getFirstName();
}
Person
abstract class Person implements JavaHandlerContext<Vertex>, IPerson {
#Override
void setFirstName(String firstName) {
asVertex().setProperty('firstName', encrypt(firstName))
}
#Override
String getFirstName() {
return decrypt(asVertex().getProperty('firstName'))
}
static String encrypt(String plain){
return plain.toUpperCase(); // <- your own implementation here
}
static String decrypt(Object encrypted){
return encrypted.toString().toLowerCase(); // <- your own implementation here
}
}
Usage example (Groovy)
// setup
IPerson nickg = framedGraph.addVertex('PID1', IPerson)
IPerson jspriggs = framedGraph.addVertex('PID2', IPerson)
nickg.setFirstName('nickg')
jspriggs.setFirstName('jspriggs')
// re-retrieve from Frame vertices sometime later...
IPerson nickg2 = framedGraph.getVertex(nickg.asVertex().id, IPerson)
IPerson jspriggs2 = framedGraph.getVertex(jspriggs.asVertex().id, IPerson)
// check encrypted values (these are stored in the DB)...
assert nickg2.asVertex().getProperty('firstName') == 'NICKG'
assert jspriggs2.asVertex().getProperty('firstName') == 'JSPRIGGS'
// check decrypted getters...
assert nickg2.getFirstName() == 'nickg'
assert jspriggs2.getFirstName() == 'jspriggs'
If using Groovy, you could intercept calls to these methods programatically (which would be nice because you could keep using #Property annotations).
I'm not sure if there's a Tinkerpop solution to intercepting these calls, other than writing your own custom handler (maybe try extending the JavaHandlerModule?).
Thanks for the comment, and I should have gotten back to respond to this sooner, but I recently found a better answer to my problem. I was looking for a way to make the encrypt/decrypt happen without overhead and without developers really noticing it happens.
The better way to tackle this issue was actually to write hooks for before insert/update and after read to handle it just at the database layer. I was able to write it in java, package a jar file for it and install it on our orientDB instance, picked up pretty flawlessly and helped us to encrypt the necessary fields without noticing any speed decreases.

GWT+GXT serialization goes wrong after minor changes. But why?

I thought I knew GWT serialization rules, but apparently I don't. This case is just weird, I'm trying to figure it out for couple of hours, still no luck. Maybe you, guys, could lend me a hand on this one?
First things first: the stack trace.
...blah blah blah...
Caused by: com.google.gwt.user.client.rpc.SerializationException: Type 'geos.dto.common.client.Market' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = null
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:619)
at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126)
at com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase.serialize(Collection_CustomFieldSerializerBase.java:44)
at com.google.gwt.user.client.rpc.core.java.util.HashSet_CustomFieldSerializer.serialize(HashSet_CustomFieldSerializer.java:39)
at com.google.gwt.user.client.rpc.core.java.util.HashSet_CustomFieldSerializer.serializeInstance(HashSet_CustomFieldSerializer.java:51)
at com.google.gwt.user.client.rpc.core.java.util.HashSet_CustomFieldSerializer.serializeInstance(HashSet_CustomFieldSerializer.java:28)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeImpl(ServerSerializationStreamWriter.java:740)
at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:621)
at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126)
at com.extjs.gxt.ui.client.data.RpcMap_CustomFieldSerializer.serialize(RpcMap_CustomFieldSerializer.java:35)
... 78 more
So it appears the problem lies in geos.dto.common.client.Market. Let's see the minimal that still can be compiled.
package geos.dto.common.client;
public class Market extends RowModel<Integer> {
public static final String ID="id";
public static final String NAME="name";
public Market() { }
public Market(int id, String name) { }
public String getName() { }
public void setName(String name) { }
}
Either I really need a vacation, or it's just fine. A LOT of DTO classes inherit from RowModel, they are working and are serialized properly, no problems there. But of course I'll show you anyway. This time some GXT stuff ahead. This class is unedited, but still fairly simple.
package geos.dto.common.client;
import com.extjs.gxt.ui.client.data.BaseModelData;
public class RowModel<I> extends BaseModelData implements IdentifiableModelData<I> {
private I identifier;
private String identifierProperty;
public RowModel() { }
public RowModel(String identifierProperty) {
this.identifierProperty=identifierProperty;
}
#Override
public I getIdentifier() {
return identifier;
}
public void setIdentifier(I identifier) {
this.identifier = identifier;
if((identifierProperty!=null)&&(!identifierProperty.isEmpty())) {
set(identifierProperty,identifier);
}
}
public void setIdentifierProperty(String identifierProperty) {
this.identifierProperty = identifierProperty;
if(identifier!=null) {
set(identifierProperty,identifier);
}
}
public String getIdentifierProperty() {
return identifierProperty;
}
#Override
public <X> X set(String property, X value) {
if(property.equals(identifierProperty)&&((identifier==null)||(!getIdentifier().equals(value)))) {
setIdentifier((I)value);
}
return super.set(property, value);
}
}
Looks somewhat weird, I know, but these identifier is really important. I removed toString() which - in this case - returns null (because internal RpcMap is null, and it's null because no values are set in Market class). And the last piece of code, the interface implemented by RowModel:
package geos.dto.common.client;
import com.extjs.gxt.ui.client.data.ModelData;
import java.io.Serializable;
public interface IdentifiableModelData<I> extends ModelData, Serializable {
public I getIdentifier();
}
The versions are GWT 2.4.0 and GXT 2.2.5. I want to upgrade it soon, but first I want to deal with problems like this one.
And that would be all, I think. Do you see anything I can't see? I certainly hope so! Thanks!
Expecting, that your package structure follows the naming conventions: Is it possible that you have to move your Market-class into the shared package?
If you make a rcp call, the class is serialized on the client side and deserialized on the server side. There fore the class have to be accessible from the client and the server. If you class lies in the client-package, the server can't access this class. Classes that are used on the client and server side are put in a package called shared.
So, all classes that are only needed in your client, should be inside a package called client. Classes, that are needed on the server and the client side should be inside the shared package and classes, that are only neede on the server side are inside the server package.
This is my abstract class, that extends BaseModelData and lies inside the shared package:
package de.gishmo.leela.application.shared.models;
import java.io.Serializable;
import com.extjs.gxt.ui.client.data.BaseModelData;
#SuppressWarnings("serial")
public abstract class MyBaseModel
extends BaseModelData
implements Serializable {
public final static String MYFIELD = "myField";
public abstract String getModelName();
}
works well in RCP-calls.
And please implement the Serializable Interface.
I've got an oblivion.
The problem wasn't in that class, not at all. Thing is, it's transferred using another class, that extends RowModel as well. And it's set this way:
public void setMarkets(Set<Market> markets) {
set(MARKETS,markets);
}
And because I haven't included the Market type in that class, GWT didn't know it should be serialized at compilation time. Adding private Market _market; in that class did the trick. Actually it's well known issue related to subclasses of BaseModelData (that it can't serialize types that are not declared as class fields), but I totally forgotten it...