Run JavaScript in Java - java

I have a javaScript tag:
<!-- Begin ParsTools.com Prayer Times Code -->
<script type="text/javascript" language="javascript" src="http://www2.parstools.com/oghat/oghatwhite.php"></script>
<script language="javascript">
var CurrentDate= new Date();
var JAT= 1;
function pz() {};
init();
document.getElementById("cities").selectedIndex=12;
coord();
main();
</script>
<!-- End Prayer Times code -->
I want to run this script in java and receive the html document that server sends in response. How can I do this? I also need to parse the received document and extract some special tags.
thank you.

The easiest way I know is using HtmlUnit.
WebClient htmlunit = new WebClient();
HtmlPage page = htmlunit.getPage("http://www.google.com");
//executing the javascript and getting the new page
page = page.executeJavaScript("<JS code here>").getNewPage();
more info: http://www.aviyehuda.com/2011/05/htmlunit-a-quick-introduction/

Sajad/Future visitors,
You may look into Jakarta Bean Scripting Framework (BSF) to run your javascript even as standalone code if using older java version (< 1.6, later versions of java have it embedded)

Related

d3-wordcloud in GWT

I am trying to use d3-wordcloud(https://github.com/jasondavies/d3-cloud) in my GWT project. I included this in my .html file:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" language="javascript" src="d3.layout.cloud.js"></script>
<script type="text/javascript" language="javascript" src="main.js"></script>
Where 'main.js' has a method which contains this code:
d3.layout.cloud().size([width, height])
.timeInterval(20)
.words(word_entries)
.fontSize(function(d) { return xScale(+d.value); })
.text(function(d) { return d.key; })
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.on("end", draw)
.start();
When I try to call the method from the .html file, the word cloud is generated fine. But when I do it from a java file (with $wnd), I get this error:
Uncaught TypeError: d3.layout.cloud is not a function' error
I think this might be because the d3.layout.cloud.js is written in node js and GWT doesn't know how to work with it.
Is that the reason? Is there a workaround?
Additional info: I use GWT 2.7. Good with java. Zero node js skills!
Feels like you need to simply use cloud()... instead of d3.layout.cloud()...
See line 10: https://github.com/jasondavies/d3-cloud/blob/master/examples/node.js

Proper escaping for ng-init

I have a java web application with an angular.js app imported on a page. When the page is called, I gather a bunch of variables in the java class and build a JSONObject instance containing them.
JSONObject initData = new JSONObject();
initData.put("key1", "abc");
initData.put("test special chars", "$%{}<>'\"?");
request.setAttribute("initData", initData.toString());
I want the variables gathered in the java class to be available to the angular app, which is why I'm using a json object. In the jsp I have the following:
<div ng-app="myAngularApp" ng-init="initData=${initData}">
<div class="ng-view"></div>
</div>
<script src="angular/scripts/frameworks.js"></script>
<script src="angular/scripts/plugins.js"></script>
<script src="angular/scripts/myApp.js"></script>
<script type="text/javascript">angular.modulate.instantiateModules();</script>
The ${initData} prints out the string value of my JSONObject from the java class. However, I can't seem to escape it correctly. I've tried a bunch of StringEscapeUtils methods but no luck.
What's the correct way to get this info into ng-init?

Converting local JSP page into global web page without modifying the source code?

I have designed a product recommendation hub using Java and JavaScript in Eclipse. Basic functionality is, if the person enters the product name, it will retrieve the relevant product reviews from the local XAMPP database, perform sentiment analysis on it and dispalys whether the product is recommended or not based on the number of positive or negative sentiments. My questions:
Is it possible to convert this local JSP UI page into a globally accessible web page without modifying my java code?
If Yes, please guide me. If No, please justify to get a clear understanding.
Is it possible using Amazon AWS?
You could load the page via ajax/jquery.
In the target page, create a div tag that will be your placeholder:
<div id="myPlaceholder"></div>
and add some javascript like:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.get("/theurlofthecurrentpage?some=thing", function(data) {
$("#myPlaceholder").html(data);
});
});
</script>
If the JSP control does full postbacks, you may have to update it to handle it clientside. hopefully this helps.

Inserting a JavaScript resource into a Liferay Portlet

