Hibernate Validator: Using constants in constraints.xml - hibernate-validator

I am using Hibernate Validator as a JSR-303 validation provider and its xml style constraints descriptions.
So, I have a
<bean class="com.my.User" ignore-annotations="true">
<field name="email">
<constraint annotation="javax.validation.constraints.Pattern">
<element name="regexp"><![CDATA[[A-Za-z0-9\._%+-]{1,64}#[A-Za-z0-9.-]+\.[A-Za-
z]{2,4}]]></element>
</constraint>
</field>
.....
</bean>
I also have a separate class, which contains all my patterns
public final class Regexps {
public static final String EMAIL_REGEXP = "A-Za-z0-9\._%+-]{1,64}#[A-Za-z0-9.-]+\.[A-
Za-z]{2,4}";
....
}
So, as you can see, I have two places, where email regexp is present, and I want only one place.
My question:
Is it possible to use the
public static final String EMAIL_REGEXP = "A-Za-z0-9\._%+-]{1,64}#[A-Za-z0-9.-]+\.[A-
Za-z]{2,4}";
field inside the xml, so that
I could just refer to the contant string field.
So I would Like to have something like:
<bean class="com.my.User" ignore-annotations="true">
<field name="email">
<constraint annotation="javax.validation.constraints.Pattern">
<element name="regexp">Regexps.EMAIL_REGEXP</element>
</constraint>
</field>
.....
</bean>
By the way, it is possible via annotations
public class User {
#Pattern(regexp = Regexps.EMAIL_REGEXP)
private String email;
}
But I cannot use annotations, because I use the legacy POJOs which I use for data transfering and cannot change the source code.

Currently it's not possible to reference constraints from within XML constrained mappings. I think it's a good idea, though. Could you open a feature request in our issue tracker so we can discuss the feature there?
If you can't use annotations, you might give Hibernate Validator's API for programmatic constraint declaration a try, you could then work with a shared constant for the pattern.

Related

Update Document Template Dynamically in Alfresco from property page

