Hello I have a url string like
http://example.com/foo/?bar=15&oof=myp
Now lets say that I want to change the int value in the bar parameter to 16, in order to have
http://example.com/foo/?bar=16&oof=myp
How can I do this? Considering that the number after the = might be of 1, 2 or ever 3 characters. Thank you
You can use UriComponentsBuilder (it's part of Spring Web jar) like this:
String url = "http://example.com/foo/?bar=15&oof=myp";
UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromUriString(url);
urlBuilder.replaceQueryParam("bar", 107);
String result = urlBuilder.build().toUriString();
Substitute 107 with the number you want. With this method you can have URI or String object from urlBuilder.
Use regex to find the number parameter in the string url
Use String.replace() to replace the old parameter with the new parameter
Related
Need to parse a string having format like this -
"xxx.xxx.xxx.xxx ProxyHost=prod.loacl.com ProxyUser=test ProxyPas=tes#123 ProxyPort=1809".
Need to split or parse in such a manner that I get "prod.loacl.com" "test" "tes#123" "1809" in some strings and if any of parameters is not defined like ProxyPas then it should be null.
We need to ignore the IP addr xxx.xxx.xxx.xxx it will be always concatenated.
Do we have split or use some list to get this done...which is the best possible way to extract this information and why?
Note: Input string can change except ProxyHost parameter, user may not input the ProxyPass etc.
If you assume that format of the input string will not change, you can do something like this:
string inputString = "xxx.xxx.xxx.xxx ProxyHost=prod.loacl.com ProxyUser=test ProxyPas=tes#123 ProxyPort=1809";
string[] eachPart = inputString.Split(" ");
for(int i = 1; i < eachPart.Length; i++) // Skip the IP address
{
string[] partData = eachPart[i].Split("=");
string dataName = partData[0];
string dataValue = partData[1];
// do something with dataName and dataValue
}
However, if input string can change its format you should add some additional logic to this code.
Use regex with groups for this, sample:
var myString = "xxx.xxx.xxx.xxx ProxyHost=prod.loacl.com ProxyUser=test ProxyPas=tes123 ProxyPort=1809";
var regex = new Regex(#"ProxyHost=([^\s]+) ProxyUser=([^\s]+) ProxyPas=([^\s]+) ProxyPort=(\d+)");
var match = regex.Match(myString);
while(match != null && match.Success)
{
int i = 0;
foreach(var group in match.Groups)
{
Console.WriteLine($"Group {i}: Value:'{group}'");
i++;
}
match = match.NextMatch();
}
now you can match the groups to your properties.
One of the possible approaches is to do this Regular Expression:
([^=]+?)\=((\"[^"]+?\")|([^ ]+))
on the whole string. This allows variable input like this:
variable="this has spaces but still is recognized as one"
Problem is that seems like the variable content will be in either 3rd or 4th Group of such match, according to online regex testers, depends on if it has quotes or simply one string - must have more elegant way to do this, but can't come up with any now.
You can check this document to understand more about C#'s regexp groups:
Match.Groups
You will have to deal with null inputs accordingly, when you are putting the content into your C# variable.
I have the following endpoint:
#GetMapping(path = "/{folder}/**")
public void myEndpoint(#PathVariable("folder") String folder,
HttpServletRequest request) {
//...
}
I want to extract the ** as String. The ** can look as follows - /path/to/obj.
I've came up with the following solution:
request.getRequestUri().substring(folder + '/');
However, the SonarQube yells that building the reqular expression should be avoided with tainted, user-controlled data.
refactor this code to not construct the regular expression from tainted user-controlled data
Is there a better, more secure way, to write this extraction?
How about using another #PathVariable?
#GetMapping(path = "/{folder}/{suffix}")
public void myEndpoint(
#PathVariable("folder") String folder,
#PathVariable("suffix") String suffix,
HttpServletRequest request)
{
// ...
}
This is applicable when there are no more slashes (/) present in the request URL.
Otherwise, I am not aware of any other solution. You might want to parse the captured request and validate using java.net.URL.
I came out with the following solution:
int position = request.getRequestUri().lastIndexOf(folder) + folder.length() + 1);
String myPath = request.getRequestUri().substring(position);
I'm calculating the index where my subpath starts. To do that, I'm taking the last index of the root path. It returns me the starting index of the folder String. Then I have to add the length of the String and increase by 1 (stands for slash).
int a=50;
How do I encode this using URLEncoder?
For strings we do
String value=URLEncoder.encoder("SomeStringValye",this.encoding);
Integer numbers in the URL are not an issue. You need not URL encode it.
So in your case, simply construct a url by concatenating as follows
String s = "www.xyz.com/?id=" +1;
If you have some special characters in your url parameter like space, ;, then you have to url encode the parameter value
URLEncoder.encode(
"urlParameterString",
java.nio.charset.StandardCharsets.UTF_8.toString() )
If you still want to pass the integer to the URL encoder method, simply make your integer as a string e.g., 10+""
I need to substract an specific parameter (urlReturn) from a URL like this :
http://somedomain.mx/th=6048000&campus=A&matric=L01425785&serv=GRAD&count=2&per=TEST&passwd=69786e720c0f0e&mount=1000.00&urlReturn=http://somedomain.mx:7003/SP/app/login.xhtml?id=1234&mat=2323&fh=05012014124755&store=TESO
My final string should look like this:
String urlReturn = http://somedomain.mx:7003/SP/app/login.xhtml?id=1234&mat=2323;
And the rest of the string should look like this:
String urlReturn2 = http://somedomain.mx/th=6048000&campus=A&matric=L01425785&serv=GRAD&count=2&per=TEST&passwd=69786e720c0f0e&mount=1000.00&fh=05012014124755&store=TESO
I currently have this :
String string = string.toString().split("\\&")[0];
But the urlReturn parameter should always come as the first one.
Try this (s is your original String):
urlReturn = s.substring(0, s.indexOf("&urlReturn=")).replace("&urlReturn=", "");
urlReturn2 = s.substring(s.indexOf("&urlReturn=")).replace("&urlReturn=", "");
Definitely not elegant at all, but working. I really need some sleep now so take my anser carefully :) You may alswo wanto to check if the parameters is in the String s via the contains method to avoid index out of bounds exceptions.
use string#split
url.split("\\?")[1];
So I'm looking to get the first numbers of an IP. Let's say I have something like 255.35.54.34. I want to get the first part of numbers up until the first period. How would I do this in Java? So it'd leave me with 255.
Take a look at the String class. You can use a couple of methods to accomplish this:
the indexof(...) method will give you the offset of the "."
the substring(...) method will allow you to get a string using the above offset
Or another option is to use the split(...) method to get an array of all four IP values.
As #camickr says, you can use indexOf and substring thus:
String ipAddress = "192.168.1.9";
System.out.println(ipAddress.substring(0, ipAddress.indexOf('.')));
This will print "192"
You can use the split() method with a period as the argument. This will split the string along periods and give you a String[].
Then get the values just as you would from a normal array by using a subscript. In your case index 0 will get you the value
String ip = "255.255.255.255";
String[] splitIP = ip.split(".");
String required = splitIP[0];
You can do it in two ways :
One is that you use String.split() method, and other is to using StringTokenizer class.
Using String.split() :
String ip = "255.1.2.3";
String[] splitIP = ip.split("\\.");
String required = splitIP[0];
System.out.println(required);
Here \\ is required,oherwise it will throw an exception
Using StringTokenizer :
String ip = "255.1.2.3";
StringTokenizer tk=new StringTokenizer(ip,".");
while (tk.hasMoreTokens())
{
System.out.println(tk.nextToken());
break;
}
Hope this will help you..