displaying page at client side (getting data from lua using socket.request) - extjs

i am trying to reach a cross domain server using lua.
i get a response from the server (the html code).
now, i need this page that i got to display at my site.
Code:
--body, header, status, error
b, h, s, e = socket.http.request{url = "http://someurl"
, proxy = "http://someProxy"
, sink = ltn12.sink.file(io.stdout)
}
the sink attribute does his job and prints the html back to the client side.
on the client side i am developing with extjs.
my question, is how do i display the page that was recieved ?
Thx,
Yoni

I think you would want to capture the output into a string in Lua, rather than having the sink be io.stdout, then use that string with one of the "3 ways to render HTML inside of a ExtJS container".
As for writing the data to a string instead of stdout, that might look like this:
local t = {}
sink = ltn12.sink.table(t)
-- ...
local html = table.concat(t)

Related

Avoiding using save() function twice

I want to use external API for my django application, which sends image to the server and receives back some LaTeX.
My model looks like this:
class Snip(models.Model):
snip = models.FileField(upload_to="snips/") #stored image
latex = models.TextField(default = '') #received text from API
The image has to be stored/saved so URL might be included in JSON sent to the API. But that implies newly uploaded image has to be saved in newly created Snip object and after receiving the requested text back saved again.
My view looks like this:
if file:
temp_snip = Snip() #creating newe object
temp_snip.snip = file
temp_snip.save() #saving image to the database (required for getting image URL)
temp_snip.setLatex() #some magic :)
temp_snip.save() #saving the magic (second field in the model).
My question is:
Is there any simple solution to avoid using save() function twice?

Get input from user with Rascal

Rascal is currently hosting my simple web server. Here I have an input for users using HTML textarea tag, and a submit button. However, I can't figure out how to request that input data from users when they have submitted it. I also don't see much documentation about it, so any help would be appreciated!
Assuming you either use the Content and/or util::Webserver from the library for serving content from Rascal, you always provide a function of type Response (Request) to the server. This function does everything from serving index.html to receiving form inputs, and handling XMLHttpRequests. All you have to do is write the function's alternatives.
The kinds of Requests you can get are defined like this in Content.rsc:
data Request (map[str, str] headers = (), map[str, str] parameters = (), map[str,str] uploads = ())
= get (str path)
| put (str path, Body content)
| post(str path, Body content)
| delete(str path)
| head(str path)
;
And responses are defined by:
data Response
= response(Status status, str mimeType, map[str,str] header, str content)
| fileResponse(loc file, str mimeType, map[str,str] header)
| jsonResponse(Status status, map[str,str] header, value val, bool implicitConstructors = true, bool implicitNodes = true, str dateTimeFormat = "yyyy-MM-dd\'T\'HH:mm:ss\'Z\'")
;
In the example below I use convenience utility functions such as Content::response(str) which wrap an html string with the right HTTP status and mimetypes.
Example:
// this serves the initial form
Response myServer(get("/"))
= response("\<p\>What is your name?\</p\>
'\<form action=\"/submit\" method=\"GET\"\>
' \<input type=\"text\" name=\"name\" value=\"\"\>
'\</form\>
");
// // this responds to the form submission, now using a function body with a return (just for fun):
Response myServer(p:get("/submit")) {
return response("Hello <p.parameters["name"]>!");
}
// in case of failing to handle a request, we dump the request back for debugging purposes:
default Response myServer(Request q) = response("<q>");
Now we can serve this directly from the REPL. The content will show up in an Eclipse editor window or in your default browser and will stay available for 30 minutes after the last interaction in Rascal's internal application server:
rascal>content("test", myServer)
Serving 'test' at |http://localhost:9050/|
Or we can serve it on our own, then browse to http://localhost:10001 to test the server. We have to shut the thing down manually when we're done:
rascal>import util::Webserver;
ok
rascal>serve(|http://localhost:10001|, myServer)
ok
rascal>shutdown(|http://localhost:10001|)
The initially served page in an editor window
The response after for submission

AngularJS HTTP POST and request data with Classic ASP [duplicate]

How do I access what has been posted by a client to my classic ASP server?
I know that there is the Request.Forms variable, but the client's request was not made using a Form.
The client request's body is just a string made using a standard POST statement.
Thanks
You need to read request bytes if content type of request sent by client is not form data. In this case, request is not a form-data that is accessible through name-value pairs so you cannot use Request.Form collection. I suggest investigate the BinaryRead method.
Reading posted data and convert into string :
If Request.TotalBytes > 0 Then
Dim lngBytesCount
lngBytesCount = Request.TotalBytes
Response.Write BytesToStr(Request.BinaryRead(lngBytesCount))
End If
Function BytesToStr(bytes)
Dim Stream
Set Stream = Server.CreateObject("Adodb.Stream")
Stream.Type = 1 'adTypeBinary
Stream.Open
Stream.Write bytes
Stream.Position = 0
Stream.Type = 2 'adTypeText
Stream.Charset = "iso-8859-1"
BytesToStr = Stream.ReadText
Stream.Close
Set Stream = Nothing
End Function
Hope it helps.
Update #1:
With using JScript
if(Request.TotalBytes > 0){
var lngBytesCount = Request.TotalBytes
Response.Write(BytesToStr(Request.BinaryRead(lngBytesCount)))
}
function BytesToStr(bytes){
var stream = Server.CreateObject("Adodb.Stream")
stream.type = 1
stream.open
stream.write(bytes)
stream.position = 0
stream.type = 2
stream.charset = "iso-8859-1"
var sOut = stream.readtext()
stream.close
return sOut
}
To get the JSON string value just use CStr(Request.Form)
Works a treat.
In Classic ASP, Request.Form is the collection used for any data sent via POST.
For the sake of completeness, I'll add that Request.QueryString is the collection used for any data sent via GET/the Query String.
I would guess based on the above that even though the client is not a web browser, the Request.Form collection should be populated.
note: all of this is assuming the data being sent is textual in nature, and that there are no binary uploads (e.g. pictures or files) being sent. Update your question body if this is an incorrect assumption.
To test, write out the raw form data and see what you have - something along the lines of:
Response.Write(Request.Form)
Which with a regular web page will output something like
field=value&field2=value2
If you get something along those lines, you could then use that as a reference for a proper index.
If you do not get something like that, update your question with what you tried and what you got.

Server Side Error validation

In my application I am doing client side and server side validation. Client side validation is pretty easy and user will not be able to click on the submitForm button. But suppose the zip code entered does not match with the order number and server is giving me error in 200 response in angular $http call promise. How can I show the server side error and maintain my validation ?
{"result":{"success":false,"code":null,"message":"The entered Zip does not match with Order"},"errors":
[]
Might not be the exact answer but could help :
1) On the server side if there are errors you should first stop the script from reaching to database.
2) Populate error messages on the server side in an array in the form of associative array, which can contain field name as key and error message as value. Later send the array to client side in JSON format.
3) On the client side loop through the JSON object to initialise the scope variables that will contain error messages per field.
May be in the format : serverErrors.fieldName.error = 'Error Message from server'
This should be a scope object. And the same object should be rendered on the template per field. So that when you loop through your JSON and assign error messages to each field it will show up in template. As Angular has two way binding.
This way you will be able to handle custom server side validations and show errors on client side. And this is possible not just in theory we have implemented this approach in one of our projects.
Hope that helps :)
I think you can try
$http.post('URL', { "ID": ID }).success(function (resultData) {
if (results.result.success) {
alert("scuess!");
$window.location.href = "/";
}
else {
alert(results.result.message)
}
});

