I am working with the HttpExchange class, and want to use the getAttribute function to get the POST parameters. If i just call the function and print the results it works. But there has to be some better way to access the returned object and get the contained data.
The Manual is here: http://download.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#getAttribute%28java.lang.String%29
How can i access the Object? Which methods does it have?
I am not familiar with this API, but it appears that HttpExchange.getAttribute is not the method you would use to get POST parameters. Rather it is a mechanism for sharing information within a chain of Filters. Since you would implement the Filters, you would document and understand the attributes that can be stored.
To read the POST details, wouldn't you do HttpExchange.getRequestBody?
Use Java Reflection. Using reflection you could do something like this
Class c = Class.forName("YourClassName");
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString()); //iterate through these methods to find out data
The HttpExchange returns you the type Object for the given attribute name, It is assumed that the one who try to retrieve the attribute knows the type of the attribute and can downcast the Object to appropriate class. E.g. -
String attrValue = (String) httpExchangeObject.getAttribute("nameOfTheAttribute");
you don't need to use reflection on the returned object to find out the structre.. I feel simple down-casting should solve the purpose.
I'm not familiar with this API either. The request POST parameters should be available in raw, unparsed form from getResponseBody(). However, if you know that the getAttribute method will contain the data you need, but you don't know which class it will have (I don't know how you would know the former without knowing the latter, but anyway), you can use reflection to print the name of the class:
System.out.println (foo.getAttribute("name").getClass ());
If it turns out to be an internal, undocumented class, you can then use more reflection (or other techniques) to look at the class hierarchy until you find a publicly-documented class or interface that you can use.
But this shouldn't be necessary because what you need should be documented somewhere.
Related
I'm doing a very simple thing that should just work, IMO. I've got a resource like:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("{nodeType}/{uuid}")
public Object getResourceInfo(#PathParam("nodeType") String nodeType,
#PathParam("uuid") String uuid,
#Context SecurityContext authority) { ...
Note I'm returning type Object. This is because depending on the call (here depending on the nodeType argument) I want to return a different concrete class (which will always be #XmlRootElement) and have that get marshalled out into the response.
However, this does not work. I get exception like:
Exception Description: A descriptor for class com.mycompany.XmlElementTypeInstance was not found in the project. For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.
If I change Object to a single subclass, it works. But I want it to be able to handle any subclass, XmlElementTypeInstance, XmlElementTypeInstance2, etcetc.
I tried making a common interface from which all of the XmlElementTypeInstance subclasses derive, but then I only get those properties in the interface, not the extra properties in the subclasses. Playing with #XmlElementRef and adding all possible properties to the common interface is extremely ugly and can't work quite correctly to generate the JSON I want, so please don't suggest that. =)
Is there any way to do this? It seems like simple, basic, necessary functionality... any other REST framework I've used, no problem...
The solution it turns out is simple (had to read the JSR instead of the actual Jersey docs, however!)
Instead of returning Object, returning Response (section 3.3.3 of JSR 339) with the object set as the entity forces the implementation to pick an appropriate MessageBody{Writer,Reader} at runtime.
return Response.ok().entity(<the object>).build();
Lost way too much time on this. Hope it helps someone later. =/
I have a model instance already, it's a basic POJO, how can I populate it (by issuing a SELECT) with the values using dbutils by calling the setters which are named to match the table column names?
So BasicRowProcessor should match, I just don't find the appropiate class/method to call with the object as parameter.
There is only one instance I want to set, not an array.
I'm not sure I understand your question. Some source code would help.
There are lots of libraries that perform ORM. See source forge for some ORM projects. One of them is sormula which I created. For the simplest use of it, see POJO zero-config example.
All you can do is
YourObject result = new BasicRowProcessor().toBean(yourResultSet,YourObject.class);
It will create the instance though. This API is not designed to allow you to modify an already existing object.
If you really need to update the existing object you might implement a YourObject.copy(YourObject obj) method and call it with the result from BasicRowProcessor.toBean but it looks quite ugly.
An other (also ugly) solution would be to implement the BeanProcessor class, implement the BeanProcessor.newInstance(Class) method to return your object, then pass your implementation instance to the BasicRowProcessor instance.
I've been using AutoBeans to map JSON data coming from a non GWT-RPC Java based web service. Everything has been working so far except for one mapping.
On the server side, the Class has a property of type Map where MyAbstractParentObject is the parent class of about 15 different child classes.
When I map that to a corresponding AutoBean interface on the client I'm not able to downcast MyAbstractParentObject to its child type after it's been decoded. I looked all over the GWT docs and 'the Googles' to see if AutoBeans even has polymorphic support but couldn't get an answer either way. Interceptors and Categories don't seem to be able handle this, just methods they want to exist in the interface that aren't getters/setters.
I was attempting to do a workaround using the type field in the JSON data to create an instance of the child class but the AutoBean does not give me access to the raw JSON, even though in the debugger I can see it as a protected field called 'data'. If I try to decode the original bean it will only have the fields in the MyAbstractParentObject.
The only alternatives I can see are to:
Extend or create my own AutoBeanCodex that can properly handle the
children of MyAbstractParentObject when it decodes the JSON.
Find a way to get to the raw JSON in the MyAbstractParentObject AutoBean
and use that to create and instance of the child class on the fly.
Switch to some other JSON-GWT Serialization framework like
GWTProJSONSerializer or piriti.
Any help would be appreciated.
I know this was asked a long time ago, but I struggled to find an answer too. I realized that the AutoBeans, since they're basically just fancy wrappers for the JSON, still contain all the data for the fields of the child object you want to downcast it to. So I wrote a method like this:
public <A, B> B cast( A sourceObject, Class<B> targetClass )
{
AutoBean<A> sourceBean = AutoBeanUtils.getAutoBean( sourceObject ); // Get the corresponding AutoBean.
HasSplittable splittableBean = ( HasSplittable ) sourceBean; // Implementation (if still AbstractAutoBean) supports this interface ;)
Splittable splittable = splittableBean.getSplittable().deepCopy(); // If you don't copy it, decode() tries to be clever and returns
// the original bean!
AutoBean<B> targetBean = AutoBeanCodex.decode( typeFactory, targetClass, splittable ); // Create new AutoBean of
// the target type.
return targetBean.as(); // Get the proxy for the outside world.
}
--Where typeFactory extends AutoBeanFactory, as you can see.
It's worked well enough for me. The trickiest bit was the cast to HasSplittable, since AutoBean doesn't extend that interface, but AbstractAutoBean (which implements AutoBean) does -- and a subclass of that is what's returned by calls to getAutoBean().
You also need to copy the Splittable, otherwise AutoBeanCodex thinks, "hey, I already have an AutoBean for that Splittable! Here you go!" -- and just gives you the original. ;)
Anyway, you can cast downwards, upwards...sideways! :P
Late edit: Stumbling upon this again months later, I figured I'd add a small caveat about something Jonathan mentioned below. The method I've described here is designed to be used on an AutoBean that hasn't been modified since it was deserialized. That's because (AFAIK) there's no guarantee that any setters you call will actually update the JSON (needed for the casting). This probably isn't a big deal, since typically you'll use this when you have an incoming DTO and you want to cast it to its real type ASAP, before doing anything else with it. In our case, none of our AutoBeans even had setters, so it wasn't really an issue. ;)
After you've cast it, you can do whatever you want with the resulting bean, which is fresh out of the factory after all!
I'm not very familiar with AutoBean but you probably can use the serializer/deserializer from RestyGWT. It supports polymorphism by making use of annotation.
link to the documentation:
http://restygwt.fusesource.org/documentation/restygwt-user-guide.html#Polymorphic_Sub_Types
I am using an API that gives access to a certain set of subclasses with a common interface. I use the interface throughout my code, and the instances are resolved to the proper subclass based on user needs. My problem is that I need to create a copy of one of these objects, but I don't have access to the clone() method and the API doesn't provide a copy constructor.
ie:
ObjectInterface myObject = objectFromParameter.clone(); //Not possible...
Is there a workaround in Java?
iYou might be able to do what you want with reflection. Alternatively, If the object supports serialization, you can serialize to a byte array and then reconstruct a new instance from that.
Looking at some code cleanup and I was wondering the best way to deal with this:
Have a class with some private variables like:
myBool1, myBool2, myBool3
myInt1, myInt2, myInt3
myString1, myString2, myString3
What's the best way to do a getter function that is generic to the return value? So if I do a call to the getter with something like:
myNewBool=<blah>.get("myBool1")
myNewString=<blah>.get("myString2")
myNewInt=<blah>.get("myInt3")
Anyone have any suggestions?
You can't really have a generic getter if you don't know what you want to get, for example :
boolean myNewBool= get("myString1");
If get returns something, but you don't really know if this something is compatible with a boolean, and terrible things could happen.
You could try this:
public <T> get(String element){
return (T) elementToGet;
}
But you would have to specify the return type when you call the get method.
String element = myObject.<String>get("element");
Here are the bad sides :
You can't work directly with primitives
You can have a lot of ClassCastException
If you misspell an attribute name you won't see it until you run it
You don't expose a nice public API, people would have to know evert possible attribute to use it, and as said above, a misspelled attribute (or an inexistant one) wouldn't be seen until runtime.
You have to know the return time and type it each time you use your method
You would have to type a really long (and smelly) code in your get method either to use each possible attribute (if you still want have some private and not accessible) or worse, use reflection to find the right attribute.
So definitively not a good idea.
What you can do instead is using the good old getters//setters and if there is a lot of them, generate them with your IDE.
Another way would be to use the project lombok.
Resources :
Project Lombok
On the same topic :
Create automatically only getters in Eclipse
Eclipse Generate All getters setters in package
Java Getters and Setters
First you should ask what would be the pros and cons of such a solution.
Pros:
One method instead of many
Cons:
Non-intuitive to the users of your class (classical getters are more common)
You cannot have an overload that only differs by a return type, therefore you will have to have methods like getBool, getInt etc.
It's slower - you have to pass the string, check for validity, do a lookup in a map...
The only advantage of your proposed solution would be not repeating the get()/set() code. However, as these methods are usually generated by your IDE and contain only a single-line command, I wouldn't see that as a big problem.
To answer your actual question - you can create a HashMap with name-attribute mapping. Alternatively, you may use Java reflection to access the attributes. The second solution is more general but also harder to write.
This is really a terrible idea. I'm not sure why creating a getter/setter for each private variable is a problem, but passing around strings that map to a variable's symbolic name would be hard to maintain and confusing. You don't need this to be generic; each variable represents a different quantity and they should be accessed as such.
It wouldn't be clean up but mess up. I'd either created 3 getter methods for the fields or redesign it completely. But calling a function, with a name of a field to return, as an argument can bring nothing good.
When you code, you must be refactoring your code for all the time you are coding. But not like this. Solution is delegating logic to another class, wrapping code into more utilizable methods or changing and simplifying domain objects...