Go Premium for a chance to win a PS4. Enter to Win


script value (ScriptEngine)

Posted on 2009-07-01
Medium Priority
Last Modified: 2012-05-07
I try to get some information in my script from my java program by using ScriptEngineManager.  Why values of the variables I would love to get were null?  How can I get a variable's value from the script?
My script...
function googleMapCal(lat, lng, city, region, country)
	var ClientLoc = google.loader.ClientLocation;
	lat = ClientLoc.latitude;
	lng = ClientLoc.Longitude;
	city = ClientLoc.address.city;
	region = ClientLoc.address.region;
	country = ClientLoc.address.country;
function drawMap(ClientLoc) {
    if (google.loader.ClientLocation) {
        var cl = google.loader.ClientLocation;
        var location = [cl.address.city, cl.address.region, cl.address.country].join(', ');
        ClientLoc = cl;
    } else {
        document.getElementById('cantfindyou').innerHTML = "Crap, I don't know. Good hiding!";
Where I try to get values....
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("JavaScript");
		Bindings vars = new SimpleBindings();
		// Run Javascript
			engine.eval("function googleMapCal(lat, lng, city, region, country)" +
			"{" +
				"var ClientLoc = google.loader.ClientLocation;" +
				"drawMap(ClientLoc);" +
				"lat = ClientLoc.latitude;" +
				"lng = ClientLoc.Longitude;" +
				"city = ClientLoc.address.city;" +
				"region = ClientLoc.address.region;" +
				"country = ClientLoc.address.country;" +
			"}", vars);
		} catch (ScriptException ex){
		// Get JavaScript Variables
		lat = (String)vars.get("lat");
		lng = (String)vars.get("lng");
		city = (String)vars.get("city");
		country = (String)vars.get("country");
		region = (String)vars.get("region");
		System.out.println("You are from " + lat + "/" + lng + "/" + city + "/" + country + "/" + region);

Open in new window

Question by:xenia27
  • 4
  • 2

Author Comment

ID: 24760803
What's wrong with my code?
LVL 10

Accepted Solution

mahome earned 1500 total points
ID: 24761156
You're just defining a function. You must call the function, that the values will be set. Here an example:

Bindings vars = new SimpleBindings();
        // Run Javascript
                engine.eval("function mytest(param1)" +
                "{" +
                        "value = param1;" +
                "}" +
                "mytest('test it');"
                        , vars);
        } catch (ScriptException ex){
        // Get JavaScript Variables
        String value = vars.get("value").toString();
        System.out.println("My Value: " + value);

Open in new window


Author Comment

ID: 24761226
I got an error message "Source  not found"...
What should I do?  Did I define something wrong?
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 10

Expert Comment

ID: 24761234
Can you post your complete Java-main-Funktion and the complete error message.

Author Comment

ID: 24761263
When I tried to run in debug mode, I got an error message pops up said I missed ";" somewhere in my file.  Then, I tried to run the function where calls javascript function and I got..

H 08:12:23 com.google.appengine.tools.development.ApiProxyLocalImpl log
SEVERE: [1246522343671000] javax.servlet.ServletContext log: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String com.unet.googleproject.client.GreetingService.greetServer(java.lang.String)' threw an unexpected exception: java.lang.NullPointerException
      at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:360)
      at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:546)
      at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:166)
      at com.google.gwt.user.server.rpc.RemoteServiceServlet.doPost(RemoteServiceServlet.java:86)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:713)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
      at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
      at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1093)
      at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
      at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
      at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360)
      at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
      at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
      at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:712)
      at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
      at com.google.apphosting.utils.jetty.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:54)
      at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139)
      at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:306)
      at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139)
      at org.mortbay.jetty.Server.handle(Server.java:313)
      at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:506)
      at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:844)
      at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:644)
      at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205)
      at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:381)
      at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:396)
      at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:442)
Caused by: java.lang.NullPointerException
      at com.unet.googleproject.server.GreetingServiceImpl.GetClient(GreetingServiceImpl.java:48)
      at com.unet.googleproject.server.GreetingServiceImpl.greetServer(GreetingServiceImpl.java:28)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:527)
      ... 25 more
