ScriptEngineManager: How to make a http request from JavaScript Engine - javascript

I'm, using javax.script.ScriptEngineManager, in which, im using the JS Script Engine, like this.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.eval(str);//str contains JS code as String
Invocable inv = (Invocable) engine;
Object[] objAry = {"Sample String input"};//input ary
Object objOutput = inv.invokeFunction(fuctionName, objAry);//function name & input ary
Now, I want to execute, JS code which will make a HTTP request.
Currently, I'm trying with this script.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
But, it is not supported, as I guess, this code, is for browser.
Therefore, My question is, How to make a HTTP call from JS code, which is executing via javax.script.ScriptEngineManager?
And, currently, I'm using jdk7.

Related

Get values of parameters of javascript function from Java?

For my Java application I need to be able of, given a JavaScript string, determine the actual arguments passed into a function call.
For example, given this JavaScript string:
const url = "http://foo.bar?q=" + location.href
const method = "GET"
const isAjax = true
let xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, isAjax);
I would like to evaluate this JavaScript in order to get this:
xmlhttp.open("GET", "http://foo.bar?q=someurl", true);
Right now I'm using a regex to look for the parts of the JavaScript I'm interested in (in this example it would be the open method of the XMLHttpRequest object), but I need to be able to compute the actual values of the arguments passed to a function, if they are not hardcoded from the call-side.
I have been searching here but what I found was more related to actually executing the JavaScript code rather than looking at its expressions values (more like evaluating it, getting an AST or something like that).
Any ideas on how to accomplish this?
My idea is to add some javascript mocking library like sinon and execute this javascript.
Especially take a look at fake XMLHttpRequest
Javascript code will like this:
let sinon = require('sinon');
let xhr = sinon.useFakeXMLHttpRequest();
let requests = [];
xhr.onCreate = function (xhr) {
requests.push(xhr);
}
const url = "http://foo.bar?q=" + location.href
const method = "GET"
const isAjax = true
let xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, isAjax);
console.log(requests[0].url)

Redirect to another servlets path through Java Method

I have a method inside my doGet that starts a thread if the date is not equal to today. The scheduler will find the execute() method. Inside this method() I try to use the redirect.
Method 1:
I used the ScriptEngine to call my js method through Java but it always gives me the following error:
Js method:
function httpGet(theUrl){
window.open(theUrl)
}
Java Method:
ScriptEngine engine = manager.getEngineByName("js");
// read script file
engine.eval(Files.newBufferedReader(Paths.get(url), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("httpGet", "http://localhost:8080/myProject/StartScript?duration="+minutes);
Error:
javax.script.ScriptException: ReferenceError: "window" is not defined in <eval> at line number 3
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:392)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:190)
at watering.WateringScheduler.execute(WateringScheduler.java:99)
at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)Caused by: <eval>:3 ReferenceError: "window" is not defined
Method 2:
I tried to use HttpUrlConnection but the problem is that it never redirects me to the page even though it connects.
URL url;
log.info("hi "+ minutes);
url = new URL("http://localhost:8080/myProject/StartScript?duration="+minutes);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
int responseCode = urlConnection.getResponseCode();
System.out.println(responseCode);
if(responseCode==200) {
urlConnection = (HttpURLConnection) url.openConnection();
System.out.println("Redirect to URL : " + url);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
The problem is that everything I read online points to redirect through the doGet or doPost. I want to redirect through my execute() method.
Thanks!
The script engine in Java provides the ability to execute Javascript code, but does not provide an emulation of a browser.
Use HTTP clients like okhttp to download the raw HTML of the page.
For more information please visit
“document” is not defined in java ScriptEngine

How to use AJAX in Java? [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
I have the following javaScript function:
function loadSomething() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "javaservlet.java", true);
xhttp.send();
}
and I want to get, lets say an int value from a Java Servlet - "javaservlet". What code should I write in javaservlets doGet() method in order to send a value, so I can get and use it in javaScript? Thank you!
So, you want to return something from your servlet back to the javascript you called that servlet from. Here is the way, make an XMLHttpRequest object using these lines of code
var reqObject = new XMLHttpRequst(); or new ActiveXObject("Microsoft.XMLHTTP");
now make a request to the servlet's get or post method using the XMLHttpRequst's open method, you can simply do it like this
reqObject.open("GET/POST", "ServletName", true);
now if you have made a request to the server and state of the object reqObject is being changed then you will want to see the changes that are being made. Call a function when the state of the object is changed
reqObject.onreadystatechange = processRespose;
if you want to send something as parameter to the servlet use send method otherwise send null.
reqObject.send(null);
now if the servlet is returning something in the method you called from .open the state of the object will be changed and function processResponse will be called.
function processResponse(){
//check whether the response form the server is intact and correct
if(reqObject.status==200 && reqObject.readyState==200){
//simply means we got the response correctly
//Now you can get the response by
var res = reqObject.responseText;
}
}
you can read about the objects methods and properties here
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
I java servlet you just have to send the expected string with the PrintWriter's object. A rough version of Get method would look somewhat like this
doGet(request, response){
PrintWriter out = response.getWriter();
out.println("Javasrvlet");
}
You need to provide url mapping for that servlet in web.xml. I am assuming your servlet class name is JavaServlet.
<servlet>
<description></description>
<display-name>JavaServlet</display-name>
<servlet-name>JavaServlet</servlet-name>
<servlet-class>JavaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JavaServlet</servlet-name>
<url-pattern>/javaServlet</url-pattern>
</servlet-mapping>
Now change the following in javascript code to send GET request to JavaServlet.
function loadSomething()
{
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "javaServlet", true);
xhttp.send();
}
You can write like this....
public void service(HttpServletRequest request, HttpServletResponse){
response.getWriter().write("<Your Data>");
}

Load external URL content using pure Javascript

The following JQuery gets content of an external url:
var url = 'example.com/editor/stores/10';
$('#storeArticlePublish_Channel').load(url);
I do not want to use JQuery. How would I do this using normal javascript?
You can use XMLHttpRequest object for this.To make a request:
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET",URL,true);
xmlhttp.send();
The 'URL' is the url you want to execute/open.
The 3rd parameter is for async request, it can be either true or false.
And to get the result in #storeArticlePublish_Channel element, you can simply use this in the next line:
document.getElementById("storeArticlePublish_Channel").innerHTML = xmlhttp.responseText;

parse rss feed using javascript

I am parsing an RSS feed using PHP and JavaScript. First I created a proxy with PHP to obtain the RSS feed. Then get individual data from this RSS feed using JavaScript. My issue with with the JavaScript. I am able to get the entire JavaScript document if I use console.log(rssData); with no errors. If I try to get individual elements within this document say for example: <title>, <description>, or <pubDate> using rssData.getElementsByName("title"); it gives an error "Uncaught TypeError: Object....has no method 'getElementsByName'". So my question is how to I obtain the elements in the RSS feed?
Javascript (Updated)
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
return xmlHttp.responseXML;
}
// rss source
var rssData = httpGet('http://website.com/rss.php');
// rss values
var allTitles = rssData.getElementsByTagName("title"); // title
var allDate = rssData.getElementsByTagName("pubDate"); // date
Try changing the last line of the httpGet function to:
return xmlHttp.responseXML;
After all, you are expecting an XML response back. You may also need to add this line to your PHP proxy:
header("Content-type: text/xml");
To force the return content to be sent as XML.

Categories

Resources