I have the following piece of code :
public String createDownloadLink(String user) {
String url = "No file exists";
String fileName = "download.zip";
if (userExists())
url = "<a onClick= 'downloadfile(\"" + user + "\", \"" + Encode.forJavaScript(fileName) + "\")' href='#' >Download</a>";
return url;
}
In the above piece of code, the user value is their respective email address.
This code works fine for all email addresses except for email addresses having an apostrophe in it.
Example : For user = "john.d'cruz#java.com" , the url I get in response is
<a onclick="downloadfile("john.d" cruz#java.com", "download.zip")' href="#">Download</a>
And this is a broken url so the download fails.
I tried using
user = user.replace("'","\'");
But it still gives me the same error.
How do I fix this?
If I understand correctly, you just need to escape the ' with a \, right?
If so, your method for escaping the ' sign should look like this instead.
user = user.replace("'","\\'");
Java uses \ for escaping characters, so in your method you were saying ' should be replaced with an escaped ' which basically translates back to the '. Please correct me if I understood the question incorrectly.
For escaping characters you could use:
StringEscapeUtils.escapeJava("john.d'cruz#java.com");
which results in john.d\'cruz#java.com.
Add below dependency to your project:
https://mvnrepository.com/artifact/org.apache.commons/commons-text
and this import statement:
import org.apache.commons.text.StringEscapeUtils;
Something like this should work in your case:
public String createDownloadLink(String user) {
if (userExists()) {
return String.format("<a onClick=\"downloadFile('%s', 'download.zip')\" href=\"#\" >Download</a>", StringEscapeUtils.escapeJava(user));
}
return "No file exists";
}
Related
I have this exception message:
public CityDto getCityByName(String name) throws DataNotFoundException {
CityEntity cityEntity = cityRepository.findByName(name);
if (cityEntity == null){
throw new DataNotFoundException("city with name " + '"' + name + '"' + " not found!");
}else
return CityMapper.INSTANCE.toCityDto(cityEntity);
}
and this how Postman show me this message:
{
"status": "NOT_FOUND",
"message": "Entity not found",
"errors": [
"city with name \"Toronto\" not found!"
]
}
As u can see, city name Toronto for some reason have backslash. How to remove it?
do this throw new DataNotFoundException("city with name '" + name + "' not found!")
Removing backslash is not the issue, basically you need to understand the technical details why the backslash is there.
For this you can visit this Java Strings W3Schools link to understand
as it explains
Because strings must be written within quotes, Java will misunderstand
this string, and generate an error:
String txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape
character.
The backslash (\) escape character turns these characters into
string characters
The sequence \" inserts a double quote in a string
I want to replace particular string values with "XXXX". The issue is the pattern is very dynamic and it won't have a fixed pattern in input data.
My input data
https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme
I need to replace the values of userId and password with "XXXX".
My output should be -
https://internetbanking.abc.co.uk/personal/logon/login/?userId=XXXX&password=XXXX&reme
This is an one off example. There are other cases where only userId and password is present -
userId=12345678&password=stackoverflow&rememberID=
I am using Regex in java to achieve the above, but have not been successful yet. Appreciate any guidance.
[&]([^\\/?&;]{0,})(userId=|password=)=[^&;]+|((?<=\\/)|(?<=\\?)|(?<=;))([^\\/?&;]{0,})(userId=|password=)=[^&]+|(?<=\\?)(userId=|password=)=[^&]+|(userId=|password=)=[^&]+
PS : I am not an expert in Regex. Also, please do let me know if there are any other alternatives to achieve this apart from Regex.
This may cover given both cases.
String maskUserNameAndPassword(String input) {
return input.replaceAll("(userId|password)=[^&]+", "$1=XXXXX");
}
String inputUrl1 =
"https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";
String inputUrl2 =
"userId=12345678&password=stackoverflow&rememberID=";
String input = "https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";
String maskedUrl1 = maskUserNameAndPassword(inputUrl1);
System.out.println("Mask url1: " + maskUserNameAndPassword(inputUrl1));
String maskedUrl2 = maskUserNameAndPassword(inputUrl1);
System.out.println("Mask url2: " + maskUserNameAndPassword(inputUrl2));
Above will result:
Mask url1: https://internetbanking.abc.co.uk/personal/logon/login/?userId=XXXXX&password=XXXXX&reme
Mask url2: userId=XXXXX&password=XXXXX&rememberID=
String url = "https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";
String masked = url.replaceAll("(userId|password)=[^&]+", "$1=XXXX");
See online demo and regex explanation.
Please note, that sending sensitive data via the query string is a big security issue.
I would rather use a URL parser than regex. The below example uses the standard URL class available in java but third party libraries can do it much better.
Function<Map.Entry<String, String>, Map.Entry<String, String>> maskUserPasswordEntries = e ->
(e.getKey().equals("userId") || e.getKey().equals("password")) ? Map.entry(e.getKey(), "XXXX") : e;
Function<List<String>, Map.Entry<String, String>> transformParamsToMap = p ->
Map.entry(p.get(0), p.size() == 1 ? "" : p.get(p.size() - 1));
URL url = new URL("https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme");
String maskedQuery = Stream.of(url.getQuery().split("&"))
.map(s -> List.of(s.split("=")))
.map(transformParamsToMap)
.map(maskUserPasswordEntries).map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("&"));
System.out.println(url.getProtocol() + "://" + url.getAuthority() + url.getPath() + "?" + maskedQuery);
Output:
https://internetbanking.abc.co.uk/personal/logon/login/?userId=XXXX&password=XXXX&reme=
Just use the methods replace/replaceAll from the String class, they support Charset aswell as regex.
String url = "https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";
url = url.replaceAll("(userId=.+?&)", "userId=XXXX&");
url = url.replaceAll("(password=.+?&)", "password=XXXX&");
System.out.println(url);
I'm not a regex expert either, but if you find it useful, I usually use this website to test my expressions and as a online Cheatsheet:
https://regexr.com
Use:
(?<=(\?|&))(userId|password)=(.*?)(?=(&|$))
(?<=(\?|&)) makes sure it’s preceded by ? or & (but not part of the match)
(userId|password)= matches either userId or password, then =
(.*?) matches any char as long as the next instruction cannot be executed
(?=(&|$)) makes sure the next char is either & or end of the string, (but not part of the match)
Then, replace with $2=xxxxx (to keep userId or password) and choose replaceAll.
I'm working on Java with URL and I don't know how to encode the " ' " character.
I don't want to use URLEncoder since it replaces spaces with + and I need %20
private String encoder(String param) {
return param.replaceAll("\\s", "%20").replaceAll("\\'", "%27");
}
This is the code i'm trying but it doesn't work, do you have any ideas on how to replace this " ' " ? Or know another method better than it?
Thank you!!
You don't need to escape ' symbol, just enclose it in double quotes
param.replaceAll("\\s", "%20").replaceAll("'", "%27");
Another way is to use java.net.URLEncoder class to encode URL and replace + symbols to %20
java.net.URLEncoder.encode("URL with spaces'", "UTF-8").replace("+", "%20")
I tried searching for something similar, and couldn't find anything. I'm having difficulty trying to replace a few characters after a specific part in a URL.
Here is the URL: https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
I want to remove the /v/ part, leave the t1.0-9, and also remove the /s130x130/.I cannot just replace s130x130, because those may be different variables. How do I go about doing that?
I have a previous URL where I am using this code:
if (pictureUri.indexOf("&url=") != -1)
{
String replacement = "";
String url = pictureUri.replaceAll("&", "/");
String result = url.replaceAll("().*?(/url=)",
"$1" + replacement + "$2");
String pictureUrl = null;
if (result.startsWith("/url="))
{
pictureUrl = result.replace("/url=", "");
}
}
Can I do something similar with the above URL?
With the regex
/v/|/s\d+x\d+/
replaced with
/
It turns the string from
https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
to
https://scontent-b.xx.fbcdn.net/hphotos-xpf1/t1.0-9/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
as seen here. Is this what you're trying to do?
I am having a string,I want to convert to link,But I am not able to do the same,My code is given below:
Content.append("<a href=\""+System.getProperty("application.middleware.webapplication.host")).append(":")"/"/">);
what about a simple solution like this ?
String host = System.getProperty("application.middleware.webapplication.host");
String url = "http://" + host;
String linkText = "please click here";
Content.append("<a href='"+ url + "'>" + linkText + "</a>" );
The above doesn't compile. If you didn't try to put everything on one line, you would understand why more easily
Start by creating a variable for System.getProperty("..."). Then put one instruction per line. Then don't mix append() and the + concatenation operator. The code becomes:
String host = System.getProperty("application.middleware.webapplication.host");
content.append("<a href=\"");
content.append(host);
content.append(":")"/"/">);
And the last instruction isn't valid. To become valid, and make it a link, you would need something like
String host = System.getProperty("application.middleware.webapplication.host");
content.append("<a href=\"");
content.append(host);
content.append("\">Click here</a>");
Respecting the Java naming conventions (variables start with a lowercase letter) is also crucial in making code readable and understandable.
Content.append("<a href=\"")
.append(System.getProperty("application.middleware.webapplication.host"))
.append("\">My Link</a>");