Deploy Quarkus Microservice with RestClient - java

Anyone knows how to replace the character "/" in application.yaml in Quarkus
# REST Client configuration property
org:
acme:
restclient:
CountriesService/mp-rest/url: https://restcountries.eu/rest
When I deploy, this error seems to appear
Error: release insurance-svc failed, and has been uninstalled due to atomic being set: ConfigMap "insurance-svc-dev-config" is invalid: [data[coreClient/mp-rest/url]: Invalid value: "coreClient/mp-rest/url": a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name', or 'KEY_NAME', or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+'), data[identityClient/mp-rest/scope]: Invalid value: "identityClient/mp-rest/scope": a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name', or 'KEY_NAME', or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+'), data[coreClient/mp-rest/scope]: Invalid value: "coreClient/mp-rest/scope": a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name', or 'KEY_NAME', or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+'), data[identityClient/mp-rest/url]: Invalid value: "identityClient/mp-rest/url": a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name', or 'KEY_NAME', or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+')
Is there any way to change the way it configs without adding whole baseUri into annotation #RegisterRestClient()?

You can use different approach, you can create a custom configuration property to hold the URI. Then create a Factory that reads or has injected this configuration property and is used to instantiate your rest client.
URL apiUrl = new URL("http://localhost:9080/onlineMusicService");
MusicPlaylistService playlistSvc =
RestClientBuilder.newBuilder()
.baseUrl(apiUrl)
.register(PlaylistResponseExceptionMapper.class)
.build(MusicPlaylistService.class);
List<String> playlistNames = playlistSvc.getPlaylistNames();
for (String name : playlistNames) {
List<Song> songs = playlistSvc.getPlaylist(name);
if (hasSongBy(songs, "band name")) {
coolPlaylists.add(name);
}
}
You can read that url from the custom configuration property with the name you want.

I'd recommend watching this pull request: https://github.com/quarkusio/quarkus/pull/17220
Once it is merged and a Quarkus version with it released, you'll be able to use quarkus.rest-client."org.acme.restclient.CountriesService".url=https://restcountries.eu/rest instead - the key does not contain a slash, so it's compatible with Kubernetes

Related

Apostrophe in FeignException shows like /u0027

