Escaping a | (pipe) in SpEL - spring

I'm hoping there is a very quick simple answer to this, I've read a few other questions on here that reference SpEL and escape sequences, but still haven't succeeded.
I would like to split a property into a list of String using #Value and SpEL. The property will be:
12345|12345|12345
So I need to split on pipe characters, I can do this in Java by using .split(\\|) to successfully escape the pipe character. I have tried with no slashes, 2 slashes and 4 slashes and all are unsuccessful. Is it possible to split on pipes using the following code? My client wants to keep using pipes for whatever reason...
#Value("#{'${list.of.blocked.people}'.split('\\|')}")
private List<String> myBlockedPeopleList;
Thanks.
Here is a link to the question that got me this far, for reference.
Reading a list from properties file and load with Spring annotation value
I also tried looking at the Spring Docs, but I couldn't find any reference to escape pipes in their documentatin.
Spring Documentation on SpEL

Found the answer on a web development forum here.
My solution was to basically give up on trying to escape the pipe character with back-slashes and use the unicode character escaped sequence. If anyone else is trying to pull in a pipe-separated String using #Value, the following code is tested and works with Java 6, Tomcat 6 and Spring 3.
// Reads blockPeopleString delimited with | and splits into List of Strings
#Value("#{'${blockPeopleString}'.split('\\u007c')}")
private List<String> blockPeopleList;

Related

Multiline values in application.yml for spring.cloud.function.definition

We have a Spring boot project using the deprecated #StreamListener and now we are switching to Spring Cloud Stream functional kafka binders.
The problem is that this service connects to multiple kafka topics and our single line spring.cloud.function.definition: topicA;topicB;topicC;...;topicN is becoming very long
I would like to know how to use on Spring's application.yaml the yaml capabilities such as multi line values (such as | or > operators) but I haven't found something similar on documentation.
My goal would be something such as
spring.cloud.function.definition: | topicA;
topicB;
topicC;
...;
topicN
Thanks
There are multiple ways to represent multiline values in YAML. Details could be found in How do I break a string in YAML over multiple lines? and most of them are supported in Spring and could be used in application.yml.
Using multiline for function definitions in Spring Cloud Stream
All above approaches works in Spring but at the end it really depends how the result value is used. In some cases new line character is preserved and in some cases replaced with space.
From what I see spring.cloud.function.definition is parsed in org.springframework.cloud.stream.function.FunctionConfiguration and logic doesn't expect any white spaces.
The only approach that would work in this case is double-quoted block with escaped the newline
spring.cloud.function.definition: "topicA;topicB;topicC;\
...;topicN"

Replacing (escaping) characters in Groovy