I have one document template as like attached screen shot. now my requirement is i want to dynamically update some values of that document when i will upload it in alfresco site. i will either create that Document through node template or upload. I want to provide those values from document property page.
can anyone help me how can i achieve this.
I tried it using java script, but i am getting some problem. so i am thinking for using Alfresco CMIS API. But i am quite new in alfresco cmis. so can any one tell the better way which i can use for this task.
Thanks in advance.
I think you should trigger an custom action by a Rule
When someone update a node (for example by editing properties), your action will be triggered and you will be able to :
get the content of your node
get the properties of your node
use the apache poi library provided by alfresco (my guess is that you use word documents) to find your parameters, and the replace them by the value you find in the property nodes.
Here is an excellent tutorial to learn how to create a custom action.
Note : You may have to keep the original templated document if you want to change a second time your properties (by using versionning for example).
Edit (see discussion below) :
I assume you know how to use rules in alfresco : http://docs.alfresco.com/5.0/tasks/library-folder-rules-define.html
Declare a new action to assign to a rule. This action must be triggered when the excel is dropped or updated
Create an action implementing your need :
public class MyAction extends ActionExecuterAbstractBase {
...
#Override
protected void executeImpl(final Action arg0, final NodeRef arg1) {
// your code here
}
....
}
This action will :
Take the nodeRef parameter (which is the excel file) and load the file
...
Inputstream inputstream = getFileFolderService().getReader(arg1).getContentInputStream();
...
NPOIFSFileSystem fs = null;
HSSFWorkbook workbook = null;
try {
fs = new NPOIFSFileSystem(inputstream);
workbook = new HSSFWorkbook(fs.getRoot(), true);
//get your data with POI
For each row of your excel :
Make a copy of your template :
find it :
getSearchService().query(searchParameters)
copy it :
getFileFolderService().copy(sourceNodeRef, targetParentRef, newName)
Do transformations of your new word content (Find occurrences and replace with poi library).
Update the content of your new file :
ContentWriter writerDoc = getContentService().getWriter(document.getNodeRef(), ContentModel.PROP_CONTENT,
true);
writerDoc.putContent(file/inputStream);
In your context file, declare you action :
<bean id="my-action" class="x.y.z.MyAction" parent="action-executer">
<property name="searchService">
<ref bean="searchService" />
</property>
<property name="nodeService">
<ref bean="nodeService" />
</property>
<property name="contentService">
<ref bean="contentService" />
</property>
<property name="fileFolderService">
<ref bean="FileFolderService" />
</property>
....
</bean>
In Share, assign to a folder a rule with the action you have created.

Parameters passed from nant to a <script> method

How do you pass a parameter to a method from nant? The nant method can take a project as parameter why not take any other type parameter?
http://nant.sourceforge.net/release/0.85/help/tasks/script.html
The example give in the question takes zero arguments.
Month name in NAnt
<property name="build.date" value="${datetime::parse('2014-07-29 10:21:02')}" />
<property name="build.month" value="${utils::GetMonth(${build.date})}}" />
[Function("GetMonth")]
public static string GetMonth(DateTime date)
{
return date.ToLongDateString().Split(new Char[]{' '})[1];
}
You should avoid the second pair of curly braces, like this:
<property name="build.month" value="${utils::GetMonth(build.date)}" />
In case there's a problem passing DateTime, you can try switching to string parameter instead and parse it the proper way in the C# code.

HTML escape with Spring MVC and Jackson Mapper

I am going to escape HTML in Spring MVC with Jackson Mapper to avoid XSS attack. I search for escaping with Jackson alone and how to config Jackson in Spring. I tried to export json with text like "<" ">", I expected it to escape them to < and >. For example, I added some text enclosed with "bold tag" <b>, I expected to see plain bold tag text in the front end html but it ended up so that the text is shown in bold style in the front end html page.
Below is my approach. I don't know why it didn't work out.
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
this.getJsonFactory().setCharacterEscapes(new CustomCharacterEscapes());
}
}
public class CustomCharacterEscapes extends CharacterEscapes {
private final int[] asciiEscapes;
public CustomCharacterEscapes() {
int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
esc['<'] = CharacterEscapes.ESCAPE_STANDARD;
esc['>'] = CharacterEscapes.ESCAPE_STANDARD;
esc['&'] = CharacterEscapes.ESCAPE_STANDARD;
esc['\''] = CharacterEscapes.ESCAPE_STANDARD;
asciiEscapes = esc;
}
#Override
public int[] getEscapeCodesForAscii() {
return asciiEscapes;
}
#Override
public SerializableString getEscapeSequence(int ch) {
return null;
}
}
Here is the Spring Bean configuration:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<array>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<bean class="x.y.z.CustomObjectMapper" />
</property>
</bean>
</array>
</property>
</bean>
I have never tried to write my own HttpMessageConverter, but I did find this posting that seems pretty relevant to what you want to do. In looking at their solution vs. what you posted here, I can say the biggest differences I noticed was that you did not seem to implement/override the following:
protected boolean supports(Class<?> clazz), which indicates which class type you are supporting (I would recon in your case this would be Object or Serializable if you want it to be generic enough to handle every possibility, or some class specific to your domain objects)
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage), looks like it's used for the request-side
protected void writeInternal(Object t, HttpOutputMessage outputMessage), which looks like it's used for the response-side
Another approach might be to simple create a custom Jackson serializer in conjunction with #ResponseBody. Or, better yet, if you have a value that is user-driven, and your storing it in a database, escape the values prior to insertion. That way you don't need to do anything at all, and the value(s) in question would be "safe" from end-to-end. If you wanted to get crazy-fancy, you could write a custom java.beans.PropertyEditor that escapes Strings for HTML and plug that into the mix using the InitBinder.
Finally, I would like to recommend that, instead of trying to replace the characters on your own, you use something like Apache Commons-Lang's StringEscapeUtils to escape the values.

Writing SQL queries in XML

http://www.codeproject.com/Articles/11178/Writing-SQL-queries-in-XML-A-support-intensive-app
ASP.NET - Storing SQL Queries in Global Resource File?
I want to do something like the above link...but it is not working for me..
I have dynamic sql in my project which i want to move to xml. Can some one please help?
I really hope that you saying you want to store "SELECT BookingID from BOOKING WHERE BOOKINGDATE >= {0}" doesn't mean you are planning on writing:
String.Format(query, parameter)
That's a huge security vulnerability.
Edit:
If you really want to go down this route I would suggest Xml like:
<queries>
<query id="getBookingId">
<parameters>
<parameter name="bookingDate" />
</parameters>
<statement>
<!--
SELECT BookingID from BOOKING WHERE BOOKINGDATE >= #bookingDate
-->
</statement>
</query>
</queries>
Then you can have a class:
[XmlElement("query")]
public sealed class Query
{
[XmlAttribute("id")]
public string Id { get; set; }
// other elements/collections
}
You can then deserialize your Xml into a collection of these Query objects. I would recommend doing this once and storing it in an IDictionary somewhere to avoid repeatedly processing an Xml file.
You then have everything you need in each Query object. A collection of parameters and the sql statement - note that you'll have to manually strip the comment characters () out of the statement before using. Again, probably best to do this once at the beginning.

Many-to-one relation exception due to closed session after loading

