KotlinJs - simple HTTP GET without Dynamic Type functionality - http-get

I'm totally new in KotlinJs and I wanted to check its potential in server-less service development.
I decided to start with calling external API with HTTP GET method using XMLHttpRequest() suggested in KotlinJs documentation. However, I cannot come up with any way of using it without dynamic mechanism.
fun main(args: Array<String>) {
val url = "https://jsonplaceholder.typicode.com/todos/1"
var xhttp: dynamic = XMLHttpRequest()
xhttp.open("GET", url, true)
xhttp.onreadystatechange = fun() {
if (xhttp.readyState == 4) {
println(xhttp.responseJson)
}
}
xhttp.send()
}
Of course this example works perfectly fine, but I feel like it has to be better way of doing it without disabling Kotlin's type checker.
Is there any way of doing it using KotlinJs only (without dynamic) ?
If it is not possible, could someone at least explain why?

I found a way for not using dynamic with callbacks, just like in classic .js
private fun getData(input: String, callback: (String) -> Unit) {
val url = "https://jsonplaceholder.typicode.com/todos/$input"
val xmlHttp = XMLHttpRequest()
xmlHttp.open("GET", url)
xmlHttp.onload = {
if (xmlHttp.readyState == 4.toShort() && xmlHttp.status == 200.toShort()) {
callback.invoke(xmlHttp.responseText)
}
}
xmlHttp.send()
}
and than just call it:
getData("1") {
response -> println(response)
}
Hopefully it will help someone in the future.

Related

Spring webflux - multi Mono

I do not know or ask this question except here, if it's not the place I apologize.
I am currently working on an application using spring webflux and I have a problem with the use of Mono and Flux.
Here I have a REST request that comes with a simple bean that contains attributes including a list. This list is iterated to use a responsive mongo call that returns a Mono (findOne).
But I do not think I've found the right way to do it:
#PostMapping
#RequestMapping("/check")
public Mono<ContactCheckResponse> check(#RequestBody List<ContactCheckRequest> list) {
final ContactCheckResponse response = new ContactCheckResponse();
response.setRsnCode("00");
response.setRspnCode("0000");
LOG.debug("o--> person - check {} items", list.size());
final List<ContactCheckResponse.Contact> contacts = new ArrayList<>();
response.setContacts(contacts);
return Mono.fromCallable(() -> {
list.stream().forEach( c -> {
Boolean exists = contactRespository.findOneByThumbprint(c.getIdentifiant()).block() != null;
ContactCheckResponse.Contact responseContact = new ContactCheckResponse.Contact();
responseContact.setExist(exists);
responseContact.setIdentifiant(c.getIdentifiant());
responseContact.setRsnCode("00");
responseContact.setRspnCode("0000");
response.getContacts().add(responseContact);
});
return response;
});
}
the fact of having to make a block does not seem to me in the idea "reactive" but I did not find how to do otherwise.
Could someone help me find the best way to do this task?
Thank you
Something along these lines:
return Flux.fromIterable(list)
.flatMap(c -> contactRespository.findOneByThumbprint(c.getIdentifiant())
.map(r -> r != null)
.map(exists -> {
ContactCheckResponse.Contact responseContact = new ContactCheckResponse.Contact();
...
return responseContact;
})
)
.reduce(response, (r,c) -> {
response.getContacts().add(responseContact);
return response;
});
Create a Flux from the list, create a contact for each entry and reduce everything to a Mono.

ASync Recaptcha in MVC3