Returning multiple items with Servlet

Good day, I'm working on a Servlet that must return a PDF file and the message log for the processing done with that file.
So far I'm passing a boolean which I evaluate and return either the log or the file, depending on the user selection, as follows:
//If user Checked the Download PDF
if (isDownload) {
byte[] oContent = lel;
response.setContentType("application/pdf");
response.addHeader("Content-disposition", "attachment;filename=test.pdf");
out = response.getOutputStream();
out.write(oContent);
} //If user Unchecked Download PDF and only wants to see logs
else {
System.out.println("idCompany: "+company);
System.out.println("code: "+code);
System.out.println("date: "+dateValid);
System.out.println("account: "+acct);
System.out.println("documentType: "+type);
String result = readFile("/home/gianksp/Desktop/Documentos/Logs/log.txt");
System.setOut(System.out);
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter outl = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
outl.print(result);
outl.flush();
}
Is there an efficient way to return both items at the same time?
Thank you very much
HTTP protocol doesn't allow you to send more than one HTTP response per one HTTP request. With this restriction in mind you can think of the following alternatives:
Let client fire two HTTP requests, for example by specifyingonclick event handler, or, if you returned HTML page in the first response, you could fire another request on window.load or page.ready;
Provide your for an opportunity of choosing what he'd like to download and act in a servlet accordingly: if he chose PDF - return PDF; if he chose text - return text and if he chose both - pack them in an archive and return it.
Note that the first variant is both clumsy and not user friendly and as far as I'm concerned should be avoided at all costs. A page where user controls what he gets is a much better alternative.
You could wrap them in a DTO object or place them in the session to reference from a JSP.

Resources