- Java Spring PropertyPlaceholderConfigurer and how to trim whitespaces/tabs in properties file
- Java Spring PropertyPlaceholderConfigurer and how to trim whitespaces/tabs in properties file
- SpringBoot auto trim spaces in the @RequestParam list if there is only 1 parameter is provided
- How to trim white spaces from char fields pojo using hibernate and Legacy database
- Disable trimming of whitespace from path variables in Spring 3.2
- The problem
- Solution
- how to read property name with spaces in java
- 4 Answers 4
- Can Java properties file have space?
- How do I add a space to a property file?
- Where is the Java properties file?
- How read .properties file in Java?
- What are properties of a file?
- Where should I put properties file in Java?
- How to create a properties file in Java?
- How to load properties file in Java classpath?
- Spaces in JAVA_OPTS in Apache Tomcat
Java Spring PropertyPlaceholderConfigurer and how to trim whitespaces/tabs in properties file
PS.I am using Spring support for hibernate dao support. Thanks Solution 1: you can try this instruction inside your mehtod to auto trimming space in your list Solution 2: You can simply make your call like that, Since the values are comma-separated, Spring Controller will interpret them as two different values of the by default.
Java Spring PropertyPlaceholderConfigurer and how to trim whitespaces/tabs in properties file
I have a property file which is managed in classic way by propertyplaceholderconfigurer :
The problem that i have a lots of String properties in .properties file, around 30 entries, and if someone adds a tabulation at the end of property value, the application fails to use correctly these properties. I would like to trim each property value before using it. I can do it manually using .trim() on each property in the DataPathUtils class, but i am wondering if there are any other ways to do this, either by PropertyPlaceholderConfigurer either .
- I think the way your data is entered which has trailing spaces needs to be addressed.
- If the source cannot be controlled then you would need to extend PropertyPlaceholderConfigurer and trim it processProperties(). Using this approach you can change things in future as per requirement like getting data from database or changing a particular key value pair or caching.
public class CustomPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer < /** * Map that hold all the properties. */ private MappropertiesMap; /** * Iterate through all the Propery keys and build a Map, resolve all the nested values before beuilding the map. */ @Override protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException < super.processProperties(beanFactory, props); propertiesMap = new HashMap(); for (Object key : props.keySet()) < String keyStr = key.toString(); String valueStr = prop.getProperty(keyStr); propertiesMap.put(keyStr.trim(), valueStr.trim()); >> public String getProperty(String name)
Spring Controller Advice to Trim JSON Data, Add a comment. -1. Try this, Create a class. Annotate the class with @JsonComponent extend the JsonDeserializer and, add your trimming logic in the overridden method, this will automatically trim the whitespaces in the json request, when it hits the controller, no external properties needed to activate this.
SpringBoot auto trim spaces in the @RequestParam list if there is only 1 parameter is provided
I have a REST API which supports filtering by multiple values:
@GetMapping("/employees") public ResponseEntity> getAllEmployees( @RequestParam(name = "role", required = false) List roles)
Call this API this provided information: /employees?role= ADMIN then List roles will have 1 element:
But when I call this API with multiple roles: /employees?role= ADMIN&role=STUDENT then roles will have 2 elements:
How can I avoid this auto-trimming spaces here?
you can try this instruction inside your mehtod to auto trimming space in your list
List rolesWithoutSpaces = roles.stream().map(String::trim).collect(Collectors.toList());
You can simply make your call like that,
/employees?role= ADMIN,STUDENT
Since the values are comma-separated, Spring Controller will interpret them as two different values of the List roles by default.
If you then print them inside your controller, you will see that any blank space is auto-trimmed.
Did that for (String s : roles) System.out.println(«Role :» + s); inside the controller and my logs are,
Properties with Spring and Spring Boot, As of Spring Boot 2.3, we can also specify wildcard locations for configuration files. For example, we can set the spring.config.location property to config/*/: java -jar app.jar —spring.config.location=config/*/ This way, Spring Boot will look for configuration files matching the config/*/ directory pattern outside of …
How to trim white spaces from char fields pojo using hibernate and Legacy database
My table has column as char(5) and can not change it to varchar(5). So when I fetch values out from the table using hibernateTemplate , that returns added spaces with actual say single alphabet value.(A custome fix is to use .trim() method with checking NPE) but do we have a provided approach to handle this kind of situation. PS.I am using Spring support for hibernate dao support. (In SQL, the CHAR data type is a fixed length character string. By definition, the additional characters are padded wtih spaces.)
One way of avoiding explicit call to trim() is you can provide a lifecycle method using a @PostLoad annotation n your Enitity. eg:
@PostLoad protected void trim() < if(stringAttr!=null)< stringAttr=stringAttr.trim(); >>
I have referred discussion on similar question here
Of the suggested solutions I feel adding user type best suites the requirements and makes more sense because 1. @postload (Or actually lifecycle methods) does not work with using SessionFactory with hibernate. 2. Modification in assessor could be ignored during code refractor and another developer may overlook the setters which may lead to overwriting the setter.
So I am using following solution. 1.Have one package-info.java :- This has details for typedefs being used. 2.Annotated the fields with @Type(type=»MyTrimTypeString») 3.Defined a user type class MyTrimTypeString, Code for which followed reply by StepherSwensen with a slight update on nullSafeGet looks like
@Override public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException
and nullSafeSet looks like :
@Override public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException
Java Spring PropertyPlaceholderConfigurer and how to, The problem that i have a lots of String properties in .properties file, around 30 entries, and if someone adds a tabulation at the end of property value, the application fails to use correctly these properties. I would like to trim each property value before using it.
Disable trimming of whitespace from path variables in Spring 3.2
By default, Spring trims leading/trailing whitespace from strings used as path variables. I’ve tracked this down to be because the trimTokens flag is set to true by default in AntPathMatcher .
What I can’t figure out, though, is how to set that flag to false .
Providing my own RequestMappingHandlerMapping bean using an AntPathMatcher where I set it to false didn’t work.
How do I change this flag using JavaConfig?
Let your configuration extend WebMvcConfigurationSupport override requestMappingHandlerMapping() and configure accordingly.
@Configuration public MyConfig extends WebMvcConfigurationSupport < @Bean public PathMatcher pathMatcher() < // Your AntPathMatcher here. >@Bean public RequestMappingHandlerMapping requestMappingHandlerMapping() < RequestMappingHandlerMapping rmhm = super.requestMappingHandlerMapping(); rmhm.setPathMatcher(pathMatcher()); return rmhm; >>
The problem
Just like you pointed out the issue is because all versions of the Spring Framework before 4.3.0 have the default antpathmatcher with the trimTokens flag is set to true.
Solution
Add a config file that returns the default antpathmatcher but with the trimTokens flag set to false
@Configuration @EnableAspectJAutoProxy public class PricingConfig extends WebMvcConfigurerAdapter < @Bean public PathMatcher pathMatcher() < AntPathMatcher pathMatcher = new AntPathMatcher(); pathMatcher.setTrimTokens(false); return pathMatcher; >@Override public void configurePathMatch(PathMatchConfigurer configurer) < configurer.setPathMatcher(pathMatcher()); >>
Spring — javax validation size trim whitespace, At first Spring will use setter-method to set value of property. And for validate value Spring will get it with getter-method. That means, you can trim value in setter-method for prepare it to validation: public class User < @NotBlank @Size (min = 2) private String name; public void setName (String value) < …
how to read property name with spaces in java
If the property name has spaces, it is only returning the first word.. Can any one please tell me how to do this?
You could read the file yourself, messy, but it would over come the issue with how Properties translates each line
4 Answers 4
You can escape the spaces in your properties file, but I think it will start to look pretty ugly.
username=a password=b Parent\ file\ name=c Child\ file\ name=d
You might be better of writing your own implementation with split() or indexOf() or whatever your heart desires to avoid any future bugs and/or headaches.
the java.util.Properties.load() method has a few built in separators, including =, space, : If you want to use any of these in a property name, you need to escape it with a \ character. It’s unfortunate that the javadocs don’t really mention this, but the documentation in apache commons-config while not explicity for this method does apply (at least in terms of property/value delimiter) commons.apache.org/configuration/apidocs/org/apache/commons/…
One semi random addition: when using properties files take great care to avoid unintended whitespace at the end of the property! Although the whitespace surrounding the ‘=’ is ignored, the whitespace at the end isn’t and can cause hair-pulling bugs.
In Java.util.Properties , = , : , or white space character are key/value delimiter when load from property file.
Below are detailed Javadoc of its public void load(Reader reader)
Can Java properties file have space?
You can escape every thing in properties file with Java Unicode: for = for whitespace.
How do I add a space to a property file?
‘\\’ – add escape character. ‘\ ‘ – add space in a key or at the start of a value.
How write properties file in Java?
You can do it in following way:
- Set the properties first in the Properties object by using object. setProperty(String obj1, String obj2) .
- Then write it to your File by passing a FileOutputStream to properties_object. store(FileOutputStream, String) .
What is a property file in Java?
properties is a file extension for files mainly used in Java-related technologies to store the configurable parameters of an application. They can also be used for storing strings for Internationalization and localization; these are known as Property Resource Bundles.
Where is the Java properties file?
resource folder
properties file inside your resource folder of the java project. The extension we use for the properties file is . properties.
How read .properties file in Java?
How do you create a properties file?
Create a properties file Right-click and select Add New Properties File. A new properties file will be added to your project. The new file will be selected and highlighted in the list. Type a name for your properties file, for example, “Properties”.
How do you read a properties file?
What are properties of a file?
When dealing with files, file properties are pieces of information about that file, which can be accessed via a menu item (often called “Properties”). For example, in Microsoft Windows, you can access the properties of a file by right-clicking the file name and selecting Properties.
Where should I put properties file in Java?
properties file inside your resource folder of the java project. The extension we use for the properties file is . properties.
How do I set system properties in java?
Programmatically, a system property can be set using the setProperty method of the System object, and also via the setProperty method of the Properties object that can be obtained from System via getProperties.
What is Property class java?
Properties is a subclass of Hashtable. It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file. Properties class can specify other properties list as it’s the default.
How to create a properties file in Java?
How to load properties file in Java classpath?
How does the properties class work in Java?
What does the java.util.properties object do?
Spaces in JAVA_OPTS in Apache Tomcat
I actually figured this out using AWS Elasticbeanstalk, which lets you have spaces in the Environment Properties you can enter via the UI.
As part of the build of the server instance, the Elasticbeanstalk service replaces the /usr/bin/tomcat7 script in order to accommodate some of its requirements.
If you check this, you can see the following difference:
if [ "$1" = "start" ]; then $ $JAVA_OPTS $CATALINA_OPTS \
if [ "$1" = "start" ]; then eval "$ $JAVA_OPTS $CATALINA_OPTS \ . "
ie they have placed an «eval» before the command to start the JVM, and enclosed the entire command in double-quotes.
This appears to allow the JAVA_OPTS values with spaces be preserved.
Seems to me there is no way to use spaces in JAVA_OPTS, I have the same problem on OSX. You can add your property directly to other -D options in the catalina.sh
Let’s open file $CATALINA_HOME\bin\catalina.sh . You will see the guide from Apache Tomcat for variable JAVA_OPTS
# JAVA_OPTS (Optional) Java runtime options used when any command # is executed. # Include here and not in CATALINA_OPTS all options, that # should be used by Tomcat and also by the stop process, # the version command etc. # Most options should go into CATALINA_OPTS.
You want set property -Dmy.property=»How are you» , it is not a property that JVM supported. You should put it in variable CATALINA_OPTS . If your property’s value has space(s), wrap it inside » » .
# CATALINA_OPTS (Optional) Java runtime options used when the "start", # "run" or "debug" command is executed. # Include here and not in JAVA_OPTS all options, that should # only be used by Tomcat itself, not by the stop process, # the version command etc. # Examples are heap size, GC logging, JMX ports etc.
(Although you used Apache Tomcat 5.5, I quoted guide from Apache Tomcat 9.0.11 because it is existing in my computer)