I've noticed BlazeDS has certain things it does not support and it is often difficult to find this out. Ex: polymorphism is not. One must create methods with different names as methods with the same name with different parameters create a conflict.
I'm trying to find out if BlazeDS does not support Java static and non-static inner classes.
Details of an example pointing out the issue:
public class UserDTO {
private String name;
private AddressDTO adddress;
private PhoneDTO phone;
....
public static class PhoneDTO {
private String phoneNumber;
.....
}
public class AddressDTO {
private String address;
.....
}
This code appears to work fine for passing data to Flex via BlazeDS but results in errors when passing the data from Flex via BlazeDS back to Java.
#Service
#RemotingDestination(channels = { "my-amf" }, value = "UserService")
public class UserService {
....
public UserDTO getUser(Long userID) {
.....
return userDTO;
}
public void updateUser(UserDTO userDTO) {
....
}
public void updatePhone(PhoneDTO phoneDTO) {
.....
}
The example code above will compile and the getUser method will work. A call to the updateUser or updatePhone methods on the other hand results in a BlazeDS error. Is there a special way to use inner classes in Flex or are inner classes not supported?
Here is an example of the error messages produced:
[BlazeDS]Cannot create class of type 'com.test.dto.UserDTO.PhoneDTO'.
flex.messaging.MessageException: Cannot create class of type 'com.test.dto.UserDTO.PhoneDTO'. Type 'com.test.dto.UserDTO.PhoneDTO' not found.
Example Flex code:
var thisPhone:PhoneDTO = new PhoneDTO();
thisPhone.phoneNumber = "8885551212";
updateTagsResult.token = userService.updatePhone(thisPhone);
As for the static classes, I'm also very skeptical that they can be used as well. Static classes are possible in Actionscript, but only in the same file (private static) and I don't believe AMF3 supports it.
The purpose of AMF3 is just to have simple property to property serialization between classes. Anything more complex than that is hard to transfer over and frankly, shouldn't be done in the first place because the complexity will, in all probability, affect your development. This is why Java has DTOs. Abstract data objects that can be transferred to any languages using your choice of data protocol.
Inner Classes
No, sending an Actionscript object aliased to a Java inner class (static or otherwise) is not supported out-of-the-box.
As you've seen, when the AMF packet is deserialized, the class name is interpreted as an outer class, rather than as an inner class.
However, you could implement this yourself by having your classes implement IExternalizable. (See here for further information)
An alternative to IExternalizable is to use an approach similar to this one, which provides support for Java Enum's to be sent across to Flex. They use a custom deserializer endpoint.
In the interests of completeness, I should point out that serializing Actionscript inner classes is supported, however the [RemoteClass] metatag is not. Instead, inner classes must be explicitly registered using registerClassAlias, normally within a static method of the outer class.
Polymorphism
To correct a point in the original post:
.... Ex: polymorphism is not. One must create methods with different names as methods with the same name with different parameters create a conflict.
Given that BlazeDS is a server-side product, I'm assuming that you're referring to the way BlazeDS handles Polymorphism & overloading in Java. In which case, your statement is incorrect.
For example, the following code is valid:
#RemotingDestination
public class EchoService {
public String echo(String source)
{
return "Received String";
}
public Object echo(Object source)
{
return "Recieved object of type " + source.getClass().getName();
}
Executed as follows:
remoteObject.echo("Hello") // result from service is "Received String"
remoteObject.echo(new Date()) // result from service is "Received object of type java.util.Date"
However, this is not an example of polymoprhism, as your question states. This is method overloading, which is different.
Polymorphism is supported, as shown here:
// Java
// This method on EchoService
public String echo(Employee employee)
{
return employee.sayHello();
}
public class Employee {
public String sayHello() {
return "Hello, I'm an employee";
}
}
public class Manager extends Employee {
#Override
public String sayHello() {
return "Hello, I'm a Manager";
}
}
Executed as follows:
// In flex...
remoteObject.echo(new Employee()) // Recieves "Hello, I'm an employee"
remoteObject.echo(new Manager()) // Recieves "Hello, I'm a Manager"
If we remove the echo(Employee employee) method, then the result is:
// In flex...
remoteObject.echo(new Employee()) // Recieves "Recieved object of type Employee"
remoteObject.echo(new Manager()) // Recieves "Recieved object of type Manager"
Related
I'm having a question about the implementation of this example here: https://dev.grakn.ai/docs/examples/phone-calls-migration-java. We have an abstract method inside a nested abstract static class:
public class PhoneCallsCSVMigration {
/**
* representation of Input object that links an input file to its own templating function,
* which is used to map a Json object to a Graql query string
*/
abstract static class Input {
String path;
public Input(String path) {
this.path = path;
}
String getDataPath() {
return path;
}
abstract String template(Json data);
}
...
Later on, the abstract method template(Json data) is overridden with the aim of obtaining a graqlInsertQuery:
inputs.add(new Input("files/phone-calls/data/companies") {
#Override
public String template(Json company) {
return "insert $company isa company, has name " + company.at("name") + ";";
}
});
First of all, how is it even possible to instantiate something of the type Input? And secondly, where does the Json company come from? I want to split up the PhoneCallsCSVMigration class into several classes like Input, GraknHandler, QueryHandler etc., and I'm wondering how I can define the template for constructing a Graql insert query other than overriding the abstract class. Any help is highly appreciated.
First of all, how is it even possible to instantiate something of the
type Input?
You're not instantiating class Input. You're creating an instance of an anonymous class that derives from Input and that implements its abstract method template.
where does the Json company come from?
It comes from the one that will invoke the template method, passing it as the parameter.
I leave the rest of the question to somebody who understood it...
Evidenty externally an Input child is created with a path and implementing template.
Probably this object is passed to the surrounding class and it calls template passing Json data.
The abstract method could just as easily be replaced by a Function<Json, String> but then that function would miss the path, so one could use BiFunction<String, Json, String>.
You have to look where and when the path and Json come from. Here it seems a bit artificial. Instead of an static inner class as above, a traditional (very similar) pattern would be:
abstract class A {
public final void func() { // Some service offered by this class.
B b = ...;
C c = onFunc(b);
}
abstract protected C onFunc(B b); // Some requirement to implement.
}
Here func is for users of A, a service.
And onFunc is for implementors of A to fulfill a specific requirement.
So out of context as in your case is a bit weird or over-engineered. Just passing a callback function would seem to do.
Since I have a terrible memory, I like to put all the detnd I ails of data objects into enumerations, so I can use code completion in the IDE adon't have to keep referring back to get the name of a table or the name of a field. Usually I use some type of class containing only Enums for the purpose.
Lets say I have table of "Domains" (database source) "Tables" and "Fields" that look something like this:
public class DataObjectNames {
public enum Domains {
Domain1,
Domain2;
}
public enum Domain1Tables {
Customers,
Orders;
}
public enum Domain2Tables {
OrderItems,
Shipments;
}
public enum CustomerFields {
id,
email;
}
public enum OrderFields {
id,
customerId;
}
//fields for OrderItems and Shipments . . .
}
But suppose I wanted to be able to do something like:
Domain1.tables().Customers.fields(). //code completion supplies choices?
What I would like ot happen after I type the period is for autocomplete to provide a choice between .id and .email, much the same as it would if "fields" returned an object with two methods, or if I just typed
CustomerFields.
in the IDE.
In order for that to happen, it seems to me I somehow need to return not a specific instance of an enumeration, but the enumeration itself. I've tried various approaches like this:
public enum Domains {
Domain1 {
#Override
public Enum<?> tables() {
return Domain1Tables.foo();
} //Is there a method that will return the enum itself?
},
Domain2 {
#Override
public Enum<?> tables() {
return Domain2Tables.foo();
};
public abstract Enum<?> tables();
}
But of course I haven't been able to find a funciton foo() that returns the enum class itself.
Any thoughts?
You can't do this with enums because Java's class model doesn't work the way you would need in order for this style to work.
I haven't been able to find a function foo() that returns the enum class itself.
Returning the enum class itself is easy, you just do Domain1Tables.class, but that won't give you the completion you want because what it gives you is a Class<Domain1Tables> object, and that object doesn't have fields named Customers and Orders.
You want to be able to treat the "Domain1Tables" class as if it's an object and refer to the enum constants (which are effectively static final fields) as if they were members of that object, but Java simply doesn't do that.
If you give up on using enums for it, then you can simply have:
public class DataObjectNames {
public class Domains {
class Domain1 {
class Tables {
class Customers {
public static final String id = "id";
public static final String email = "email";
}
}
}
}
}
but in that case DataObjectNames.Domains.Domain1 wouldn't be a valid expression anymore (because it reference to a class scope, but not to an object.
There's probably a solution to what you're trying to do, but without more context I can provide anything more details than what's above.
//Interface DAO
public abstract class BaseDAO<T extends BaseDTO> {
public void update(T t) throws DBException {
Field[] fieldsToInsert = t.getClass().getDeclaredFields();
//code to update database object academic or event
}
public Integer create(T t) throws DBException {
Field[] fieldsToInsert = t.getClass().getDeclaredFields();
//code to create academic or event in database
}
}
//Concrete DAOs
public class AcademicDAO extends BaseDAO<AcademicDTO> {
//provide implementation
}
public class EventDAO extends BaseDAO<EventDTO> {
//provide implementation
}
//Transfer object
public class AcademicDTO extends BaseDTO {
String title;
String surname;
//getters and setters
}
public class BaseDTO {
protected Integer ID;
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
}
Hello Guys, I have a sample code on me that follows the above structure to create a small java application to manage academics and events. It is leniently following this pattern
1- You experts are familiar with this pattern more than me. I would like to understand why generics are used in this case so DAOs can extend and implement a generic base class. It would be great if one can show how generics here may be advantageous using an example.
2 - I have also witnessed the use of java Fields. Is there a link between generics and Fields?
I would like to document DAO pattern in an academic report, but I am finding difficult to understand how Generics and Reflect Field play a part here. Do they support flexibility and loose coupling?
The code you've provided is reusable set of logic to load and persist entities. Many times, in an application of non-trivial size, you'll wind up persisting many different types of objects. In this example, you can define as many objects as necessary, but only define the logic to actually save and load once. By asking the DTO what Field objects are there, it can get at the data to help construct queries for loading and saving.
Generics allow you to use this pattern while maintaining type safety. AcademicDAO can only handle AcadmeicDTO. You can't use AcademicDAO to store EventDTO. Generics allow the instance of the class to rely on a more specific type when dealing with the Field objects. If you didn't have generics, the BaseDAO would take Object, and you wouldn't be able to access any methods except those that Object provides because the JVM wouldn't know what class is provided, so it has to limit it's knowledge to that of Object. Using getClass().getDeclaredFields() bypasses that limitation because getClass() returns the actual class of the Object parameter.
Field is just a way to use reflection to access the values of the properties in each DTO. If you had to access the fields directly, with getTitle(), you couldn't reuse a generic base class to do your persistence. What would happen when you needed to access EventDTO? You would have to provide logic for that. Field allows you to skip that logic.
Edit:
To explain what I mean by accessing getID, you could do the following within BaseDAO because T is known to be a BaseDTO with a getID() method defined:
public abstract class BaseDAO<T extends BaseDTO> {
public boolean update(T t) throws DBException {
Integer id = t.getID();
Field[] fields = t.getClass().getDeclaredFields();
// Assuming you have a db object to execute queries using bind variables:
boolean success = db.execute("UPDATE table SET ... WHERE id = ?", id.intValue());
return success;
}
}
If you had this instead (in a non-generic class):
public boolean update(Object o) throws DBException {
// This line doesn't work, since Object doesn't have a getID() method.
Integer id = t.getID();
Field[] fields = o.getClass().getDeclaredFields();
boolean success = db.execute("UPDATE table SET ... WHERE id = ?", id.intValue());
return success;
}
You'd have to look through those Field objects, or ask for the ID field and assume it existed.
For question 1. The use of generics allows the same implementations of update and create to be used regardless of the type of the DTO. Consider if you didn't use generics. Then the best you could do for the parameter type of update would be BaseDTO, but then you could call
academicDAO.update( eventDTO )
which doesn't make sense. With the code as you have it, this would be a type error. So the main advantage is: better type checking.
For question 2. The use of Fields allows a single implementation of update and create to work on DTO object of various concrete types.
I often find I want to do something like this:
class Foo{
public static abstract String getParam();
}
To force a subclasses of Foo to return a parameter.
I know you can't do it and I know why you can't do it but the common alternative of:
class Foo{
public abstract String getParam();
}
Is unsatisfactory because it requires you to have an instance which is not helpful if you just want to know the value of the parameter and instantiating the class is expensive.
I'd be very interested to know of how people get around this without getting into using the "Constant Interface" anti pattern.
EDIT: I'll add some more detail about my specific problem, but this is just the current time when I've wanted to do something like this there are several others from the past.
My subclasses are all data processors and the superclass defines the common code between them which allows them to get the data, parse it and put it where it needs to go.
The processors each require certain parameters which are held in an SQL database. Each processor should be able to provide a list of parameters that it requires and the default values so the configuration database can be validated or initialised to defaults by checking the required parameters for each processor type.
Having it performed in the constructor of the processor is not acceptable because it only needs to be done once per class not once per object instance and should be done at system startup when an instance of each type of class may not yet be needed.
The best you can do here in a static context is something like one of the following:
a. Have a method you specifically look for, but is not part of any contract (and therefore you can't enforce anyone to implement) and look for that at runtime:
public static String getParam() { ... };
try {
Method m = clazz.getDeclaredMethod("getParam");
String param = (String) m.invoke(null);
}
catch (NoSuchMethodException e) {
// handle this error
}
b. Use an annotation, which suffers from the same issue in that you can't force people to put it on their classes.
#Target({TYPE})
#Retention(RUNTIME)
public #interface Param {
String value() default "";
}
#Param("foo")
public class MyClass { ... }
public static String getParam(Class<?> clazz) {
if (clazz.isAnnotationPresent(Param.class)) {
return clazz.getAnnotation(Param.class).value();
}
else {
// what to do if there is no annotation
}
}
I agree - I feel that this is a limitation of Java. Sure, they have made their case about the advantages of not allowing inherited static methods, so I get it, but the fact is I have run into cases where this would be useful. Consider this case:
I have a parent Condition class, and for each of its sub-classes, I want a getName() method that states the class' name. The name of the sub-class will not be the Java's class name, but will be some lower-case text string used for JSON purposes on a web front end. The getName() method will not change per instance, so it is safe to make it static. However, some of the sub-classes of the Condition class will not be allowed to have no-argument constructors - some of them I will need to require that some parameters are defined at instantiation.
I use the Reflections library to get all classes in a package at runtime. Now, I want a list of all the names of each Condition class that is in this package, so I can return it to a web front end for JavaScript parsing. I would go through the effort of just instantiating each class, but as I said, they do not all have no-argument constructors. I have designed the constructors of the sub-classes to throw an IllegalArgumentException if some of the parameters are not correctly defined, so I cannot merely pass in null arguments. This is why I want the getName() method to be static, but required for all sub-classes.
My current workaround is to do the following: In the Condition class (which is abstract), I have defined a method:
public String getName () {
throw new IllegalArugmentException ("Child class did not declare an overridden getName() method using a static getConditionName() method. This must be done in order for the class to be registerred with Condition.getAllConditions()");
}
So in each sub-class, I simply define:
#Override
public String getName () {
return getConditionName ();
}
And then I define a static getConditionName() method for each. This is not quite "forcing" each sub-class to do so, but I do it in a way where if getName() is ever inadvertently called, the programmer is instructed how to fix the problem.
It seems to me you want to solve the wrong problem with the wrong tool. If all subclasses define (can't really say inherit) your static method, you will still be unable to call it painlessly (To call the static method on a class not known at compile time would be via reflection or byte code manipulation).
And if the idea is to have a set of behaviors, why not just use instances that all implement the same interface? An instance with no specific state is cheap in terms of memory and construction time, and if there is no state you can always share one instance (flyweight pattern) for all callers.
If you just need to couple metadata with classes, you can build/use any metadata facility you like, the most basic (by hand) implementation is to use a Map where the class object is the key. If that suits your problem depends on your problem, which you don't really describe in detail.
EDIT: (Structural) Metadata would associate data with classes (thats only one flavor, but probably the more common one). Annotations can be used as very simple metadata facility (annotate the class with a parameter). There are countless other ways (and goals to achieve) to do it, on the complex side are frameworks that provide basically every bit of information designed into an UML model for access at runtime.
But what you describe (processors and parameters in database) is what I christened "set of behaviors". And the argument "parameters need to be loaded once per class" is moot, it completely ignores the idioms that can be used to solve this without needing anything 'static'. Namely, the flyweight pattern (for having only once instance) and lazy initialization (for doing work only once). Combine with factory as needed.
I'm having the same problem over and over again and it's hard for me to understand why Java 8 preferred to implement lambda instead of that.
Anyway, if your subclasses only implement retrieving a few parameters and doing rather simple tasks, you can use enumerations as they are very powerful in Java: you can basically consider it a fixed set of instances of an interface. They can have members, methods, etc. They just can't be instanciated (as they are "pre-instanciated").
public enum Processor {
PROC_IMAGE {
#Override
public String getParam() {
return "image";
}
},
PROC_TEXT {
#Override
public String getParam() {
return "text";
}
}
;
public abstract String getParam();
public boolean doProcessing() {
System.out.println(getParam());
}
}
The nice thing is that you can get all "instances" by calling Processor.values():
for (Processor p : Processorvalues()) {
System.out.println(String.format("Param %s: %s", p.name(), p.getParam()));
p.doProcessing();
}
If the processing is more complex, you can do it in other classes that are instanciated in the enum methods:
#Override
public String getParam() {
return new LookForParam("text").getParam();
}
You can then enrich the enumeration with any new processor you can think of.
The down side is that you can't use it if other people want to create new processors, as it means modifying the source file.
You can use the factory pattern to allow the system to create 'data' instances first, and create 'functional' instances later. The 'data' instances will contain the 'mandatory' getters that you wanted to have static. The 'functional' instances do complex parameter validation and/or expensive construction. Of course the parameter setter in the factory can also so preliminary validation.
public abstract class Processor { /*...*/ }
public interface ProcessorFactory {
String getName(); // The mandatory getter in this example
void setParameter(String parameter, String value);
/** #throws IllegalStateException when parameter validation fails */
Processor construct();
}
public class ProcessorA implements ProcessorFactory {
#Override
public String getName() { return "processor-a"; }
#Override
public void setParameter(String parameter, String value) {
Objects.requireNonNull(parameter, "parameter");
Objects.requireNonNull(value, "value");
switch (parameter) {
case "source": setSource(value); break;
/*...*/
default: throw new IllegalArgumentException("Unknown parameter: " + parameter);
}
}
private void setSource(String value) { /*...*/ }
#Override
public Processor construct() {
return new ProcessorAImpl();
}
// Doesn't have to be an inner class. It's up to you.
private class ProcessorAImpl extends Processor { /*...*/ }
}
I have DTOs (Data Transfer Objects) sent to the DAO (Data Access Object).
DTO has an identifier string.
Based on this string (or rather the DTO), I want to invoke specific methods in the DAO.
These methods make database calls.
I have found two options to do this:
1. Constant specific method implementation using Enum
2. Invoke the method based on reflection ( in which case the DTO will carry the name of the method that needs to be invoked.)
I want to know which is a better option. Are there any other alternatives ? Is it okay to have database calls within the Enum.
The programming language used is Java.
I would not put database calls within your Enum. Instead, provide a method on your DAO that accepts the DTO, and then let that method call other methods within the DAO based on the string on the DTO. You could use a switch statement on the Enum, and make this very efficient. (Alternatively, put this implementation in a separate "adapter" class, since it could be argued that this code doesn't strictly belong in the DAO, either.)
I would also avoid reflection, mainly due to additional complexities - including in debugging and troubleshooting, as well as potential security concerns. (What if the String contained a method name that you didn't want called?)
You can create a map that maps the strings to method calls:
class YourDAO {
private interface Action {
public void perform();
}
private Map<String, Action> actions;
public YourDAO() {
actions.add("String1", new Action() {
public void perform() {
daoMethod1();
}
}
actions.add("String2", new Action() {
public void perform() {
daoMethod2();
}
}
}
public void daoMethod1() {
...
}
public void daoMethod2() {
...
}
public void doSomethingWithDTO(YourDTO dto) {
actions.get(dto.getIdentifier()).perform();
}
}
You can even adapt this idea to perform specific actions on different DTO types if you
change the key type of the map to Class<?> and instead of dto.getIdentifier() use dto.getClass().