Is there a way to turn off reflection on a method? - java

Using XML-RPC client and server, redstone.xmlrpc.XmlRpcServlet and XmlRpcClient
I don't have control of the implementation of the Servlet, but just the client. I am sending an object to the servlet.
The servlet seems to be using some form of reflection on the object I send it. The problem is that I have a method on the object called:
public boolean isPhysicalDevice()
{
return !getAddress().isChannel();
}
However, the servlet gets a list of the keys on the object and gets one key as "physicalDevice", which is not an attribute of the object but only exists as part of the name of this method. Is there a way, I can perhaps annotate the method on the object I send, so the servlet doesn't try to reflect this method and treat it as an attribute of the object?

Factor out the interface you want the servlet to see and pass it a Proxy for that interface which simply delegates every invocation to your object. (Proxy is Serializable.)

Related

Using constructor to set values in Spring MVC

My major intention is to do validation for an object in Spring Controller itself.
My code structure looks like
public #ResponseBody
String functionName(#RequestBody Employee employee){}
The idea is to validate the DTO the moment an http post request is hit
For same,I wrote an exception method to be called in constructor which adds the object to an error queue in case of error.
However the problem is, the values are set in spring by setter and not by constructor.
Is there any way/setting to change it so that values are set by constructor.
EDIT
The intention is to validate object employee the moment request is received without writing another method to validate.
My idea was to do validation in constructor of Employee and in case of failure, Pass the data to a error handler and stop object formation itself.
But it seems, In spring constructor is not used to set data, instead setter's are used.
So question is if constructor can be used.

Override HttpMessageConverter for Spring RequestBody

I have the following code:
#RequestMapping(value="/mobile/device", method = RequestMethod.PUT)
public ResponseEntity<Void> flagDevice (#RequestBody List<MobileDeviceData> devicedataList, #RequestHeader(value="special_code") String specialCode) {
// Implementation details
}
Each instance of MobileDeviceData that gets created needs to have a param field filled in with the RequestHeader special_code.
How would I go about doing this so that it is fully populated by the time the flagDevice method body gets called?
Thanks in advance.
This is non trivial.
An HttpMessageConverter is already provided that deserializes the JSON, that's the MappingJackson2HttpMessageConverter. It has access to request headers. You could extend that class to also use the headers for deserialization (this is extremely difficult to do generically, as opposed to only for MobileDeviceData).
You could use Spring AOP, intercept the method, retrieve the arguments, cast to the appropriate types, and assign the value yourself.
The solution I would go for is the simplest: do it yourself in the handler method. Loop the the List and use a corresponding setter to set the specialCode for each MobileDeviceData.
Another option is to define your own HandlerMethodArgumentResolver specifically for List<MobileDeviceData> parameters that need to be constructed from header vales.

Assigning/Passing value from Java function to JS/JQuery function

Lets say I have a Java function something like
public int getNumber(){
}
which returns some value based on it's logic. And I have a JS file something like
Tapestry.Validator.amountValidator = function(field, message) {
field.addValidator(function(value) {
if (value != null) {
// code here
}
}
});
};
Now I am asking myself is it possible in JS or JQuery to pass value from Java function to it's function(value) in JS and if so, how can it be achieved?
UPDATE: As suggested by abalos answer, Tap for myself has already done 3 out of 4 stages for it. I am providing a function that deals with server side and logic behind it.
#InjectComponent
private TextField amount;
#Inject
private FieldValidatorSource fieldValidatorSource;
public FieldValidator<?> getAmountValidator()
{
return fieldValidatorSource.createValidators(amount, "required,max=" + getBroj());
}
Now here validator is taken from a logic inside a function getBroj(), which is maximum number of what it takes. And this works like a charm on server side. Now I was thinking that what I don't have( using my logic ) is only Client side, and I can achieve it by updating current Validation class from Tapestry that will handle with this kind of request yet known to that class. And to do it I would need to call a js file with a function calling something like above in the example, but I am not quite sure how to pass value from getNumber() function to the JS function above.
You don't need Jersey or DWR or any other framework at all for invoking a method in Tapestry. You just need to ask your questions properly.
final private static String EVENT_NAME = "whateverEventNameYouWant";
#Inject
private ComponentResources resources;
#Inject
private JavaScriptSupport javaScriptSupport;
/** Method that will provide the value you want to pass to JS. */
#OnEvent(EVENT_NAME)
public JSONObject provideValue() {
JSONObject object = new JSONObject();
object.put("value", /* the value you want to pass to JS */);
// other values you may want to pass
return object;
}
void afterRender() {
// This creates an URL for the event you created. Requesting it will
// invoke any event handler methods for that event name.
Link link = resources.createEventLink(EVENT_NAME);
javaScriptSupport.addScript("var eventUrl = '%s';", link.); // the JavaScript variable name doesn't matter. You can choose any you want
}
Then, in your JavaScript, do an AJAX request using the URL in the eventUrl variable. I'll leave this part for you to figure out from the jQuery documentation. The received data is exactly the JSONObject or JSONArray you'll return in your event handler method.
I think you have some very heavy misconceptions into what types of languages Java and jQuery/Javascript are. First off, with the exception of node.js, jQuery/Javascript are used for client-side operations. Java is used for server-side operations. This means that you will need to pass a value from the server to the client.
Now, what you are asking for looks initially like it is trying to perform validation. This should not be completed only on the client-side. There are ways to get around client validation and it is best to leave information from the client in an "untrusted" state until it is validated on the server.
With all that said, to do what you are trying to do will require the use of some method for the client to communicate with the server. My favorite way to do this for simple operations is through a web service.
Here are steps to do what you require, but note that this is not the only way.
Create a web service with Jersey.
Pass the value to the web service via AJAX with either JSON or XML with a request that contains the value.
Perform your validation on the server-side with the information from the service.
Pass a response from the rest service back to the client-side AJAX call and use it for your JS/jQuery code.
Let me know if you have any questions.

