Issue: Action redirect do not include parameter as complex objects in Struts2? - redirect

I have tried an example in which i have inserted a user using insert method of UserAction class.
On insert I have redirected the success to loadAdd method of UserAction.
During redirect I have passed the parameter as
${user}
In struts 2.0.14 this gives an ognl exception.
whereas when I pass
${user.id}
it works.
My observation says this is a bug in struts or ognl that it does parse composite objects while it parses simple data types.
Any work-around please suggest.
Or
Is there any way by which I can forward the complete action context or value stack in the redirected action

It's not a bug.
Struts2 uses a type conversion system to convert between Strings (native HTTP) and other objects. It has default type converters for all of the standard primitives, boxed primitives, collections, maps, etc. If you want to allow Struts2 to automatically convert between a string and your User class, you need to create a type converter for it. Otherwise, you can use ${user.id}, which is a primitive or boxed primitive.
http://struts.apache.org/2.2.3/docs/type-conversion.html
Also, the ValueStack is per-request, so when you redirect and create a new request, the previous requests ValueStack is no longer available.

Related

Node.CloneNode() not a function -dom-to-image.js

I want to create a .png file of a HTML page in angularjs and download it. For this I'm currently using dom-to-image.js and using the domToImage.toBlob function and passing the node element to it. But internally when it goes to dom-to-image.js it throws the error:
node.cloneNode() is not a function
Can anyone please assist me here?
Thanks
This error arises when you attempt to call cloneNode() on anything other than a single DOM node.
In this case, the error is coming from the dom-to-image library, which calls that method internally.
Note that without a code snippet, its hard to identify the precise issue with your code, but the point is, when you call domtoimage.toBlob(), you need to supply a single DOM node.
So double check what you are calling it with. If you are selecting by class, for instance, you could end up with more than one element.
Its best practice to be precise with which node you want to convert to a blob - use the id attribute, like this:
domtoimage.toBlob(document.getElementById('element')).then(...)
where element is the id of your target node.
Its also possible you're selecting with angular.element() or even using jQuery directly.
In both cases, this returns an Object -- which you can't call cloneNode() on.
Also note the following from the Angular docs for angular.element():
Note: All element references in AngularJS are always wrapped with jQuery or jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.
Which means you would observe the same behavior in both cases, e.g. both of these:
domtoimage.toBlob($('#element')).then(...)
domtoimage.toBlob(angular.element('#element')).then(...)
would result in the error you see. You can index the Object before supplying it to domtoimage.toBlob(), perhaps like this:
domtoimage.toBlob($('#element')[0]).then(...)
domtoimage.toBlob(angular.element('#element')[0]).then(...)
and that would also work.
Also check out this post about "cloneNode is not a function".

Access to Bind Parameters in MyBatis Interceptor

