How to get string query params from URL in Domino - xpages

After some time I managed to make a redirect from some API.
However, now I'm facing a different problem.
It seems, that there's just no way to get a query param from URL.
The button looks like that:
<xp:eventHandler event="onclick" submit="true"
refreshMode="complete">
<xp:this.action><![CDATA[#{javascript:
var redirectUrl = context.getUrl().toString();
var errorRedirectUrl = context.getUrl().toString();
var EGRZAuthObject = new ru.iteko.egrz.requestprocessors.EGRZAuthorization();
//auth which redirects
EGRZAuthObject.initializeAuthProcess(redirectUrl, errorRedirectUrl);
print("marker param is " + param.get("marker"));
print("marker param is " + facesContext.getExternalContext().getRequest().getQueryString());
print("url " + context.getUrl().toString());
}]]></xp:this.action>
</xp:eventHandler>
The method which redirects is as follows:
public static void initializeAuthProcess(String redirectUrl, String apiRedirectUrl) throws ClientProtocolException, IOException
{
CloseableHttpClient httpclient = HttpClients.createDefault();
try
{
HttpContext context = new BasicHttpContext();
String urlToGoTo = AuthURLs.ESIALoginURL(redirectUrl, apiRedirectUrl);
HttpGet httpGet = new HttpGet(urlToGoTo);
HttpResponse response1 = httpclient.execute(httpGet, context);
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(
HttpCoreContext .HTTP_REQUEST);
HttpHost currentHost = (HttpHost) context.getAttribute(
HttpCoreContext .HTTP_TARGET_HOST);
String redirectURLEsia = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext externalContext = fc.getExternalContext();
externalContext.redirect(redirectURLEsia);
}
finally
{
httpclient.close();
}
}
Here's what happens:
In a browser the user initializes auth process by pressing the button
Then initializeAuthProcess executes a request to the system A
System A takes us to the system B, we redirect the user there
The user goes through authorization process in the system B
System B (after auth) redirects the user to our system
And it appends some sort of token in our system's URL called marker
Later on, we should do something with the marker...
The problem is that we don't know how to get the marker. It's always either null or empty. In a browser, however, we always can see it after auth in the system B successfully completed.
I get the following output:
marker param is null
marker param is
url https://oursystem.com/Nav2.xsp
We also wondering how to remove it from the URL after processing is completed. But as of now, we need to get it at least.
How can we do that?
Thanks in advance.
EDIT:
Obviously the thing is that the code gets executed immediately without waiting for the user authorization in the system B.
For instance if we press the button again we'll have marker param.
So we need a different approach there we should define marker and do something with it

You looking at the wrong end. There are 2 options: pick the marker from the returned response1 calling the other systems or move that code to the page you redirect to

If you click the button, you are redirected to the other page. Testing for the marker should therefore be in the callback step between 5 & 6. Check in the beforeRenderResponse event if the marker is there and then you can react to that.

Related

"User not found" Error when creating a child entity using ControllerB action, soon after an aspUser is created in controllerA

After the successful creation of an application user and the following line of code (in Register action in AccountController) :
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
I am trying to add a child object
var controller=DependencyResolver.Current.GetService<AnotherController>();
controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);
var res = controller.Create(
new ChildEntity
{
ApplicationUserId = user.Id,
IsAcative = true
});
my create Method looks like this
public async Task<ActionResult> Create(ChildEntity entity)
{
if (ModelState.IsValid)
{
db.ChildEntity.Add(entity);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(entity);
}
My object is not created. the return valueres contains the error "user not found" propertyName : "ApplicationUserId"
Can anybody help me to understand what is going on?
ps : i have noticed that the User.Identity.GetUserId() return null !!! (may be fo some other reason, may be my problem is linked to this..)
First and foremost, the user principal is not populated until after the next page load. The sign-in process merely sets the auth cookie. That cookie needs to be sent back and the auth machinery needs to run (as part of the request pipeline), before you can get anything from User.
Second, what you're doing here is just absolutely wrong. If you want to reuse the user creation code, factor it out into another class that all your controllers can utilize. It's absolutely the wrong approach to try to new up a controller inside another action to call an action on that.

Xamarin: Issues with transitioning between controllers and storyboard views

I realize this might come across as a very basic question, but I just downloaded Xamarin three days ago, and I've been stuck on the same issue for two days without finding a solution.
Here is what I am trying to do:
Get user input, call API, parse JSON and pass data to another controller, and change views.
Here is what I have been able to do so far: I get the user input, I call the API, I parse the response back, write the token to a file, and I want to pass the remaining data to the second controller.
This is the code I am trying:
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
if (verifyCode != null)
{
this.NavigationController.PushViewController(verifyCode, true);
}
My storyboard setup:
Navigation controller -> routesTo -> FirstController
I have another UI Controller View set up with the following properties set:
storyboardid: verify
restorationid: verify
and I am trying to push that controller view onto the navigation controller.
Right now this line is erroring out:
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
giving me this error, which I don't know what it means: Could not find an existing managed instance for this object, nor was it possible to create a new managed instance.
Am I way off in my approach?
p.s: I cannot use the ctrl drag thing like the tutorial suggests because I have an asynchronous call. And I cannot under no circumstances make it synchronous. So all the page transition has to be manual.
EDIT
to anyone requesting more code or more info:
partial void registerButton_TouchUpInside (UIButton sender)
{
phone = registrationNumber.Text;
string url = url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.Method = "GET";
Console.WriteLine("Getting response...");
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
}
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string content = reader.ReadToEnd();
if (string.IsNullOrWhiteSpace(content))
{
//Console.WriteLine(text);
Console.Out.WriteLine("Response contained empty body...");
}
else
{
var json = JObject.Parse (content);
var token = json["token"];
var regCode = json["regCode"];
var aURL = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine (aURL, "app.json");
File.WriteAllText(filename, "{token: '"+token+"'}");
// transition to main view. THIS IS WHERE EVERYTHING GETS MESSED UP
var verifyCode = Storyboard.InstantiateViewController("verify") as VerifyCodeController;
if (verifyCode != null)
{
this.NavigationController.PushViewController(verifyCode, true);
}
}
}
}
}
Here is all the info for every view in my storyboard:
1- Navigation controller:
- App starts there
- The root is the register pager, which is the page we are currently working on.
2- The register view.
- The root page
- class RegisterController
- No storyboard id
- No restoration id
3- The validate view
- Not connected to the navigation controller initially, but I want it to be connected eventually. Do I have to connect it either way? Through a segue?
- class VerifyCodeController
- storyboard id : verify
- restoration id : verify
If you guys need more information I'm willing to post more. I just think I posted everything relevant.

