Solved

script value (ScriptEngine)

Posted on 2009-07-01
6
441 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This article discusses how to create an extensible mechanism for linked drop downs.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…
Suggested Courses

627 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