How do I read the bind parameters inside a MyBatis Interceptor? I'm trying to extract those information so I can write them to a log table.
The guide (http://www.mybatis.org/mybatis-3/configuration.html) didn't mention how to get them, and the JavaDoc (http://www.mybatis.org/mybatis-3/es/apidocs/org/apache/ibatis/mapping/BoundSql.html) does not have a single line of comment. I saw an example on SO about constructing a new BoundSql but that isn't what I needed.
I tried to test what contents are stored in BoundSql.getParameterMappings() and BoundSql.getParameterObject(), but it seems to be pretty complex. There's JavaType and JdbcType, and if there's only one parameter the ParameterObject isn't a Map object.
What is the proper way to get the bind parameters from BoundSql?
After going through MyBatis source code (where comment is an endangered species), I found out how MyBatis processes the bind parameters. However, that requires access to the JDBC Statement object, which is simply not available inside an Interceptor.
Then I did some testing and settled on this:
If there is only a single parameter, BindSql.getParameterObject() will give you the parameter itself. By using BindSql.getParameterMappings() and ParameterMapping.getJavaType() I can tell which Java class the parameter is.
If there are more than one parameter, BindSql.getParameterObject() will return an instance of org.apache.ibatis.binding.MapperMethod.ParamMap, which extends HashMap, or it will be an instance of the DTO you used. Using .getProperty() from ParameterMapping as key or as getter name, you can process the bind parameters one by one.
If anyone has a better way to do this, I'm all ears.

JAX-RS and unknown query parameters

I have a Java client that calls a RESTEasy (JAX-RS) Java server. It is possible that some of my users may have a newer version of the client than the server.
That client may call a resource on the server that contains query parameters that the server does not know about. Is it possible to detect this on the server side and return an error?
I understand that if the client calls a URL that has not been implemented yet on the server, the client will get a 404 error, but what happens if the client passes in a query parameter that is not implemented (e.g.: ?sort_by=last_name)?
Is it possible to detect this on the server side and return an error?
Yes, you can do it. I think the easiest way is to use #Context UriInfo. You can obtain all query parameters by calling getQueryParameters() method. So you know if there are any unknown parameters and you can return error.
but what happens if the client passes in a query parameter that is not implemented
If you implement no special support of handling "unknown" parameters, the resource will be called and the parameter will be silently ignored.
Personally I think that it's better to ignore the unknown parameters. If you just ignore them, it may help to make the API backward compatible.
You should definitely check out the JAX-RS filters (org.apache.cxf.jaxrs.ext.RequestHandler) to intercept, validate, manipulate request, e.g. for security or validatng query parameters.
If you declared all your parameters using annotations you can parse the web.xml file for the resource class names (see possible regex below) and use the full qualified class names to access the declared annotations for methods (like javax.ws.rs.GET) and method parameters (like javax.ws.rs.QueryParam) to scan all available web service resources - this way you don't have to manually add all resource classes to your filter.
Store this information in static variables so you just have to parse this stuff the first time you hit your filter.
In your filter you can access the org.apache.cxf.message.Message for the incoming request. The query string is easy to access - if you also want to validate form parameters and multipart names, you have to reas the message content and write it back to the message (this gets a bit nasty since you have to deal with multipart boundaries etc).
To 'index' the resources I just take the HTTP method and append the path (which is then used as key to access the declared parameters.
You can use the ServletContext to read the web.xml file. For extracting the resource classes this regex might be helpful
String webxml = readInputStreamAsString(context.getResourceAsStream("WEB-INF/web.xml"));
Pattern serviceClassesPattern = Pattern.compile("<param-name>jaxrs.serviceClasses</param-name>.*?<param-value>(.*?)</param-value>", Pattern.DOTALL | Pattern.MULTILINE);

What is to prefer in Restlet: handleGet, handlePost OR represent, acceptRepresetation?

IMHO, there are two techiques to handle a query for a resource:
For http GET you can override represent(Variant variant) or handleGet().
For http POST the same applies with acceptRepresentation(Representation entity) and handlePost().
The doc for handleGet says:
Handles a GET call by automatically returning the best representation available. The content negotiation is automatically supported based on the client's preferences available in the request. This feature can be turned off using the "negotiateContent" property.
and for represent:
Returns a full representation for a given variant previously returned via the getVariants() method. The default implementation directly returns the variant in case the variants are already full representations. In all other cases, you will need to override this method in order to provide your own implementation.
What are the main differences between these two types of implementations? In which case should I prefer one over the other? Is it right that I can achieve with e.g. handleGet() everything that would work with represent()?
I first started using handleGet setting the entity for the response. When I implemented another project I used represent. Looking back i can't really say one way is better or clearer than the other. What are your expirences for that?
I recommend using represent(Variant) because then you’ll be leveraging the content negotiation functionality provided by the default implementation of handleGet(Request, Response).
BTW, lately I've started using the annotation-based syntax instead of overriding superclass methods, and I like it. I find it clearer, simpler, and more flexible.
For example:
#Post('html')
Representation doSearch(Form form) throws ResourceException {
// get a field from the form
String query = form.getFirstValue("query");
// validate the form - primitive example of course
if (query == null || query.trim().length() == 0)
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Query is required.");
// do something
SearchResults searchResults = SearchEngine.doSearch(query);
// return a HTML representation
return new StringRepresentation(searchResults.asHtmlString(), MediaType.TEXT_HTML);
}
The advantages of using this approach include the incoming representation being automatically converted to a useful form, the method can be named whatever makes sense for your application, and just by scanning the class you can see which class methods handle which HTTP methods, for what kind of representations.

In ASP.NET MVC 2 / EF, comma in number causes model binding error

In my HTTP POST controller method for add/editing data, I'm receiving an entity from my EF data model. Some of the fields in that entity are of type double. Everything works fine unless the user types in a comma for a thousands separator, which then causes a model binding validation error.
Has anyone run into this before? Is replacing the default model binder with a custom one the only solution or is there a better approach?
Any advice would be greatly appreciated.
Thanks.
Modelbinding for MVC uses a culture invariant mode of binding. Therefore numbers must be in the 100000.00 format.
Though the following relates to the datetime it also is pertinent to the decimal type as well.
Quote from the asp.net team member:
"This is intentional. Anything that is part of the URI (note the 'Uniform' in URI) is interpreted as if it were coming from the invariant culture. This is so that a user in the U.S. who copies a link and sends it over IM to a friend in the U.K. can be confident that his friend will see the exact same page (as opposed to an HTTP 500 due to a DateTime conversion error, for example). In general, dates passed in RouteData or QueryString should be in the format yyyy-mm-dd so as to be unambiguous across cultures.
If you need to interpret a QueryString or RouteData parameter in a culture-aware manner, pull it in as a string, then convert it to the desired type manually, passing in the desired culture. (DateTime.Parse has overloads that allow you to specify a culture.) If you do this, I recommend also taking the desired culture as a QueryString or a RouteData parameter so that the 'Uniform' part of URI isn't lost, e.g. the URL will look something like ...?culture=fr-fr&date=01-10-1990."