spring validator without using properties file for show error messages - spring-mvc

I want configuration for show error messages on jsp using spring validator,but without using this configuration for message.properties.
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>message</value>
</list>
</property>
</bean>

error.rejectValue(String field,
String errorCode,
Object[] errorArgs,
String defaultMessage)
Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.
The field name may be null or empty String to indicate the current object itself rather than a field of it. This may result in a corresponding field error within the nested object graph or a global error if the current object is the top object.
Parameters:
field - the field name (may be null or empty String)
errorCode - error code, interpretable as a message key
errorArgs - error arguments, for argument binding via MessageFormat (can be null)
defaultMessage - fallback default message
reference link

Use
error.rejectvalue with three parameters("name of path variable" , "any name" , "message you want to show");
just like
error.rejectvalue("Name", "msg.name", "please enter name");

Related

Spring MVC #RequestParam - empty List vs null

By default Spring MVC assumes #RequestParam to be required. Consider this method (in Kotlin):
fun myMethod(#RequestParam list: List<String>) { ... }
When passing empty list from javaScript, we would call something like:
$.post("myMethod", {list: []}, ...)
In this case however, as the list is empty, there is no way to serialize empty list, so the parameter essentially disappears and so the condition on required parameter is not satisfied. One is forced to use the required: false on the #RequestParam annotation. That is not nice, because we will never receive the empty list, but null.
Is there a way to force Spring MVC always assume empty lists in such case instead of being null?
To get Spring to give you an empty list instead of null, you set the default value to be an empty string:
#RequestParam(required = false, defaultValue = "")
This can be managed in the serialization with ObjectMapper. If you are using jackson in your spring MVC, you can do either the following.
1) Configure your object mapper:
objectMapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS, false);
2) Or if you are using beans via xml config:
<bean name="objectMapper" class="org.springframework.http.converter.json.JacksonObjectMapperFactoryBean" autowire="no">
<property name="featuresToDisable">
<list>
<value type="org.codehaus.jackson.map.SerializationConfig.Feature">WRITE_EMPTY_JSON_ARRAYS</value>
</list>
</property>
</bean>
You can try a WebDataBinder in your controller.
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(List.class, "list", new CustomCollectionEditor( List.class, true));
}
Tried this?
fun myMethod(#RequestParam list: List<String> = listOf()) { ... }

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.

Apache Tiles : change template page at runtime

I have a question : suppose that in a spring MVC 3.0 enviroment i manage Views with Tiles : I have a xml file with definitions of all views. Every view extends a specific template. I have two templates : one for rendering a completeDOM () and one for partialDOM (.....).The problem is, there are some views that can be retrieved in fullDOM and also in partialDOM, but i don't want to write two similars definitions.
I was thinking to a dynamic approach : inject the template of a view at runtime, specifying an http parameter which should contains the name of the template. If the request contains the parameter, than Tiles should override the template exteded by the view, with the template detected by http parameter value.
Some suggestions?
I know this is an old question but I had needed to do this very thing so I thought I'd share my solution.
Tiles allows what they refer to as "runtime composition", which lets you modify definitions. So you can reuse an existing definition and just swap the template:
<tiles:insertDefinition name="existingDefinition" template="alternateTemplate.jsp" />
In spring tilesConfigurer you need to set mutable container:
<property name="useMutableTilesContainer" value="true"/>
<property name="checkRefresh" value="true"/>
And in your Spring Controller:
ModelAndView model = new ModelAndView();
MutableTilesContainer container = (MutableTilesContainer)ServletUtil.getContainer(request.getSession().getServletContext());
Attribute attribute = new Attribute("your template jsp");
HashMap<String, Attribute> attributes = new HashMap<String, Attribute>();
attributes.put("body", attribute);
Definition definition = new Definition("your definition name", "your jsp", attributes);
definition.setExtends("your definition template name");
definition = PatternUtil.replacePlaceholders(definition, "your definition name", new Object());
container.register(definition, request, response);
model.setViewName("your definition name");
I think a view preparer might help:
http://tiles.apache.org/framework/tutorial/advanced/preparer.html

Why does Hibernate Validator #NotEmpty produce duplicate messages?

While working with Hibernate Validator, I noticed that the #NotEmpty and #NotNull annotations produce duplicate messages in the InvalidValue array returned by getInvalidValues(...).
If I specify a message like #NotEmpty(message = "My error message."), then I'll get one InvalidValue of "My error message." and a second of "may not be null or empty"
If i don't include a message (eg #NotEmpty by itself), then I get two copies of the InvalidValue with a message field of "may not be null or empty".
Why does Hibernate Validator do this?? Shouldn't I get one message, either the value that I override using the parameter, or the default message, but not both??
For some more context:
I am extending ClassValidator<T> with my own ClassValidator<MyClass> implementation. I do so to add some custom validations which cannot be done by annotation. I need to see the run time value of more than one property of the class in order to determine the validation.
I get the validations when I call myClassValidator.getInvalidValues(), which I override. Inside my implementation of getInvalidValues() I call super.getInvalidValues() to create the initial error list, and then I add my custom errors to that list. In any case, the call to super.getInvalidValues() contains the duplicate messages, one matching the message property passed into the annotation, and a second with the stock value of the annotation message.
Justin,
I've been working with Hibernate Validator for the last couple of months. While I have not run into the same issue that you've described, I also have not extended ClassValidator. For custom validation, the Hibernate Reference Guide indicates that writing custom constraints is the way to go.
I have been able to use the built-in constraints almost exclusively on my current project. In one case, where I needed to do some very specific calculations on an integer field, I wrote a custom constraint as described in the reference guide; it was a breeze.
Speaking to your specific problem, I wrote a simple test app as a sort of sanity check on my part:
import org.hibernate.validator.*;
public class HibernateValidatorTest {
#NotEmpty
#NotNull
private String validateMe;
public static void main ( String[] args ) {
ClassValidator<HibernateValidatorTest> validator =
new ClassValidator<HibernateValidatorTest>( HibernateValidatorTest.class );
InvalidValue[] inVals =
validator.getInvalidValues( new HibernateValidatorTest() );
for ( InvalidValue inVal : inVals ) {
System.out.println( inVal.getMessage() );
}
}
}
With both Hibernate constraints on the validateMe field, the console output is:
may not be null or empty
may not be null
Removing one or the other has the expected effect of printing only a single message to the console.
I hope this is helpful.
Brian T. Grant

Resources