How to read parameters passed by extjs record.set(values) in an rest service coded in java?

I am new to extjs and am trying to implement the update operation. I tried to Google but could not find a solution.
I have form which is used for updating records in a store. For this, I am using the following code in the controller,
var formPanel = Ext.getCmp('displayForm');
var record = formPanel.getRecord();
var values = formPanel.getValues();
record.set(values);
companyStore.sync();
The record.set() method calls the method(i.e.rest service) pointed by the URL specified for update operation in the store’s proxy.
How can I read the values passed by the record.set() method in the rest service coded in java.
I tried with,
#POST
#Produces({"application/xml"})
#Path("/updateData")
public CompanyDataService updateData(#QueryParam("company") Company companyObj){
//code
}
but companyObj is unable to capture the parameter values
There is no "values" parameter being passed. Based on the configuration of your store proxy's Writer (http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.writer.Json), the parameters will either be a single root value (if encode configuration is true), or as individually named parameters, one per model field being persisted.
How is your Writer configured?
Also, just to clarify, record.set() doesn't trigger the proxy call unless autoSync is configured to true. In you example, I suspect the proxy call is happening because you explicitly call sync().

Object across web methods + java

I am using a Java Web Service for
#WebService()
public class myWebService {
/**
* Web service operation
*/
MyClass Obj ;
#WebMethod(operationName = "webmethod1")
#Oneway
public void webmethod1(#WebParam(name = "serailNo") String serailNo) {
obj = new MyClass();
//do some operations on obj;
}
/**
* Web service operation
*/
#WebMethod(operationName = "webmethod2")
public void webmethod2() {
//do some operations on obj after doing intial operations in web method1
}
}
I am unable to access obj in webmethod2. It is getting a null pointer exception.
As a detail : I want to create a object . That object should be accessed across all web methods. In such a way webmethod1 will do intial operations on obj and followed web method2 will use the same obj.
How can i achieve this
If you are creating a brand new object, what you could do, would be to make your webmethod1 return whatever object it creates, and then, make webmethod2 take that same object as a parameter.
Another option would be to make webmethod2 take in the serialNo parameter and check that the obj variable is not null. If it is, it will call webmethod1 by passing it that same serial number, and create the object so that it has something to work on.
The reason you are getting a nullpointer is because the webservice is not stateful, i.e the object does not exist during the second call. It is possible to create a stateful webservice but that depends on the kind of webservice and server your running it on...
As npinti mentioned you could send the object along with the service. Although that might not be favorable, e.g if the object is big.
You could create a local cache on the server containing all the created objects by and mapping them with the serialNo.

Categories