I have integrated oAuth2 (Facebook, LinkedIn, etc) with my XPages app to allow for authentication to easily add comments (response docs). When a user authenticates, it has to redirect to the facebook/linkedin page, then return to complete the document creation. I use the state variable to do this, and pass it in the querystring of the url. When the page reloads and sees the state variable, it calls a "beforePageLoad" event and creates the response document if the user authenticated and has the correct state document.
My problem is when there is already a state parameter in the querystring. I want to replace the value, not add it to the end. I use a solution here from stackOverflow by ellemayo called updateQueryStringParameter. When I call it from my beforePageLoads it runs, but never replaces the parameter, it only appends it to the end. I end up with ...&state=E5A&state=E5F
I have a feeling that it is in the line,
return uri.replace(re, '$1' + key + "=" + value + '$2');
I can write the code using #ReplaceSubstring(), etc, but want to know if there are problems running regex in XPages SSJS. I read on Lotus.com that
A Regular Expression can be specified as Server-side, which uses the
Java (java.util.regex) API or Client-side, which uses the browser
JavaScript Regular Expression Engine. Client-side and Server-side
Regular Expression syntax is similar, but there are differences that a
user must be aware of.
Should I avoid regex in XPages SSJS ? I have it working extensively in client and in some field validations on the XPage itself.
Here is the call to the function:
if(#Contains( qString,"state=")){
qString=updateQueryStringParameter(qString, "state", linkDoc.getNoteID() );
}else{
qString="?"+qString+"&state=" + linkDoc.getNoteID()
}
the function:
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
// I also tried --> if (re.test(uri)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
It was not an XPage or Regex problem. I was using the querystring provided by Domino the excludes the "?" as part of the querystring. when I send "?" + qString to the function, it works. Regex needed to know where to start looking, thus it never found the start of the query string.
Related
I have the following JSR223 PostProcessor where the captured c_QUID value is to be surrounded by curly braces and used in a cookie. For example if c_QUID is 5575-9878-4848-8897, then I need to set the cookie as {5575-9878-4848-8897}. What can I modify in the below script to do that? As of now it does not add the curly braces.
import org.apache.jmeter.protocol.http.control.*
//Get cookie manager
CookieManager cm = sampler.getCookieManager()
log.info("XXXXXXXXXX QUID " + vars.get("c_QUID"));
Cookie c = new Cookie("QUID", vars.get("c_QUID"), "stage.randomtesting.com", "/", true, 1557578515)
cm.add(c);
Use string concatenation the value:
new Cookie("QUID", "{" + vars.get("c_QUID") + "}",
Shouldn't it be something like:
Cookie c = new Cookie("QUID", "{" + vars.get("c_QUID") + "}", "stage.randomtesting.com", "/", true, 1557578515)
By the way, you might want to use current timestamp as the cookie expiration date because your value of 1557578515 is in the past so the application might not accept it, you might want to replace it with something in the future? See Creating and Testing Dates in JMeter - Learn How article for more details
Also wouldn't that be easier just to define the custom cookie in the HTTP Cookie Manager?
I'm retrieving a list of Work Items using the VSTS API and would like to display them on my web app. I can successfully return a list of the work items in the format below:
{"count":1,"value":[{"id":246,"rev":4,"fields":{"System.Id":246,"System.State":"New","System.Title":"test1"},"url":"https://example.visualstudio.com/_apis/wit/workItems/246"}]}
I have tried a regular expression to get the values from this HTTP response with the following code:
HttpResponseMessage getWorkItemsHttpResponse = client.GetAsync("_apis/wit/workitems?ids=" + ids + "&fields=System.Id,System.Title,System.State&asOf=" + workItemQueryResult.asOf + "&api-version=2.2").Result;
if (getWorkItemsHttpResponse.IsSuccessStatusCode)
{
result = getWorkItemsHttpResponse.Content.ReadAsStringAsync().Result;
// Regular expression to extract work item values to display
string parseWI = result.ToString();
var match = Regex.Match(parseWI, "\"System.ID\": (.*)");
workItemsToDisplay = (match.Groups[1].Value);
}
}
}
}
return workItemsToDisplay;
}
This is refusing to return anything though and leaves the textbox I display the workItemsToDisplay in empty. I'm not familiar with regular expressions and i'm sure this is where the issue stems from. Not sure if Microsoft already has sample code to construct a display of Work Items from the response.
Don't use a regex. That's JSON, use a JSON parsing library (JSON.Net is the de facto standard in the .NET world) and then you can easily retrieve specific fields.
I need to send a custom email message to every User of a list ( List < User > ) I have. (I'm using C# .NET)
What I would need to do is to replace all the expressions (that start with "[?&=" have "variableName" in the middle and then ends with "]") with the actual User property value.
So for example if I have a text like this:
"Hello, [?&=Name]. A gift will be sent to [?&=Address], [?&=Zipcode], [?&=Country].
If [?&=Email] is not your email address, please contact us."
I would like to get this for the user:
"Hello, Mary. A gift will be sent to Boulevard Spain 918, 11300, Uruguay.
If marytech#gmail.com is not your email address, please contact us."
Is there a practical and clean way to do this with Regex?
This is a good place to apply regex.
The regular expression you want looks like this /\[\?&=(\w*)\]/ example
You will need to do a replace on the input string using a method that allows you to use a custom function for replacement values. Then inside that function use the first capture value as the Key so to say and pull the correct corresponding value.
Since you did not specify what language you are using I will be nice and give you an example in C# and JS that I made for my own projects just recently.
Pseudo-Code
Loop through matches
Key is in first capture group
Check if replacements dict/obj/db/... has value for the Key
if Yes, return Value
else return ""
C#
email = Regex.Replace(email, #"\[\?&=(\w*)\]",
match => //match contains a Key & Replacements dict has value for that key
match?.Groups[1].Value != null
&& replacements.ContainsKey(match.Groups[1].Value)
? replacements[match.Groups[1].Value]
: "");
JS
var content = text.replace(/\[\?&=(\w*)\]/g,
function (match, p1) {
return replacements[p1] || "";
});
Let's start by saying I have a very large project, part of this project is to grab a user recovery action status, and a user email, and send it through a service layer back to the front end of the application. The catch is, the email needs to be altered on the back end so it doesn't get sent plain text. What I mean by this is, when the value gets populated on the back end, I need to have some code to modify it so it will have a format like this: j*****e#domain.com. This absolutely needs to be done in the method that I'm working on(which honestly isn't very big). Here is the method I have that will grab the status from another method within the same class, as well as grabbing the email of the user:
public CredentialRecoveryResponse RecoveryResponse(CredentialRecoveryRequest request)
{
CredentialRecoveryResponse response = new CredentialRecoveryResponse();
response.Status = RecoverCredentials(request);
if (response.Status == UserRecoveryActionStatus.Success)
{
User usr = UserRepository.GetByID(request.UserID);
response.Email = usr.EmailAddress;
}
return response;
}
Somehow, inside this method, I need to take that usr.EmailAddress and modify it do "block" or change the values to "*" for all characters except the first and last characters before the "#domain.com" portion. Is there a quick and easy way to do this within the method that way the whole email address isn't getting sent back through the wire?
Here's one take:
private static string ObfuscateEmail(string email)
{
return Regex.Replace(email, "^(?<name>[^#]+)", m => {
string match = m.Groups["name"].Value;
return match[0] + new String('*', match.Length - 1);
});
}
What is this doing?
The method uses Regex.Replace and passes a lambda function to do the actual replacement
The regex pattern simply says match everything to the left of the # sign and create a named group called 'name'.
The lambda function then takes the first character of the match and appends to it a series of asterisks, using an overload of the String method (char, int) which repeats that char N number of times. It's N-1 here since the first char is unobfuscated.
I have a URL validation method which works pretty well except that this url passes: "http://". I would like to ensure that the user has entered a complete url like: "http://www.stackoverflow.com".
Here is the pattern I'm currently using:
"^(https?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+#)?" //user#
+ #"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184
+ "|" // allows either IP or domain
+ #"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www.
+ #"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain
+ "[a-z]{2,6})" // first level domain- .com or .museum
+ "(:[0-9]{1,4})?" // port number- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:#&=+$,%#-]+)+/?)$"
Any help to change the above to ensure that the user enters a complete and valid url would be greatly appreciated.
Why not use a urlparsing library? Let me list out some preexisting url parsing libraries for languages:
Python: http://docs.python.org/library/urlparse.html
Perl: http://search.cpan.org/dist/URI/URI/Split.pm
Ruby: http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/uri/rdoc/classes/URI.html#M001444
PHP: http://php.net/manual/en/function.parse-url.php
Java: http://download.oracle.com/javase/1.4.2/docs/api/java/net/URI.html#URI(java.lang.String)
C#: http://msdn.microsoft.com/en-us/library/system.uri.aspx
Ask if I'm missing a language.
This way, you could first parse the uri, then check to make sure that it passes your own verification rules. Here's an example in Python:
url = urlparse.urlparse(user_url)
if not (url.scheme and url.path):
raise ValueError("User did not enter a correct url!")
Since you said you were using C# on asp.net, here's an example (sorry, my c# knowledge is limited):
user_url = "http://myUrl/foo/bar";
Uri uri = new Uri(user_url);
if (uri.Scheme == Uri.UriSchemeHttp && Uri.IsWellFormedUriString(user_url, UriKind.RelativeOrAbsolute)) {
Console.WriteLine("I have a valid URL!");
}
This is pretty much a FAQ. You could simply try a search with [regex] +validate +url or just look at this answer: What is the best regular expression to check if a string is a valid URL
I use this regex. It works fine for me.
/((([A-Za-z]{3,9}:(?://)?)(?:[-;:&=+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+\$,\w]+#)[A-Za-z0-9.-]+)((?:/[+~%/.\w-]*)?\??(?:[-+=&;%#.\w])#?(?:[\w]))?)/