I am using NHibernate (version 1.2.1) for the first time so I wrote a simple test application (an ASP.NET project) that uses it. In my database I have two tables: Persons and Categories. Each person gets one category, seems easy enough.
| Persons | | Categories |
|--------------| |--------------|
| Id (PK) | | Id (PK) |
| Firstname | | CategoryName |
| Lastname | | CreatedTime |
| CategoryId | | UpdatedTime |
| CreatedTime | | Deleted |
| UpdatedTime |
| Deleted |
The Id, CreatedTime, UpdatedTime and Deleted attributes are a convention I use in all my tables, so I have tried to bring this fact into an additional abstraction layer. I have a project DatabaseFramework which has three important classes:
Entity: an abstract class that defines these four properties. All 'entity objects' (in this case Person and Category) must inherit Entity.
IEntityManager: a generic interface (type parameter as Entity) that defines methods like Load, Insert, Update, etc.
NHibernateEntityManager: an implementation of this interface using NHibernate to do the loading, saving, etc.
Now, the Person and Category classes are straightforward, they just define the attributes of the tables of course (keeping in mind that four of them are in the base Entity class).
Since the Persons table is related to the Categories table via the CategoryId attribute, the Person class has a Category property that holds the related category. However, in my webpage, I will also need the name of this category (CategoryName), for databinding purposes for example. So I created an additional property CategoryName that returns the CategoryName property of the current Category property, or an empty string if the Category is null:
Namespace Database
Public Class Person
Inherits DatabaseFramework.Entity
Public Overridable Property Firstname As String
Public Overridable Property Lastname As String
Public Overridable Property Category As Category
Public Overridable ReadOnly Property CategoryName As String
Get
Return If(Me.Category Is Nothing, _
String.Empty, _
Me.Category.CategoryName)
End Get
End Property
End Class
End Namespace
I am mapping the Person class using this mapping file. The many-to-one relation was suggested by Yads in another thread:
<id name="Id" column="Id" type="int" unsaved-value="0">
<generator class="identity" />
</id>
<property name="CreatedTime" type="DateTime" not-null="true" />
<property name="UpdatedTime" type="DateTime" not-null="true" />
<property name="Deleted" type="Boolean" not-null="true" />
<property name="Firstname" type="String" />
<property name="Lastname" type="String" />
<many-to-one name="Category" column="CategoryId" class="NHibernateWebTest.Database.Category, NHibernateWebTest" />
(I can't get it to show the root node, this forum hides it, I don't know how to escape the html-like tags...)
The final important detail is the Load method of the NHibernateEntityManager implementation. (This is in C# as it's in a different project, sorry about that).
I simply open a new ISession (ISessionFactory.OpenSession) in the GetSession method and then use that to fill an EntityCollection(Of TEntity) which is just a collection inheriting System.Collections.ObjectModel.Collection(Of T).
public virtual EntityCollection< TEntity > Load()
{
using (ISession session = this.GetSession())
{
var entities = session
.CreateCriteria(typeof (TEntity))
.Add(Expression.Eq("Deleted", false))
.List< TEntity >();
return new EntityCollection< TEntity >(entities);
}
}
(Again, I can't get it to format the code correctly, it hides the generic type parameters, probably because it reads the angled symbols as a HTML tag..? If you know how to let me do that, let me know!)
Now, the idea of this Load method is that I get a fully functional collection of Persons, all their properties set to the correct values (including the Category property, and thus, the CategoryName property should return the correct name).
However, it seems that is not the case. When I try to data-bind the result of this Load method to a GridView in ASP.NET, it tells me this:
Property accessor 'CategoryName' on object 'NHibernateWebTest.Database.Person' threw the following exception:'Could not initialize proxy - the owning Session was closed.'
The exception occurs on the DataBind method call here:
public virtual void LoadGrid()
{
if (this.Grid == null) return;
this.Grid.DataSource = this.Manager.Load();
this.Grid.DataBind();
}
Well, of course the session is closed, I closed it via the using block. Isn't that the correct approach, should I keep the session open? And for how long? Can I close it after the DataBind method has been run?
In each case, I'd really like my Load method to just return a functional collection of items. It seems to me that it is now only getting the Category when it is required (eg, when the GridView wants to read the CategoryName, which wants to read the Category property), but at that time the session is closed. Is that reasoning correct?
How do I stop this behavior? Or shouldn't I? And what should I do otherwise?
Thanks!
Setting lazy loading = false in your mapping will solve the error. It would be a better practice though to tell NHibernate in your load query that you want to fetch the child collection of categories eagerly.
For a criteia query something like .SetFetchMode("Categories", FetchMode.Eager) should work.
Here is a link that gives some insight into the so called "n + 1" problem, how lazy loading relates to it, and how NHibernate is meant to be used.
HTH,
Berryl
something like this:
var entities = session
.CreateCriteria<TEntity>()
.SetFetchMode("Categories", FetchMode.Eager)
.Add(Expression.Eq("Deleted", false))
.List< TEntity >();
The problem is that when your entity is lazy loaded. The query only gets the items that it currently needs. So in your case it gets the Person object. Then when you access any linked entities, it fires off another query. It uses proxy objects for this that know about the Session that was used. You are only keeping the Session open for the Load and then you're closing it.
This is actually bad practice in the NHibernate world. You want to keep the session alive for a period known as a unit of work. This gives you a lot of benefits, like caching and lazy loading. Consequently you can disable lazy loading it should work. Although I'd recommend modifying your loader class if at all possiblem

Resources