configuration to encode Hibernate Validator customized error messages through Spring Framework - spring-3

I am working with Spring (4.0.5) and Hibernate Validator (5.1.2.Final)
I already have working the error messages through a .properties file, it works too about i18n.
It in a standalone and testing (JUnit) environment, by the moment. I don't want include the Web environment yet to keep the things simple.
I have the following:
For the ValidationMessages_es_PE.properties file (in spanish)
person.salary.digits=Dato invalido '${validatedValue}', máximo tamaño no decimal permitido es {integer}, máximo tamaño decimal permitido es {fraction}
About the infrastructure
#Configuration
public class ValidatorConfiguration {
#Bean
public ResourceBundleMessageSource resourceBundleMessageSource(){
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setDefaultEncoding("UTF-8");
resourceBundleMessageSource.setBasenames("com.manuel.jordan.validation.messages.ValidationMessages");
return resourceBundleMessageSource;
}
#Bean
public LocalValidatorFactoryBean localValidatorFactoryBean(){
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.setValidationMessageSource(resourceBundleMessageSource());
MessageSourceResourceBundleLocator messageSourceResourceBundleLocator = new MessageSourceResourceBundleLocator(resourceBundleMessageSource());
ResourceBundleMessageInterpolator resourceBundleMessageInterpolator = new ResourceBundleMessageInterpolator(messageSourceResourceBundleLocator);
localValidatorFactoryBean.setMessageInterpolator(resourceBundleMessageInterpolator);
return localValidatorFactoryBean;
}
}
Observe I have setDefaultEncoding("UTF-8")
The test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=ValidatorConfiguration.class)
public class InvalidPersonValidation03Test {
private static final Logger logger = LoggerFactory.getLogger(InvalidPersonValidation03Test.class);
#Autowired
private LocalValidatorFactoryBean validator;
public InvalidPersonValidation03Test(){
LocaleContextHolder.setLocale(new Locale("es","PE"));
}
#Test
public void testInvalidNullId(){
...
Part of the output is the following
- >>>testInvalidFractionSalary
- ConstraintViolationImpl{interpolatedMessage='Dato invalido '1578.100', m�ximo tama�o no decimal permitido es 4, m�ximo tama�o decimal permitido es 2', propertyPath=salary, rootBeanClass=class com.manuel.jordan.domain.PersonValidation03, messageTemplate='{person.salary.digits}'}
- ConstraintViolationImpl{interpolatedMessage='Dato invalido '1578.100', m�ximo tama�o no decimal permitido es 4, m�ximo tama�o decimal permitido es 2', propertyPath=salary, rootBeanClass=class com.manuel.jordan.domain.PersonValidation03, messageTemplate='{person.salary.digits}'}
The characters ñ and á are not showing how it is expected
My IDE already has
Preferences -> Workspace -> Text file encoding with UTF-8
What extra missing configuration I need?

You cannot use unicode characters like this in a properties file. See http://docs.oracle.com/javase/8/docs/api/java/util/PropertyResourceBundle.html
In that case, characters that cannot be represented in ISO-8859-1
encoding must be represented by Unicode Escapes as defined in section
3.3 of The Java™ Language Specification...
á would be \u00E1 and ñ \u00F1

For the community
I have read this post
Problem with Java properties utf8 encoding in Eclipse
Therefore consider in use this easy and very useful tool
ResourceBundle Editor
It works for Eclipse and Spring Tool Suite
Problem solved

Related

How to keep generic filepath in #PropertySource annotation for both windows and linux

I have following configuration code in my spring boot application:-
#Configuration
#PropertySources({
#PropertySource(value = "file://${CONFIG_PATH}/folder/application.properties"),
#PropertySource(value = "file://${CONFIG_PATH}/folder/application-log.properties"),
#PropertySource(value = "file://${CONFIG_PATH}/folder/application-persistence.properties"),
#PropertySource(value = "file://${CONFIG_PATH}/folder/application-environment.properties")
})
public class PopulateFixturesConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer
propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Above code executes on Linux Server and I have Windows on local machine. So when I have to do development i have to change, I have to add extra "/" after file like this:
#PropertySource(value = "file:///${CONFIG_PATH}/folder/application-environment.properties")
and again when i have to commit the code i have to remove that extra "/".
Is there any way to keep the path generic for both windows and linux.
Thanks,
If you are using Java greater than Java 7, then you can do like this
String configPath= System.getProperty("CONFIG_PATH");
java.nio.file.Path path = java.nio.file.Paths.get(configPath, "some", "dir", "path1", "path2")
java.nio.file.Path have lot of methods which can give you the absolute path in string
If you are using Java less than Java 7 then use File.separator

GlobalChannelInterceptor pass array of patterns

I am Spring Integration 4.3.13 and trying to pass patterns when configuring #GlobalChannelInterceptor
Here is the example
#Configuration
public class IntegrationConfig{
#Bean
#GlobalChannelInterceptor(patterns = "${spring.channel.interceptor.patterns:*}")
public ChannelInterceptor channelInterceptor(){
return new ChannelInterceptorImpl();
}
}
properties file has following values:
spring.channel.interceptor.patterns=*intchannel, *event
I am using direct channels with names that end with these two string
springintchannel
registrationevent
With the above config, both the channels should have interceptor configured but it is not getting configured.
The comma-separate value isn't support there currently.
I agree that we need to fix it, so feel free to raise a JIRA on the matter and we will file a solution from some other place.
Meanwhile you can do this as a workaround:
#Bean
public GlobalChannelInterceptorWrapper channelInterceptorWrapper(#Value("${spring.channel.interceptor.patterns:*}") String[] patterns) {
GlobalChannelInterceptorWrapper globalChannelInterceptorWrapper = new GlobalChannelInterceptorWrapper(channelInterceptor());
globalChannelInterceptorWrapper.setPatterns(patterns);
return globalChannelInterceptorWrapper;
}