I have a Feign client which I use to get information from SonarQube and when I'm trying to test request with wrong component name I have an issue with displaying apostrophes as unicode (/u0027).
Here's the test code:
void measuresSearchHistoryUnknownTest() {
assertThatExceptionOfType(FeignException.NotFound.class)
.isThrownBy(() -> sonarFeignClient.measuresSearchHistory(
"badProject",
String.join(",",
EnumUtils.getJsonValue(SonarMetric.BLOCKER_VIOLATIONS),
EnumUtils.getJsonValue(SonarMetric.CRITICAL_VIOLATIONS)
),
1,
10
)).withMessageContaining("Component key 'badProject' not found");
// )).withMessageContaining("Component key \\u0027badProject\\u0027 not found");
}
This test works only if use last line (commented line with "\u0027badProject\u0027"), but it fails if I use previous line (with common apostrophes):
Expecting throwable message:
<"[404] during [GET] to [*******/sonar/api/measures/search_history?component=badProject&metrics=blocker_violations%2Ccritical_violations&p=1&ps=10] [SonarFeignClient#measuresSearchHistory(String,String,int,int)]: [{"errors":[{"msg":"Component key \u0027badProject\u0027 not found"}]}]">
to contain:
<"Component key 'badProject' not found">
but did not.
Throwable that failed the check:
feign.FeignException$NotFound: [404] during [GET] to [*******/sonar/api/measures/search_history?component=badProject&metrics=blocker_violations%2Ccritical_violations&p=1&ps=10] [SonarFeignClient#measuresSearchHistory(String,String,int,int)]: [{"errors":[{"msg":"Component key \u0027badProject\u0027 not found"}]}]
If I look this link in a browser SonarQube shows me JSON with error message and common apostrophes (not unicode), so I think an issue somewhere in Feign.
I use "spring-cloud-starter-openfeign:3.0.1"
Maybe someone can help me with that? How can I prevent parsing of apostrophes to Unicode?

How to read properties with special characters from application.yml in springboot

application.yml
mobile-type:
mobile-codes:
BlackBerry: BBSS
Samsung: SAMS
Samsung+Vodafone: SAMSVV
While reading (Samsung+Vodafone)key from application yml file , we are getting.
concatenated String format as 'SamsungVodafone' .
Morever we heve tried "Samsung'/+'Vodafone": SAMSVV but the result was same and we have tried other symbol such as '-' so its working fine .
For reading key and value from application yml file . we have written below code.
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
#ConfigurationProperties(prefix = "mobile-type")
#Component
public class mobileTypeConfig {
Map<String, String> mobileCodes;
public Map<String, String> getMobileCodes() {
return mobileCodes;
}
public void setMobileCodes(Map<String, String> mobileCodes) {
this.mobileCodes= mobileCodes;
}
}
Note :Spring Boot Version
2.0.6.RELEASE
Use square brackets not to escape any character and encode that in double quotes
mobile-type:
mobile-codes:
BlackBerry: BBSS
Samsung: SAMS
"[Samsung+Vodafone]": SAMSVV
Output
{BlackBerry=BBSS, Samsung=SAMS, Samsung+Vodafone=SAMSVV}
Binding
When binding to Map properties, if the key contains anything other than lowercase alpha-numeric characters or -, you need to use the bracket notation so that the original value is preserved. If the key is not surrounded by [], any characters that are not alpha-numeric or - are removed. For example, consider binding the following properties to a Map:
acme:
map:
"[/key1]": value1
"[/key2]": value2
please keep in mind that the left side is a yml key, not an arbitrary string. my suggestion or your usecase would be to have a map with both on the right side such as:
foo:
- name: "Samsung+Vodafone"
code: "SAMSVV"
- name: "BlackBerry"
code: "BBMS"
- name: "Samsung"
codes:
- "SAMS"
- "SMG"
you will have to change your class structure slightly, but you could actually reconstruct your initial approach from that.

An invalid character[44] was present in the Cookie value

When using Tomcat 8
Getting Error :
java.lang.IllegalArgumentException: An invalid character [44] was present in the Cookie value
at org.apache.tomcat.util.http.Rfc6265CookieProcessor.validateCookieValue(Rfc6265CookieProcessor.java:182)
at org.apache.tomcat.util.http.Rfc6265CookieProcessor.generateHeader(Rfc6265CookieProcessor.java:115)
at org.apache.catalina.connector.Response.generateCookieString(Response.java:986)
at org.apache.catalina.connector.Response.addCookie(Response.java:934)
at org.apache.catalina.connector.ResponseFacade.addCookie(ResponseFacade.java:386)
The character 0x44 is comma character and it is not allowed in cookies:
This string is a sequence of characters excluding semi-colon, comma and white space.
The reference comes from here.
I also had the same error in my project with Tomcat 8 and 9. The easiest but less optimal solution was to change to Tomcat 7, but when this version of Tomcat is deprecated or updated on the server I will have to go find all the commas and replace them in the cookie setting.

Groovy remove beginning of path

I'm trying to delete the beginning of a path that has '\' and ' ' in it. I seem to be getting the some issues saying escape character issue at character 3.
Example:
SomePath: C:\Users\ADMINISTRATOR\App Play\blah\blah
SomePath.replaceFirst('C:\\Users\\ADMINISTRATOR\\App Play\\', '');
Path should be blah\blah
I've tried:
SomePath.replaceFirst("C:\Users\ADMINISTRATOR\App Play\", "");
SomePath.replaceFirst("C:\\Users\\ADMINISTRATOR\\App Play\\", "");
SomePath.replaceFirst("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
SomePath.replaceAll("C:\Users\ADMINISTRATOR\App Play\", "");
SomePath.replaceAll("C:\\Users\\ADMINISTRATOR\\App Play\\", "");
SomePath.replaceAll("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
Just gave it a try... the examples with four backslashes work for me:
def somePath = "C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah"
println somePath
somePath.replaceFirst("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
The problem is that the string needs one escaping \ and since the replaceFirst uses a regexp, the regexp-engine needs another \ to escape the \. The result are four backslashes.
Btw: you can use string operations to get your path, but you could also try file operations like this:
def root= new File("C:\\Users\\ADMINISTRATOR\\App Play\\")
def full= new File("C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah")
def relPath = root.toPath().relativize( full.toPath() ).toFile()
println relPath
(taken from https://gist.github.com/ysb33r/5804364)
You can tackle this problem differently. You could tokenize your input path using \ as a delimiter and then you could pick the last 2 elements (blah and blah) or skip first 4 elements (C:, Users, ADMINISTRATOR, App Play). It depends which assumption is easier to deduct for you. Consider following example:
def somePath = 'C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah'
// Build a new path by accepting the last 2 parts of the initial path
assert 'blah\\blah' == somePath.tokenize('\\')[-2..-1].join('\\')
// Build a new path by skipping the first 4 parts from initial path
assert 'blah\\blah' == somePath.tokenize('\\').drop(4).join('\\')
First option works better if you want only two last parts from the initial path. Second option works better if you can expect final path like blah\blah\blahhhh because you don't know how many nested children initial path contains and you want to start building a new path right after \App Play\ .

Youtube complete Java Regex

I need to parse several pages to get all of their Youtube IDs.
I found many regular expressions on the web, but : the Java ones are not complete (they either give me garbage in addition to the IDs, or they miss some IDs).
The one that I found that seems to be complete is hosted here. But it is written in JavaScript and PHP. Unfortunately I couldn't translate them into JAVA.
Can somebody help me rewrite this PHP regex or the following JavaScript one in Java?
'~
https?:// # Required scheme. Either http or https.
(?:[0-9A-Z-]+\.)? # Optional subdomain.
(?: # Group host alternatives.
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com followed by
\S* # Allow anything up to VIDEO_ID,
[^\w\-\s] # but char before ID is non-ID char.
) # End host alternatives.
([\w\-]{11}) # $1: VIDEO_ID is exactly 11 chars.
(?=[^\w\-]|$) # Assert next char is non-ID or EOS.
(?! # Assert URL is not pre-linked.
[?=&+%\w]* # Allow URL (query) remainder.
(?: # Group pre-linked alternatives.
[\'"][^<>]*> # Either inside a start tag,
| </a> # or inside <a> element text contents.
) # End recognized pre-linked alts.
) # End negative lookahead assertion.
[?=&+%\w]* # Consume any URL (query) remainder.
~ix'
/https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w]*(?:['"][^<>]*>|<\/a>))[?=&+%\w]*/ig;
First of all you need to insert and extra backslash \ foreach backslash in the old regex, else java thinks you escapes some other special characters in the string, which you are not doing.
https?:\\/\\/(?:[0-9A-Z-]+\\.)?(?:youtu\\.be\\/|youtube\\.com\\S*[^\\w\\-\\s])([\\w\\-]{11})(?=[^\\w\\-]|$)(?![?=&+%\\w]*(?:['\"][^<>]*>|<\\/a>))[?=&+%\\w]*
Next when you compile your pattern you need to add the CASE_INSENSITIVE flag. Here's an example:
String pattern = "https?:\\/\\/(?:[0-9A-Z-]+\\.)?(?:youtu\\.be\\/|youtube\\.com\\S*[^\\w\\-\\s])([\\w\\-]{11})(?=[^\\w\\-]|$)(?![?=&+%\\w]*(?:['\"][^<>]*>|<\\/a>))[?=&+%\\w]*";
Pattern compiledPattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = compiledPattern.matcher(link);
while(matcher.find()) {
System.out.println(matcher.group());
}
Marcus above has a good regex, but i found that it doesn't recognize youtube links that have "www" but not "http(s)" in them
for example www.youtube....
i have an update:
^(?:https?:\\/\\/)?(?:[0-9A-Z-]+\\.)?(?:youtu\\.be\\/|youtube\\.com\\S*[^\\w\\-\\s])([\\w\\-]{11})(?=[^\\w\\-]|$)(?![?=&+%\\w]*(?:['\"][^<>]*>|<\\/a>))[?=&+%\\w]*
it's the same except for the start

Categories

Resources