this is where I try to call the javascript function...
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {
	public String greetServer(String input) {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		Locale clientRequest = getThreadLocalRequest().getLocale();
		String clientHostAddr = getThreadLocalRequest().getRemoteAddr();
		String lat = new String();
		String lng = new String();
		String city = new String();
		String country = new String();
		String region = new String();
		GetClient(lat, lng, city, country, region);
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent
				+ ".<br><br>You are from:<br>" + city + "/" + country + " " + region
				+ ".<br><br>Your Lat/Lng:<br>" + lat + "/" + lng;
	public void GetClient(String lat, String lng, String city, String country, String region)
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("javascript");
		Bindings vars = new SimpleBindings();
		Invocable invocableEngine = (Invocable)engine; 
		// Run Javascript
			engine.eval("function getInfo(Lat){"
					+ "  getLat(Lat); } ", vars
			lat = vars.get("Lat").toString();
			System.out.println("Lat: " + lat);
		} catch (ScriptException ex){
this is where I have my javascript...in a html file...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<!-- The HTML 4.01 Transitional DOCTYPE declaration-->
<!-- above set at the top of the file will set     -->
<!-- the browser's rendering engine into           -->
<!-- "Quirks Mode". Replacing this declaration     -->
<!-- with a "Standards Mode" doctype is supported, -->
<!-- but may lead to some differences in layout.   -->
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <!--                                                               -->
    <!-- Consider inlining CSS to reduce the number of requested files -->
    <!--                                                               -->
    <link type="text/css" rel="stylesheet" href="xxx.css">
    <!--                                           -->
    <!-- Any title is fine                         -->
    <!--                                           -->
    <title>Web Application Starter Project</title>
    <!--                                           -->
    <!-- This script loads your compiled module.   -->
    <!-- If you add any GWT meta tags, they must   -->
    <!-- be added before this line.                -->
    <!--                                           -->
    <script type="text/javascript" language="javascript" src="xxx/xxxt.nocache.js"></script>
      <style type="text/css">
  body {
    padding: 0;
    margin: 0;
    background-color: #4f4e45;
    font-family: Tahoma, Arial, sans-serif;
  #header {
    height: 30px;
    background-color: #111;
    color: #EEE;
    font-size: 10pt;
    padding-top: 4px;
    border-bottom: 1px solid #333;
  #main {
    margin: 20px auto;  
    width: 610px;
  #main h2 {
    font-weight: normal;
    margin: 0;
    color: #ff9600;
    font-size: 16pt;
    font-family: Tahoma, Arial, sans-serif;
    padding-bottom: 1em;
  a {
    color: #fff;
  #cantfindyou {
      font-size: 18pt;
  #map {
      display: none;
      height: 300px;
      border: 1px solid black;
      margin: 10px 4px;
  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->
    <!-- OPTIONAL: include this if you want history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
    <h1>Web Application Starter Project</h1>
    <table align="center">
        <td colspan="2" style="font-weight:bold;">Please enter your name:</td>        
        <td id="nameFieldContainer"></td>
        <td id="sendButtonContainer"></td>
	<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAJjoQAkGmq5qsa0PKk9Y6nxQdF2TG78juI7gyCxAZXlcasg4lQxTlaYHDB6IKUESWIPTqiJvXPeiwhg"></script>
	<script type="text/javascript">
	functionn getInfo(Lat)
	function getLat(Lat)
	    if (google.loader.ClientLocation) {
	        var cl = google.loader.ClientLocation;
	        var location = [cl.address.city, cl.address.region, cl.address.country].join(', ');
	    Lat = cl.latitude;

Open in new window


Author Comment

ID: 24769645
Any help?
Is there any example which contains both javascript and java examples?  All I can find is examples in java about how I can use ScriptEngineManager.

By the way, I try to create a web application with google wizard and eclipse.  Please help me~

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

926 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question