How can I use Scribe with JSF to connect to the LinkedIn API?

Based upon the Scribe example on github, I'm trying to authorize my application to use LinkedIn's api.
Here is my current code that is tied to a button click:
public String generateFromLinkedIn() {
OAuthService service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback("http://localhost:8080/Project/faces/linkedIn.xhtml").build();
ExternalContext externalContext = FacesContext.getCurrentInstance()
.getExternalContext();
Token requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(requestToken);
try {
externalContext.redirect(authUrl);
} catch (IOException ex) {
Logger.getLogger(LinkedInController.class.getName()).log(Level.SEVERE, null, ex);
}
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Verifier v = new Verifier(parameterMap.get("oauth_verifier"));
Token accessToken = service.getAccessToken(requestToken, v);
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.linkedin.com/v1/people/~");
service.signRequest(accessToken, request);
Response response = request.send();
System.err.println(response.getBody());
return "";
}
And in my .xhtml page I have:
<h:commandButton value="Generate" action="#{linkedInController.generateFromLinkedIn()}"></h:commandButton>
Everything works okay until I try to get the Verifier from the parameter map, which does not have any oauth_verifier. I tried splitting it up into multiple methods, but so far I cannot obtain the oauth_verifier from the URL parameters even though it is clearly there after returning from LinkedIn authorization dialog.
Any suggestions on how to get this verifier correctly or how to make Scribe work with JSF?
You seem somehow to expect that the redirected request magically returns to exactly same location in the code and continues from there. This is untrue. It are effectively 2 HTTP requests. You're basically still fiddling around in the parameter map of the current request (the one which called the generateFromLinkedIn() method).
After you call redirect() you should be returning from the method. You should move the remainder of the code into the #PostConstruct or <f:viewAction> of the backing bean tied to linkedIn.xhtml. It's the one who's called with the parameter.

Displaying results of an SPLongOperation

I am using SPLongOperation to run a lengthy operation. After completing, the gears page redirects back to the original page from which the long operation was launched. I am not able to write anything to the oriignal page using SPLongOperation.Endscript. Here is the code I am using
using (SPLongOperation operation = new SPLongOperation(this.Page))
{
//.......................
//.......................
StringBuilder endScript = new StringBuilder();
endScript.Append("document.write('Success!!');");
operation.End(Request.Url.ToString(), SPRedirectFlags.UseSource, HttpContext.Current, String.Empty, endScript.ToString());
}
You won't be able to write anything to the calling page, a new http request has been made to show you the page with the spinning wheel while your operation is under progress and then you're redirected back to the specified url (using a new request).
The easiest way to show a success message is to pass a specific querystring to your calling url by replacing your string.empty parameter with something like
operation.End(Request.Url.ToString(), SPRedirectFlags.UseSource, HttpContext.Current, "success=1");
http://msdn.microsoft.com/en-us/library/ms450341.aspx
and then on the load event, check if you have this parameter and display the relevant message (it would be better to add an item to the HttpContext.Items or doing a post instead of a get to remove the querystring but the suggested implementation will prevent you from changing your long operation call and behaviour)
Hope this will help.
Try an alert - that worked for me..
Script.Append("alert('Success!!');");
This might be of help: http://www.sharepoint-tips.com/2012/07/reporting-code-errors-when-running-code.html
SPLongOperation longOp = new SPLongOperation(this.Page);
StringBuilder sbErrors = new StringBuilder();
longOp.Begin();try
{
throw new Exception("Sample");
}
catch(Exception ex)
{
sbErrors.Append("An error occurred: " + ex.MEssage);
}
if
(sbErrors.Length > 0)
{
longOp.EndScript("document.getElementById('s4-simple-card-content').innerHTML = \"Errors have occurred during the submission. Details: " + sbErrors.ToString() + " \";");
}
//close the dialog if there were no errors
longOp.EndScript("window.frameElement.commitPopup();");

how to apply filters in jsf

I have a filter and I get Page not Found error when any client requests a JSF page in my web application. I don't know how to fix this issue.
Here is my filter code:
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession ses = req.getSession(true);
String pageRequested = req.getRequestURL().toString();
if (ses.getAttribute("userDetails") != null) {
fc.doFilter(request,response);
} else {
RequestDispatcher dis = request.getRequestDispatcher(LOGIN_PAGE);
dis.forward(request,response);
}
I have done all the necessary settings in web.xml deployment descriptor.
A 404 simply means that the requested resource is not found. Down to the point this can have 2 causes:
The URL is invalid (i.e. LOGIN_PAGE is invalid).
The resource is not there where you think it is.
To further nail down the cause in this particular problem we need to know 2 things:
What is the absolute URL of the current request? Print request.getRequestURL().
What is the absolute URL with which you can open the login page independently in webbrowser?
Then, you should be able to extract the correct LOGIN_PAGE from this information.

Resources