In JMeter, I used a Regular Expression Extractor to extract part of an HTML response. I then passed that to a BeanShell Post Processor. However, having trouble replacing \x2D to -. Is there a way to do this or perhaps do I need to extract the response as
String yourvar = vars.get("accessToken");
String anotherVar = yourvar.replace("data.access_token = '","");
String finalAccessToken = anotherVar.replace("\x2D","-");
vars.put("finalAccessToken",finalAccessToken);
It is not liking the "\x2D" part. It works if I find \x2D but the original string only has .
You need to escape your target String parameter.
final String finalAccessToken = anotherVar.replace("\\x2D", "-");
If it's not what you're asking for, add more info to the question. That's all what I was able to understand.
It is recommended to use JMeter's built-in test elements where possible. In particular your case you might be interested in __strReplace() custom JMeter Function
Install Custom JMeter Functions bundle using JMeter Plugins Manager
Use the following expression to make the replacement:
${__strReplace(${anotherVar},\\\x2D,-,)}
If you want to go for scripting - make sure to use JSR223 PostProcessor and Groovy language. Be aware that you will still need to escape backslash with another backslash like:
String finalAccessToken = anotherVar.replace("\\x2D","-");
Related
I am in the middle of making a Java application which in particular takes a relative file path of the form
String path = "path/to/Plansystem/Xslt/omraade/../../../Kms/Xslt/Rense/Template.xslt"
and reduce / simplify the path expression, so that it provides an equivalent path, but without the double dots. That is, we should obtain this String:
String result = "path/to/Kms/Xslt/Rense/Template.xslt"
Currently, I have defined the following Regular expression:
String parentDirectory = $/\/(?!\.)([\w,_-]*)\.?([\w,_-]*)\/\.\.\//$
I then replace any match with a single slash. This approach seems to work, and I came up with the expression using Regexr.com, but it seems to me that my approach is a little hacky, and I would be surprised if this specific functionality is not available in some well tested, well developed library. Is anyone familiar with such a library?
Edit:
Based on the responses made by rzwitserloot and Andy Turner I realized that the following methods works for me:
public static String slash = "/"
public static final String backslashes = $/\\+/$
static String normalizePath(String first, String... more) {
String pathToReturn = Paths.get(first, more).normalize().toString().replaceAll(backslashes, slash)
return pathToReturn
}
Note that the replacement I make at the end is only due to a specific need I have, where I want to preserve the unix notation (even when running on Windows).
No, don't bother with regular expressions. There's an API for this!
Basic 'dot' removal:
import java.nio.file.Paths;
Paths.get("/Users/Birdie/../../Users/Birdie/workspace/../workspace").normalize()
Will get you a path representing /Users/Birdie/workspace.
You can go further and follow softlinks, even:
Paths.get("/Users/Birdie/../../Users/Birdie/workspace/../workspace").toRealPath()
Use java.nio.Path:
Path path = Paths.get("path/to/Plansystem/Xslt/omraade/../../../Kms/Xslt/Rense/Template.xslt");
Path normalized = path.normalize();
Now I know about FilenameUtils.getExtension() from apache.
But in my case I'm processing extensions from http(s) urls, so in case I have something like
https://your_url/logo.svg?position=5
this method is gonna return svg?position=5
Is there the best way to handle this situation? I mean without writing this logic by myself.
You can use the URL library from JAVA. It has a lot of utility in this cases. You should do something like this:
String url = "https://your_url/logo.svg?position=5";
URL fileIneed = new URL(url);
Then, you have a lot of getter methods for the "fileIneed" variable. In your case the "getPath()" will retrieve this:
fileIneed.getPath() ---> "/logo.svg"
And then use the Apache library that you are using, and you will have the "svg" String.
FilenameUtils.getExtension(fileIneed.getPath()) ---> "svg"
JAVA URL library docs >>>
https://docs.oracle.com/javase/7/docs/api/java/net/URL.html
If you want a brandname® solution, then consider using the Apache method after stripping off the query string, if it exists:
String url = "https://your_url/logo.svg?position=5";
url = url.replaceAll("\\?.*$", "");
String ext = FilenameUtils.getExtension(url);
System.out.println(ext);
If you want a one-liner which does not even require an external library, then consider this option using String#replaceAll:
String url = "https://your_url/logo.svg?position=5";
String ext = url.replaceAll(".*/[^.]+\\.([^?]+)\\??.*", "$1");
System.out.println(ext);
svg
Here is an explanation of the regex pattern used above:
.*/ match everything up to, and including, the LAST path separator
[^.]+ then match any number of non dots, i.e. match the filename
\. match a dot
([^?]+) match AND capture any non ? character, which is the extension
\??.* match an optional ? followed by the rest of the query string, if present
I have a part of HTML from a website in the below String format:
srcset=" /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#200w.jpg?20170808 200w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#338w.jpg?20170808 338w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#445w.jpg?20170808 445w, tesla_theme/assets/img/homepage/mobile/homepage-models--touch#542w.jpg?20170808 542w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#750w.jpg?20170808 750w"
I want to add http://tesla.com in front of all the urls in the srcset element like http://tesla_theme/assets/img/homepage/mobile/homepage-models--touch#750w.jpg?20170808 750w
I believe this could be done using regex, but I am not sure.
How do I do this using Java if I have multiple srcset elements in a html string variable, and I want to replace all of the srcset url.'s and add the server url in front?
Note: The /tesla_theme will not be consistent, so I cannot use replaceAll, instead, i will have to use regex.
You can simply use String Class replace method as below, It will replace all "/_tesla" in the given String. No special regex required unless you have a kind of pattern instead of "/tesla"
String srcset=" /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#200w.jpg?20170808 200w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#338w.jpg?20170808 338w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#445w.jpg?20170808 445w, tesla_theme/assets/img/homepage/mobile/homepage-models--touch#542w.jpg?20170808 542w, /tesla_theme/assets/img/homepage/mobile/homepage-models--touch#750w.jpg?20170808 750w";
String requiredSrcSet = srcset.replace("/tesla_", "http://tesla_");
In Jmeter Bean shell assertion, I'm storing a returned value to a string. The string is returned with an underline. It is displayed with underline. Though I'm not able to show underline in my below text.
https://myhost.com:1234/abc/def/ghi
I have to parse the above string to use it in http reuquerst. For that I'm using URI/URL class to get hostname , port and path etc; But all these works only after I get rid of underline from the text. How do I get rid of underline.
You can remove underscores within the same Beanshell assertion using String.replaceAll() method like:
String myString = "your_string_with_underscores";
myString = myString.replaceAll("_","");
// do what you need with the "sanitized" string
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more Beanshell tips and tricks.
For the given url like "http://google.com//view/All/builds", i want to replace the double slash with single slash. For example the above url should display as "http://google.com/view/All/builds"
I dint know regular expressions. Can any one help me, how can i achieve this using regular expressions.
To avoid replacing the first // in http:// use the following regex :
String to = from.replaceAll("(?<!http:)//", "/");
PS: if you want to handle https use (?<!(http:|https:))// instead.
Is Regex the right approach?
In case you wanted this solution as part of an exercise to improve your regex skills, then fine. But what is it that you're really trying to achieve? You're probably trying to normalize a URL. Replacing // with / is one aspect of normalizing a URL. But what about other aspects, like removing redundant ./ and collapsing ../ with their parent directories? What about different protocols? What about ///? What about the // at the start? What about /// at the start in case of file:///?
If you want to write a generic, reusable piece of code, using a regular expression is probably not the best appraoch. And it's reinventing the wheel. Instead, consider java.net.URI.normalize().
java.net.URI.normalize()
java.lang.String
String inputUrl = "http://localhost:1234//foo//bar//buzz";
String normalizedUrl = new URI(inputUrl).normalize().toString();
java.net.URL
URL inputUrl = new URL("http://localhost:1234//foo//bar//buzz");
URL normalizedUrl = inputUrl.toURI().normalize().toURL();
java.net.URI
URI inputUri = new URI("http://localhost:1234//foo//bar//buzz");
URI normalizedUri = inputUri.normalize();
Regex
In case you do want to use a regular expression, think of all possibilities. What if, in future, this should also process other protocols, like https, file, ftp, fish, and so on? So, think again, and probably use URI.normalize(). But if you insist on a regular expression, maybe use this one:
String noramlizedUri = uri.replaceAll("(?<!\\w+:/?)//+", "/");
Compared to other solutions, this works with all URLs that look similar to HTTP URLs just with different protocols instead of http, like https, file, ftp and so on, and it will keep the triple-slash /// in case of file:///. But, unlike java.net.URI.normalize(), this does not remove redundant ./, it does not collapse ../ with their parent directories, it does not other aspects of URL normalization that you and I might have forgotten about, and it will not be updated automatically with newer RFCs about URLs, URIs, and such.
String to = from.replaceAll("(?<!(http:|https:))[//]+", "/");
will match two or more slashes.
Here is the regexp:
/(?<=[^:\s])(\/+\/)/g
It finds multiple slashes in url preserving ones after protocol regardless of it.
Handles also protocol relative urls which start from //.
#Test
public void shouldReplaceMultipleSlashes() {
assertEquals("http://google.com/?q=hi", replaceMultipleSlashes("http://google.com///?q=hi"));
assertEquals("https://google.com/?q=hi", replaceMultipleSlashes("https:////google.com//?q=hi"));
assertEquals("//somecdn.com/foo/", replaceMultipleSlashes("//somecdn.com/foo///"));
}
private static String replaceMultipleSlashes(String url) {
return url.replaceAll("(?<=[^:\\s])(\\/+\\/)", "/");
}
Literally means:
(\/+\/) - find group: /+ one or more slashes followed by / slash
(?<=[^:\s]) - which follows the group (*posiive lookbehind) of this (*negated set) [^:\s] that excludes : colon and \s whitespace
g - global search flag
I suggest you simply use String.replace which documentation is http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(java.lang.CharSequence, java.lang.CharSequence)
Something like
`myString.replace("//", "/");
If you want to remove the first occurence:
String[] parts = str.split("//", 2);
str = parts[0] + "//" + parts[1].replaceAll("//", "/");
Which is the simplest way (without regular expression). I don't know the regular expression corresponding, if there is an expert looking at the thread.... ;)