I've implemented ReCaptcha in MVC3 using ReCaptcha.net NuGet package http://recaptchanet.codeplex.com/wikipage?title=How%20to%20Use%20Recaptcha%20in%20an%20ASP.NET%20MVC%20Web%20Application. All working well, except I'd like to see if I can implement this as Async as it is sometimes quite slow, and we may have some volume on these pages.
The instructions say
RecaptchaVerificationResult recaptchaResult = await recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
ModelState.AddModelError("", "Incorrect captcha answer.");
}
however, this is using the MVC4 await syntax. Is there a way I can use this method within the MVC3 async framework?
I did try a quick hack, converting the controller to AsyncController naming the method with an Async suffix and wrapping the entire action in a Task.Factory.StartNew(() => { ... }); while using the non-async syntax, but RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper(); complains about a lack of HTTPContext.
So, can anyone help me with doing ReCaptcha asynchronously in MVC3
In the end, I've dropped using the NuGet package, and simply process the captcha's using the code below, binding the recaptcha fields in the controller method.
public bool ProcessCaptcha(string recaptcha_challenge_field, string recaptcha_response_field)
{
const string verifyUrl = "http://www.google.com/recaptcha/api/verify";
var res = true;
var ip = Request.UserHostAddress;
if (ip == "::1") ip = "127.0.0.1";
var myParameters = string.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", Config.CaptchPriv, ip, recaptcha_challenge_field, recaptcha_response_field);
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(verifyUrl, myParameters);
var split = HtmlResult.Split('\n');
if (split[0] == "false") res = false;
}
return res;
}
With this in place, I split my original controller method into a Async/Completed pair, and wrapped the work it does in Task.Factory.StartNew(() => { ... }), following the pattern outlined here http://www.deanhume.com/Home/BlogPost/mvc-asynchronous-controller---the-basics/67 which seems to work perfectly.

Primefaces: Default oncomplete method for all ajax request

I am trying to configure an oncomplete method for all ajax requests so that I can handle session timeout.
I tried adding the following script but it didn't work the same way as setting oncomplete property for p:ajax element. It wouldn't execute each time an Ajax request is made.
$.ajaxSetup({method: post,
complete: function(xhr, status, args){
var xdoc = xhr.responseXML;
if(xdoc == null){
return;
}
errorNodes = xdoc.getElementsByTagName('error-name');
if (errorNodes.length == 0) {
return;
}
errorName = errorNodes[0].childNodes[0].nodeValue;
errorValueNode = xmlDoc.getElementsByTagName('error-message');
errorValue = errorValueNode[0].childNodes[0].nodeValue;
alert(errorValue);
document.location.href='${pageContext.request.contextPath}/login/login.jsf';
}
});
Any help would be appreciated
PrimeFaces newer versions (using PF 5 here)
var originalPrimeFacesAjaxUtilsSend = PrimeFaces.ajax.Request.send;
PrimeFaces.ajax.Request.send = function(cfg) {
if (!cfg.oncomplete) {
cfg.oncomplete = doYourStuff;
}
originalPrimeFacesAjaxUtilsSend.apply(this, arguments);
};
Just to keep it somewhere, tried to find at stackoverflow but only older versions..
hope someone find this useful.
I managed to implement this by wrapping Primefaces AjaxUtils method.
var originalPrimeFacesAjaxUtilsSend = PrimeFaces.ajax.AjaxUtils.send;
PrimeFaces.ajax.AjaxUtils.send = function(cfg) {
if (!cfg.oncomplete) {
// register default handler
cfg.oncomplete = oncompleteDefaultHandler;
}
originalPrimeFacesAjaxUtilsSend.apply(this, arguments);
};
In primefaces there is component ajaxStatus which you can use for this purpose. Read documentation to see some more details about it, but for your use-case it can be something like this:
<p:ajaxStatus oncomplete="ajaxStatusHandler(xhr, status, args)"/>
and you can use your JavaScript function as is:
function ajaxStatusHandler(xhr, status, args) {
// your code ...
}
NOTE: this method can be used just for global AJAX requests (which is default in PrimeFaces), also, as I know, cross-domain script or JSONP (JSON with padding) requests can't be global.

How to generate URI inside a controller in Spring 3