For a gradle script, I am composing strings that will be used as command line for a subsequent gradle Test-task. One of the strings is the user's password, which eventually will be passed to the called (exec'ed) "java ..." call using the JVM's -D option, e.g. -Dpassword=foobar.
What complicates things here is, that this password can/should of course contain special characters, that may interfere with the use of the string as command line. In other words: I need to escape special characters (which is OS-specific). :-(
Now to my actual question:
I want to use the String.replaceAll method, i.e. replaceAll(list_of_special characters, EscapeCharacter + Ref_to_matched_character),
e.g. simplified something like replaceAll("[#$%^&]", "^$1")
'^' meaning the escape character and '$1' meaning the matched character here.
Is that possible, i.e. can one refer to the matched pattern in the second argument of replaceAll?
Is that possible, i.e. can one refer to the matched pattern in the second argument of replaceAll?
yes, it's possible
'a#b$c'.replaceAll('([#$%^&])', '^$1')
returns
a^#b^$c
Thanks for the responses and the reviews improving readability. Meanwhile I got my expression working. For those interested:
// handles gthe following: `~!##$%^&*()_+-={}|[]\:;"'<>?,./
escaped = original.replaceAll('[~!##\\$\\%\\^\\&\\*\\(\\)_\\+-={}\\|\\[\\]\\\\:;\"\\\'<>\\?,\\./]', '^$0') // for Windows - cmd.exe

Using a ruby regular expression

I'm completely new to Ruby so I was just wondering if someone could help me out.
I have the following String:
"<planKey><key>OR-J8U</key></planKey>"
What is the regex I have to write to get the center part OR-J8U?
Use the following:
str = "<planKey><key>OR-J8U</key></planKey>"
str[/(?<=\<key\>).*(?=\<\/key\>)/]
#=> "OR-J8U"
This captures anything in between opening and closing 'key' tags using lookahead and lookbehinds
If you want to get the string OR-J8U then you could simply use that string in the regular expression; the - character has to be escaped:
/OR\-J8U/
Though, I believe you want any string that is enclosed within <planKey><key> and </key></planKey>. In that case ice's answer is useful if you allow for an empty string:
/(?<=\<key\>).*(?=\<\/key\>)/
If you don't allow for an empty string, replace the * with +:
/(?<=\<key\>).*(?=\<\/key\>)/
If you prefer a more general approach (any string enclosed within any tags), then I believe the common opinion is not to use a regular expression. Instead consider using an HTML parser. On SO you can find some questions and answers in that regard.

Ajax.oncomplete escaping the singlequote incorrectly

I'm using the Omnifaces ajax.oncomplete function to show a toastr message in my JSF 2 page. The problem I'm facing is that I'm developping a frensh web application and we use a lot of quotes ('). When I add the quote, the browser throws a malformed XML exception :
malformedXML: missing ) after argument list
While I'm using the braqueted slash to make it ignore the quote and treat it as a string :
Ajax.oncomplete("toastr.warning('Vérifier l\'adresse e-mail saisie.')");
Is there a way to pass this exception ?
The \ is also an escape character in Java itself. So, ultimately the \ got stripped off by Java.
You need to double-escape it to represent a literal \, so it arrives as a real \ in JavaScript.
Ajax.oncomplete("toastr.warning('Vérifier l\\'adresse e-mail saisie.')");
Alternatively, if those strings are not hardcoded and thus coming from a dynamic source, and you'd basically thus need to perform automatic escaping, then better use Ajax#data() to automatically let OmniFaces encode the Java variable as a properly formatted JSON object available via OmniFaces.Ajax.data in JavaScript context.
Ajax.data("message", "Vérifier l'adresse e-mail saisie.");
Ajax.oncomplete("toastr.warning(OmniFaces.Ajax.data.message)");
This way you don't need to worry about escaping fuss.

How do I replace carriage returns with <br /> using freemarker and spring?

I've got an internationalised app that uses spring and freemarker. I'm getting content from localised property files using.
${rc.getMessage("help.headings.frequently_asked_questions")}
For some of the content there are carriage returns in the property values. Because I'm displaying in a web page I'd like to replace these with .
What is the best way to do this?
Edit: looking closer it seems that I don't actually have carriage returns in the property files. The properties are coming back as single line strings.
Is there a better way to declare the properties so they know they are multi-line?
help.faq.answer.new_users=If you have not yet set a PIN, please enter your username and passcode (from your token) in the boxes provided and leave the PIN field blank.\
You will be taken through the steps to create a PIN the first time you log in.
Cheers,
Pete
${springMacroRequestContext.getMessage("help.headings.frequently_asked_questions", [], "", false)?html?replace("\n", "<br>")}
To handle CR + LF (carriage return + line feed) line endings, as well as just LF do this:
<#escape x as x?html?replace("\\r?\\n","<br />",'r')>...</#escape>
<#escape x as x?html?replace('\n', '<br>')>...</#escape>
works just fine.
If you want this to be the default behaviour, consider writing a custom TemplateLoader as suggested in this blog: http://watchitlater.com/blog/2011/10/default-html-escape-using-freemarker/.
As to the
Is there a better way to declare the properties so they know they are multi-line?
part of your question, maybe this helps: you can include line terminator characters in your property values by using the \r and \n escape sequences, like it is explained in the API documentation of java.util.Properties#load(java.io.Reader).
I would recommend writing a custom directive for it (see freemarker.template.TemplateDirectiveModel), so in your templates you can write something like <#my.textAsHtml springMacroRequestContext.getMessage(...) />. It's important that this is a directive, not function, so it works properly inside <#escape x as x?html>...</#escape>. Otherwise it would be double-escaped. Using a directive can also give the highest performance, as you can directly send the output to the output Writer, rather than building a String first.

Resources