I would like to use jsTree inside of my Liferay portlet, but everytime the script gets executed I get an error:
TypeError: treeContainer.jstree is not a function # localhost:8080/web/guest/home:14
I understand that it doesn't have the JS file available for use, so I've tried these two approaches, but niether of them works.
First: Include it directly by adding
<script type="text/javascript" src="jquery.jstree.js"></script>
into the JSP. Although I can see it being "linked" in my IDE, after building and deploying it's unavailable (duh).
Second: Editing it in the liferay-portlet.xml like this:
<portlet>
<portlet-name>myPortlet</portlet-name>
<instanceable>false</instanceable>
<!-- other mappings here -->
<header-portlet-javascript>my/resource/folder/myPortlet/jquery.jstree.js
</header-portlet-javascript>
</portlet>
But even if I edit it in like this I get an 404 in the browser console.
Function used in the JSP:
<script type="text/javascript">
$(".tree-search").click(function(){
treeContainer = $(this).siblings('.tree-container');
// correct data is taken from ${jsonFake}
treeContainer.jstree({
"plugins":["themes","html_data","ui"], "json_data": { data: ${jsonFake}}
});
treeContainer.show();
treeContainer.animate({
opacity: "1"
}, 750);
});
</script>
What am I doing wrong, please?
This seems like path issue:
Create a folder named js inside docroot and put this file there.
Add script src like:
<script type='text/javascript' src='/js/jquery.jstree.js'></script>
add the js file in portal_normal.vm file in your current theme .like
<script type="text/javascript" src="jquery.jstree.js"></script>

How do you minify/obfuscate JavaScript code in a JSP that has JSP/JSTL variables mixed into it?

arrays.jsp:
//...
var x = <c:out value="${x}"/>
<c:if test="${empty doExternal}">
processExternalArrays();
</c:if>
//...
I want to minify/obfuscate JavaScript contained in a large JSP file in which numerous JSP/JSTL variables are mixed into the JavaScript code such as in the snippet above.
The code relies on variables populated using server-side logic and then passed to the client-side code, as above.
I'm already minifying my JS files using YUI compressor but I don't know what to do about the JavaScript code in my JSPs.
Is it possible to minify/obfuscate this code, given that it is dynamically created?
Probably the best solution for you would be use Granule JSP tag.
You can download it at
http://code.google.com/p/granule/
code sample is:
<g:compress>
<script type="text/javascript" src="common.js"/>
<script type="text/javascript" src="closure/goog/base.js"/>
<script>
goog.require('goog.dom');
goog.require('goog.date');
goog.require('goog.ui.DatePicker');
</script>
<script type="text/javascript">
var dp = new goog.ui.DatePicker();
dp.render(document.getElementById('datepicker'));
</script>
</g:compress>
...
Have you taken a look at htmlcompressor? In short it's a:
Java HTML/XML Compressor is a very
small, fast and easy to use library
that minifies given HTML or XML source
by removing extra whitespaces,
comments and other unneeded characters
without breaking the content
structure.
It's main function is so compress HTML and XML, but it also comes with JSP tags that can be used to compress inline JavaScript blocks by leveraging YUI Compressor. Check out the Google Code page, especially the Compressing selective content in JSP pages section.
I don't see other ways than fully delegating the job to pure JS with help of Ajaxical powers in combination with a Servlet which returns the desired information on an Ajax request (in flavor of JSON?).
E.g. in Servlet
Map<String, Object> data = new HashMap<String, Object>();
data.put("doExternal", doExternal);
data.put("x", x);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data)); // Gson is a Java-JSON converter.
and in JS (with little help of jQuery since it makes the Ajax works less verbose)
$.getJSON('servleturl', function(data) {
var x = data.x;
if (!data.doExternal) {
processExternalArrays();
}
});
This way you end up with clean JS without server-side specific clutter.
Ensure that your output is gzip encoded (apache mod_deflate). Minimizing the html/js first may make it a bit smaller, but not by much.
If you can't, or don't want to, move your JavaScript out of your HTML, one possibility would be to create a tag handler that wraps the content of your <script> tags:
<script type="text/javascript"><js:compress>
...
</js:compress></script>
The handler could probably extend SimpleTagSupport. You'd then have to investigate the Java APIs for compressors/minifiers, like YUI Compressor or dojo ShrinkSafe, and use them to process the tag body.
Edit: Sorry, I skimmed the other answers and it appears that Zack Mulgrew might be referencing a taglib that already does exactly what I'm suggesting...
Edit2: Yup, JavaScriptCompressorTag. Guess I'll have to up-vote his answer ;-)...

Categories

Resources