I use spring 3.0 and I have a really simple question but didn't find any answer on the internet. I want to generate a path (an URI) just like in my JSPs:
<spring:url value="/my/url" />
But inside a controller. What is the related service to use?
Thanks!
Edit: May it be related with this: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/resources.html#resources-resourceloader ?
Ain't there a better solution for this?
Rossen's suggestion is gold.
There's also the ServletUriComponentsBuilder class from 3.1 that builds URLs from current request in static fashion. For example:
ServletUriComponentsBuilder.fromCurrentContextPath().path("/my/additional/path").build().toUriString();
It's the closest thing to <spring:url> in servlet.
In Spring MVC 3.1 you can use the UriComponentsBuilder and its ServletUriComponentsBuilder sub-class. There is an example of that here. You can also read about UriComponentsBuilder in the reference docs.
I would say
request.getRequestURL() + "/my/url"
makes the job. There is no such built in functionality, spring:url calls UrlTag.class that has the below method to generate URL, you can use it as an insőiration for your code:
private String createUrl() throws JspException {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
StringBuilder url = new StringBuilder();
if (this.type == UrlType.CONTEXT_RELATIVE) {
// add application context to url
if (this.context == null) {
url.append(request.getContextPath());
}
else {
url.append(this.context);
}
}
if (this.type != UrlType.RELATIVE && this.type != UrlType.ABSOLUTE && !this.value.startsWith("/")) {
url.append("/");
}
url.append(replaceUriTemplateParams(this.value, this.params, this.templateParams));
url.append(createQueryString(this.params, this.templateParams, (url.indexOf("?") == -1)));
String urlStr = url.toString();
if (this.type != UrlType.ABSOLUTE) {
// Add the session identifier if needed
// (Do not embed the session identifier in a remote link!)
urlStr = response.encodeURL(urlStr);
}
// HTML and/or JavaScript escape, if demanded.
urlStr = isHtmlEscape() ? HtmlUtils.htmlEscape(urlStr) : urlStr;
urlStr = this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr;
return urlStr;
}

FTP status code response don't work

Welcome!
I have a little problem with own application. This app can be connect(sith socket) an FTP server, and its work fine. But my problem is, if the user use bad usernam or password, the program won't receive the response statucode. Whats wrong?
I would like to use this statuscode some clause to examine(usernem or/and password etc.)
Code:
public static void ReadResponse()
{
result = ParseHostResponse();
statusCode = int.Parse(result.Substring(0, 3));
statusMessage = "";
}
The ParseHostResponse() method contains next:
Code:
public static string ParseHostResponse()
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = socket.RemoteEndPoint;
socketEventArg.SetBuffer(buffer, BUFFER_SIZE, 0);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
statusMessage = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
statusMessage = statusMessage.Trim('\0');
}
else
{
statusMessage = e.SocketError.ToString();
}
});
socket.ReceiveAsync(socketEventArg);
string[] msg = statusMessage.Split('\n');
if (statusMessage.Length > 2)
{
statusMessage = msg[msg.Length - 2];
}
else
{
statusMessage = msg[0];
}
if (!statusMessage.Substring(3, 1).Equals(" "))
{
return ParseHostResponse();
}
return statusMessage;
}
If I invite to the ReadResponse() method, the Visual Studio answer with this exception: NullReferenceException
in this code:
Code:
.
.
string[] msg = statusMessage.Split('\n');
.
What is the wrong? This code issue to http://msdn.microsoft.com/en-us/library/hh202858%28v=vs.92%29.aspx#BKMK_RECEIVING
Thank you for your help!
I can't help, but have to start with these side remarks:
statusMessage.Trim('\0') does not work (try it)
statusMessage.Split('\n') is inefficient as it involves extra allocations (guess why)
Now to the actual subject: I never used sockets on WP7, but from what I know about async operations it looks to me that you start async op (by calling ReceiveAsync) and use the result (statusMessage) before the answer arrives.
Think a bit about your design of the ParseHostResponse() method:
Bad name: Indicates parsing of a response, while it actually performs communication
Bad functionality: The method indicates sync patter, but internally uses async pattern. I don't know what to suggest here as every solution seems to be wrong. For example waiting for a response will make UI irresposible.
My main recommendation is that you get more information about async programming and then reprogramm your app accordingly.

Resources