Solved

script value (ScriptEngine)

Posted on 2009-07-01
6
438 Views
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;
	drawMap(ClientLoc);
	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
		try{
			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){
			ex.printStackTrace();
		}
		
		// 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

0
Comment
Question by:xenia27
  • 4
  • 2
6 Comments
 

Author Comment

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

Accepted Solution

by:
mahome earned 500 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
        try{
                engine.eval("function mytest(param1)" +
                "{" +
                        "value = param1;" +
                "}" +
                "mytest('test it');"
                        
                        , vars);
        } catch (ScriptException ex){
                ex.printStackTrace();
        }
        
        // Get JavaScript Variables
        String value = vars.get("value").toString();
        System.out.println("My Value: " + value);

Open in new window

0
 

Author Comment

by:xenia27
ID: 24761226
I got an error message "Source  not found"...
What should I do?  Did I define something wrong?
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 10

Expert Comment

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

Author Comment

by:xenia27
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..

2009/7/2
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
		try{
			engine.eval("function getInfo(Lat){"
					+ "  getLat(Lat); } ", vars
        		);
			lat = vars.get("Lat").toString();
			System.out.println("Lat: " + lat);
		} catch (ScriptException ex){
			ex.printStackTrace();
		} 
 
	}
}
 
this is where I have my javascript...in a html file...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<!-- 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.   -->
 
<html>
  <head>
    <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;
  }
  </style>
    
  </head>
 
  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->
<body>
 
    <!-- 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">
      <tr>
        <td colspan="2" style="font-weight:bold;">Please enter your name:</td>        
      </tr>
      <tr>
        <td id="nameFieldContainer"></td>
        <td id="sendButtonContainer"></td>
      </tr>
    </table>
    
	<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAJjoQAkGmq5qsa0PKk9Y6nxQdF2TG78juI7gyCxAZXlcasg4lQxTlaYHDB6IKUESWIPTqiJvXPeiwhg"></script>
	<script type="text/javascript">
 
	functionn getInfo(Lat)
	{
		getLat(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;
	}
 
	</script>
 
</body>
 
</html>

Open in new window

0
 

Author Comment

by:xenia27
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~
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

808 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