How to write scripts to keep punctuation in Stanford dependency parser

In order to get some specific dependency information I write a java script to parse sentences rather than directly use ParserDemo.java that Stanford Parser 3.9.1 provided. But I found punctuation is missing after got typedDependencies. Is there any function to get punctuation in Stanford Parser?
I had to write a script to parse sentences myself for the reason that I need to create a SemanticGraph from a List of TypedDependencies, in order to use methods in SemanticGraph to get evey single tokens dependent information(include punctuation).
public class ChineseFileTest3 {
public static void main(String[] args){
String modelpath = "edu/stanford/nlp/models/lexparser/xinhuaFactored.ser.gz";
LexicalizedParser lp = LexicalizedParser.loadModel(modelpath);
String textFile = "data/chinese-onesent-unseg-utf8.txt";
demoDP(lp,textFile);
}
public static void demoDP(LexicalizedParser lp, String filename){
for(List<HasWord> sentence : new DocumentPreprocessor(filename)) {
Tree t = lp.apply(sentence);
ChineseGrammaticalStructure gs = new ChineseGrammaticalStructure(t);
Collection<TypedDependency> tdl = gs.typedDependenciesCollapsed();
System.out.println(tdl);
}
}
}
I would suggest not using the parser standalone but instead just running a pipeline. That will maintain the punctuation.
There is comprehensive documentation about using the Java API for pipelines here:
https://stanfordnlp.github.io/CoreNLP/api.html
You need to set the properties for Chinese. A quick way to do that is with this line of code
Properties props = StringUtils.argsToProperties("-props", "StanfordCoreNLP-chinese.properties");

ClassNotFoundException trown when registering Midlet in the PushRegistry

I'm getting an odd error I can't get to the bottom of. When I register the midlet in the Push Registry it throws the ClassNotFoundException. I've used a very standard implementation straight from the API documentation just the url has been altered
// MIDlet class name
String midletClassName = this.getClass().getName();
// Register a static connection.
String url = "sms://:2049";
// Use an unrestricted filter.
String filter = "*";
PushRegistry.registerConnection(url, midletClassName, filter);
this for some reason throws the java.lang.ClassNotFoundException! When I view the JAD it looks ok:
MIDlet-1: AlarmHandler, ,sweoch.test.AlarmHandler
which is the class midletClassName equals at debug. So why is this trowing exceptions?

DSL Add Root Element to Serialization

I am looking for help to achieve the following
The Diagram represents a car, users can add engine and colour
when I view the XML it looks like this:
<Car>
<Engine>BigEngine</Engine>
<Colour>Pink</Colour>
</Car>
What I would like to do is to wrap the car inside 'vehicle', i.e
<Vehicle>
<Car>
<Engine>BigEngine</Engine>
<Colour>Pink</Colour>
</Car>
</Vehicle>
I am not sure of the best way to achieve this. I want the model explorer and the generated XML to be wrapped in 'vehicle' but for all other intents and purposes the user is working with a car only
Info: Visual Studio 2010, C# and DSL SDK for 2010
I would try two different approaches:
1st: override DSL Package class DocData
In DocData.cs file and override method
protected override void OnDocumentSaved(System.EventArgs e)
and then I would create the wrapper
afterwards I'd override in DocData.cs
protected override void OnDocumentLoading(System.EventArgs e)
and before calling the base method base.OnDocumentLoading(e); i would delete from the file.
2nd: Under DSL Explorer go to XML Serialization Behaviour and set Car Domain Class "Is Custom = true".
This solution is not straightforward but it's not as complicated as it seems at the first place. You'll must define every single method but for each custom method you can call a DSL generated method called "DefaulMethod" which has the default DSL serializer behaviour.
I am currently using VS 2005, so some things might have changed...
I have fixed this by the following. I am double deriving the Car class and in the Car serializer I am doing this:
Writing the extra elements:
public partial class CarSerializer : CarSerializerBase
{
public override void Write(SerializationContext serializationContext, ModelElement element, XmlWriter writer, RootElementSettings rootElementSettings)
{
// Adds the Model and LobSystem root elements to match that required by the SharePoint BCS
writer.WriteStartElement("Garage");
writer.WriteStartElement("Cars");
base.Write(serializationContext, element, writer, rootElementSettings);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
To be able to read this back in I am overriding the Car LoadModel method in the SerializationHelper and where it is getting the reader I am reading the elements until I get to Car.
....
XmlReader reader = XmlReader.Create(fileStream, settings);
reader.MoveToContent();
while (!reader.EOF && !reader.Name.Equals("Car"))
{
reader.Read();
}
reader = reader.ReadSubtree();
// using (global::System.Xml.XmlReader reader = global::System.Xml.XmlReader.Create(fileStream, settings))
using (reader)
{
....

Resources