Repository: dpdearing/android-gps-emulator Branch: master Commit: f9c416329fab Files: 23 Total size: 44.3 KB Directory structure: gitextract_seoxq25r/ ├── .gitignore ├── LICENSE ├── README.md ├── lib/ │ └── gwt-maps-1.1.0.jar ├── pom.xml ├── repo/ │ └── de/ │ └── mud/ │ └── jta/ │ ├── 2.6/ │ │ ├── jta-2.6.jar │ │ ├── jta-2.6.jar.md5 │ │ ├── jta-2.6.jar.sha1 │ │ ├── jta-2.6.pom │ │ ├── jta-2.6.pom.md5 │ │ └── jta-2.6.pom.sha1 │ ├── maven-metadata.xml │ ├── maven-metadata.xml.md5 │ └── maven-metadata.xml.sha1 └── src/ └── main/ ├── java/ │ ├── Main.java │ └── com/ │ └── dpdearing/ │ └── sandbox/ │ └── gpsemulator/ │ ├── client/ │ │ └── GpsEmulator.java │ ├── common/ │ │ ├── EmulatorCommandException.java │ │ ├── EmulatorConnectionException.java │ │ └── LocationService.java │ └── server/ │ └── LocationServiceImpl.java ├── resources/ │ └── com/ │ └── dpdearing/ │ └── sandbox/ │ └── gpsemulator/ │ └── GpsEmulator.gwt.xml └── webapp/ ├── WEB-INF/ │ └── web.xml └── gpsemulator/ └── index.html ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .classpath .project .settings .idea *.iml war target google_maps_api_key ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ android-gps-emulator ==================== android-gps-emulator is a GPS location emulator for changing/setting/simulating the GPS location of the Android emulator through a simple map-based interface, using the geo fix command. Using GWT and Google Maps in combination with [JTA (Java telnet support)](http://javassh.org/space/start), this is a simple tool for emulating the geospatial (GPS) location of your local android emulator using the telnet geo fix command. **NOTE:** You must have a Google account _with billing enabled_ to generate an API key for the Google Maps JavaScript API. See Google's documentation at [Get API Key](https://developers.google.com/maps/documentation/javascript/get-api-key) Quick Start ----------- 1. Download the [latest release](https://github.com/dpdearing/android-gps-emulator/releases/latest) 2. Create a file named **`google_maps_api_key`** containing your API key 3. Run the executable war: **`java -jar android-gps-emulator-0.3.war`** 4. http://localhost:8080/gpsemulator/ ![android-gps-emulator](http://dpdearing.github.io/android-gps-emulator/img/android-gps-emulator.png) Running on a Different Port --------------------------- android-gps-emulator runs by default on port 8080. The port can be changed by passing the desired port as a parameter when running the executable war. For example, to run on port 9001:    **`java -jar android-gps-emulator-0.3.war 9001`** GWT Hosted Mode (from source) ----------------------------- 1. Clone the repository 2. Create a file named **`google_maps_api_key`** containing your API key 3. From the command line execute **`mvn gwt:run`** 4. Click `Launch Default Browser` from the GWT Development Mode ================================================ FILE: pom.xml ================================================ 4.0.0 com.dpdearing.sandbox android-gps-emulator war 0.4-SNAPSHOT Android GPS Emulator project.local file://${basedir}/./repo 2.8.0 9.2.14.v20151106 1.8 1.8 UTF-8 UTF-8 com.dpdearing.sandbox.gpsemulator.GpsEmulator gpsemulator com.google.gwt gwt ${gwt.version} import pom de.mud jta 2.6 com.google.gwt gwt-servlet runtime com.google.gwt gwt-user provided com.google.gwt gwt-dev provided com.google.gwt gwt-codeserver provided com.github.branflake2267 gwt-maps-api 3.10.0-alpha-7 org.eclipse.jetty jetty-webapp ${jetty.version} provided ${project.build.directory}/${project.build.finalName}/WEB-INF/classes org.codehaus.mojo gwt-maven-plugin ${gwt.version} compile generateAsync gwt-tests test test com.dpdearing.sandbox.gpsemulator 1.8 ${gwt.module.name}/index.html true true htmlunit **/Test*.java,**/*Test.java,**/*TestCase.java maven-surefire-plugin 2.17 true org.apache.maven.plugins maven-war-plugin 2.0.2 Main maven-antrun-plugin main-class-placement prepare-package run org.apache.maven.plugins maven-dependency-plugin 2.3 jetty-classpath prepare-package unpack-dependencies org.eclipse.jetty,javax.servlet,org.mortbay.jasper ${project.build.directory}/${project.artifactId}-${project.version} ================================================ FILE: repo/de/mud/jta/2.6/jta-2.6.jar.md5 ================================================ b47e203ccd4f3aae0c53e47052be9c68 ================================================ FILE: repo/de/mud/jta/2.6/jta-2.6.jar.sha1 ================================================ f278e7c4a3c0a43022a13766bb73c9d4339eb25a ================================================ FILE: repo/de/mud/jta/2.6/jta-2.6.pom ================================================ 4.0.0 de.mud jta 2.6 ================================================ FILE: repo/de/mud/jta/2.6/jta-2.6.pom.md5 ================================================ 08d96f8b61f9aa224c79c9fb0d92ef5a ================================================ FILE: repo/de/mud/jta/2.6/jta-2.6.pom.sha1 ================================================ 23277ac79f4fe7be4bcdb39e8232a8ef23f326ef ================================================ FILE: repo/de/mud/jta/maven-metadata.xml ================================================ de.mud jta 2.6 2.6 20140520044720 ================================================ FILE: repo/de/mud/jta/maven-metadata.xml.md5 ================================================ 1daa35267720b26493c6baa2a9284bd9 ================================================ FILE: repo/de/mud/jta/maven-metadata.xml.sha1 ================================================ ec44209de74ca4ebe675869a5aa3882983ae1cc8 ================================================ FILE: src/main/java/Main.java ================================================ /** * Copyright (c) 2014-17 David Dearing */ import java.net.URL; import java.security.ProtectionDomain; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.webapp.WebAppContext; /** * Embedded Jetty executable WAR main entry point. * * See http://uguptablog.blogspot.com/2012/09/embedded-jetty-executable-war-with.html */ public class Main { /** * @param args */ public static void main(String[] args) throws Exception { Server server = new Server(); HttpConfiguration config = new HttpConfiguration(); ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(config)); int port = 8080; if (args.length > 0) { port = Integer.parseInt(args[0]); } http.setPort(port); server.addConnector(http); ProtectionDomain domain = Main.class.getProtectionDomain(); URL location = domain.getCodeSource().getLocation(); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar(location.toExternalForm()); server.setHandler(webapp); server.start(); server.join(); } } ================================================ FILE: src/main/java/com/dpdearing/sandbox/gpsemulator/client/GpsEmulator.java ================================================ /** * Copyright (c) 2010-17 David Dearing */ package com.dpdearing.sandbox.gpsemulator.client; import com.dpdearing.sandbox.gpsemulator.common.LocationServiceAsync; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.maps.client.LoadApi; import com.google.gwt.maps.client.MapOptions; import com.google.gwt.maps.client.MapWidget; import com.google.gwt.maps.client.base.LatLng; import com.google.gwt.maps.client.events.click.ClickMapEvent; import com.google.gwt.maps.client.events.click.ClickMapHandler; import com.google.gwt.maps.client.overlays.Marker; import com.google.gwt.maps.client.overlays.MarkerOptions; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootLayoutPanel; import com.google.gwt.user.client.ui.TextBox; /** * Entry point classes define onModuleLoad(). */ public class GpsEmulator implements EntryPoint, ClickMapHandler { /** * The default emulator hostname port */ static private final String DEFAULT_HOST = "localhost"; static private final int DEFAULT_PORT = 5554; static private final String SUCCESS_STYLE = "success"; static private final String ERROR_STYLE = "error"; /** * Create a remote service proxy to talk to the server-side Location service. */ private final LocationServiceAsync _service = LocationServiceAsync.Util.getInstance(); /** * The map and current marker shown */ private MapWidget _map; private Marker _currentMarker = null; /** * The textboxes, button, and info label for configuring the host and port. */ private TextBox _hostname; private TextBox _port; private Button _button; private Label _info; /** * This is the entry point method. */ public void onModuleLoad() { GWT.setUncaughtExceptionHandler( new GWT.UncaughtExceptionHandler() { public void onUncaughtException(Throwable t) { GWT.log("Client-side uncaught exception", t); } } ); initializeUI(); loadMapApi(); } /** * Retrieve the Google Maps API key and load the API */ private void loadMapApi() { // retrieve the Google Maps API Key and then initialize the UI _service.getApiKey(new AsyncCallback() { @Override public void onFailure(Throwable caught) { setErrorMessage(caught.getLocalizedMessage()); } @Override public void onSuccess(String apiKey) { loadMapApi(apiKey); } }); } /** * Load the GWT Google Maps API using the provided API key. * * @param apiKey */ private void loadMapApi(String apiKey) { final StringBuilder otherParameters = new StringBuilder(); if (apiKey != null) { otherParameters.append("key="); otherParameters.append(apiKey); } GWT.log("LoadApi otherParameters: "+otherParameters.toString()); LoadApi.go(this::initializeMap, null, false, otherParameters.toString()); } /** * Initialize the Emulator UI */ private void initializeUI() { // Create textboxes and set default hostname and port _hostname = new TextBox(); _hostname.setText(DEFAULT_HOST); _hostname.getElement().setPropertyString("placeholder", "hostname"); _port = new TextBox(); _port.setText(String.valueOf(DEFAULT_PORT)); _port.getElement().setPropertyString("placeholder", "port"); // Create button to connect _button = new Button("Connect"); // Create the info/status label, initially not visible _info = new InlineLabel(); _info.setVisible(false); // register the button action _button.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { final String hostname = _hostname.getText(); final int port = Integer.valueOf(_port.getText()); new PortAsyncCallback(hostname, port).execute(); } }); // Create panel for textbox, button and info label final FlowPanel div = new FlowPanel(); div.setStylePrimaryName("emulator-controls"); _hostname.setStyleName("emulator-hostname"); _port.setStyleName("emulator-port"); _button.setStyleName("emulator-connect"); _info.setStyleName("emulator-info"); div.add(_hostname); div.add(_port); div.add(_button); div.add(_info); // add the controls before the map so that the div doesn't cover the map RootLayoutPanel.get().add(div); } /** * Initialize the Map widget and default zoom/position */ private void initializeMap() { // Create a map centered on Cawker City, KS USA final MapOptions opts = MapOptions.newInstance(); if (opts == null) { GWT.log("MapOptions was null"); } final LatLng center = LatLng.newInstance(30.0, 0.00); opts.setCenter(center); opts.setZoom(2); _map = new MapWidget(opts); // Register map click handler _map.addClickHandler(this); RootLayoutPanel.get().add(_map); } /** * Handle a map click event */ public void onEvent(ClickMapEvent clickMapEvent) { final LatLng point = clickMapEvent.getMouseEvent().getLatLng(); // set the location new GeoFixAsyncCallback(point.getLatitude(), point.getLongitude()).execute(); } /** * Create and add a new marker * * @param latitude * @param longitude * @return */ private Marker addMarker(double latitude, double longitude) { return addMarker(LatLng.newInstance(latitude, longitude)); } /** * Create and add a new marker * * @param point * @return */ private Marker addMarker(LatLng point) { MarkerOptions opts = MarkerOptions.newInstance(); opts.setMap(_map); opts.setPosition(point); return Marker.newInstance(opts); } /** * Clear the last-placed marker */ private void clearMarker() { if (_currentMarker != null) { _currentMarker.clear(); } } private void setSuccessMessage(String message) { _info.addStyleDependentName(SUCCESS_STYLE); _info.setText(message); _info.setVisible(true); } private void setErrorMessage(String message) { _info.addStyleDependentName(ERROR_STYLE); _info.setText(message); _info.setVisible(true); flash(); } private void clearMessage() { _info.setText(""); _info.removeStyleDependentName(ERROR_STYLE); _info.removeStyleDependentName(SUCCESS_STYLE); _info.setVisible(false); resetFlash(); } private void flash() { getFlashElement().addClassName("active"); } private void resetFlash() { getFlashElement().removeClassName("active"); } private Element getFlashElement() { return Document.get().getElementById("error-flash"); } /** * Asynchronous callback for setting the telnet port. */ private class PortAsyncCallback implements AsyncCallback, Command { private final String _hostname; private final int _port; /** * Constructor * * @param hostname the hostname * @param port the port */ public PortAsyncCallback(final String hostname, final int port) { _hostname = hostname; _port = port; } /** * Success! * * @param result void */ public void onSuccess(final Void result) { setSuccessMessage("Connected to " + _hostname + ":" + _port); } /** * Oh no! */ public void onFailure(final Throwable caught) { setErrorMessage("Error connecting to " + _hostname + ":" + _port + " - " + caught.getLocalizedMessage()); } /** * Execute service method */ public void execute() { // clear the marker and message when (re-)connecting clearMarker(); clearMessage(); _service.connect(_hostname, _port, this); } } /** * Asynchronous callback for changing the emulator's location */ private class GeoFixAsyncCallback implements AsyncCallback, Command { private final double _latitude; private final double _longitude; /** * Constructor. * * @param latitude * latitude * @param longitude * longitude */ public GeoFixAsyncCallback(final double latitude, final double longitude) { _latitude = latitude; _longitude = longitude; } /** * Success! * * @param result void */ public void onSuccess(final Void result) { // add the new marker _currentMarker = addMarker(_latitude, _longitude); setSuccessMessage("geo fix " + _longitude + " " + _latitude); } /** * Oh no! */ public void onFailure(final Throwable caught) { setErrorMessage("Error setting location: " + caught.getLocalizedMessage()); } /** * Execute service method */ public void execute() { // clear the marker and message before setting new location clearMarker(); clearMessage(); _service.setLocation(_latitude, _longitude, this); } } } ================================================ FILE: src/main/java/com/dpdearing/sandbox/gpsemulator/common/EmulatorCommandException.java ================================================ /** * Copyright (c) 2017 David Dearing */ package com.dpdearing.sandbox.gpsemulator.common; import com.google.gwt.user.client.rpc.IsSerializable; /** * A GWT-IsSerializable exception for unexpected events when sending a command to the android emulator. */ public class EmulatorCommandException extends Exception implements IsSerializable { public EmulatorCommandException() { super(); } public EmulatorCommandException(String message) { super(message); } } ================================================ FILE: src/main/java/com/dpdearing/sandbox/gpsemulator/common/EmulatorConnectionException.java ================================================ /** * Copyright (c) 2017 David Dearing */ package com.dpdearing.sandbox.gpsemulator.common; import com.google.gwt.user.client.rpc.IsSerializable; /** * A GWT-IsSerializable exception for unexpected events when making a connection to the android emulator. */ public class EmulatorConnectionException extends Exception implements IsSerializable { public EmulatorConnectionException() { super(); } public EmulatorConnectionException(String message) { super(message); } } ================================================ FILE: src/main/java/com/dpdearing/sandbox/gpsemulator/common/LocationService.java ================================================ /** * Copyright (c) 2010-17 David Dearing */ package com.dpdearing.sandbox.gpsemulator.common; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * The client side stub for the RPC service. */ @RemoteServiceRelativePath("location") public interface LocationService extends RemoteService { /** * Connect to the hostname and port * * @param hostname * the hostname * @param port * the port number * @throws EmulatorConnectionException */ void connect(String hostname, int port) throws EmulatorConnectionException; /** * Set the geospatial location * * @param latitude * latitude * @param longitude * longitude * @throws EmulatorCommandException */ void setLocation(double latitude, double longitude) throws EmulatorCommandException; /** * @return the Google Maps API Key * @throws EmulatorCommandException */ String getApiKey() throws EmulatorCommandException; } ================================================ FILE: src/main/java/com/dpdearing/sandbox/gpsemulator/server/LocationServiceImpl.java ================================================ /** * Copyright (c) 2010-17 David Dearing */ package com.dpdearing.sandbox.gpsemulator.server; import java.io.File; import java.io.IOException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import com.dpdearing.sandbox.gpsemulator.common.EmulatorCommandException; import com.dpdearing.sandbox.gpsemulator.common.EmulatorConnectionException; import com.dpdearing.sandbox.gpsemulator.common.LocationService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import de.mud.telnet.TelnetWrapper; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class LocationServiceImpl extends RemoteServiceServlet implements LocationService { private static Logger logger = Logger.getLogger(LocationServiceImpl.class.getName()); /** * The Google Maps API Key file */ final private File GOOGLE_MAPS_API_KEY_FILE = new File("google_maps_api_key"); /** * The telnet wrapper. */ final private TelnetWrapper _telnet; private Boolean _isTelnetActive = false; /** * The emulator authentication token */ private String _emulator_console_auth_token = null; /** * Constructor. */ public LocationServiceImpl() { _telnet = new TelnetWrapper(); //TODO does this work on all platforms? final String home = System.getProperty("user.home"); final File authTokenFile = new File(home, ".emulator_console_auth_token"); try { // read the entire contents of the file _emulator_console_auth_token = new Scanner(authTokenFile).useDelimiter("\\Z").next(); logger.info("Loaded emulator_console_auth_token " + _emulator_console_auth_token); } catch (IOException ioe) { logger.log(Level.SEVERE, "Failed to read the emulator_console_auth_token from " + authTokenFile.getAbsolutePath(), ioe); } } /** * {@inheritDoc} */ public void connect(final String hostname, final int port) throws EmulatorConnectionException { // disconnect from any previous connection try { _telnet.disconnect(); } catch (IOException ioe) { throw new EmulatorConnectionException(ioe.getMessage()); } _isTelnetActive = false; // connect to the specified host logger.info("Connecting to emulator at "+ hostname + ":" + port); try { _telnet.connect(hostname, port); _isTelnetActive = true; } catch (IOException ioe) { throw new EmulatorConnectionException(ioe.getMessage()); } if (_emulator_console_auth_token == null) { logger.info("No emulator_console_auth_token; skipping authentication"); } else { logger.info("Authenticating with emulator_console_auth_token: " + _emulator_console_auth_token); try { _telnet.send("auth " + _emulator_console_auth_token); } catch (IOException ioe) { throw new EmulatorConnectionException(ioe.getMessage()); } } } /** * {@inheritDoc} */ public void setLocation(final double latitude, final double longitude) throws EmulatorCommandException { if (_isTelnetActive) { try { // telnet the geo fix location: longitude first! String geo = "geo fix " + longitude + " " + latitude; logger.info("Sending command: " + geo); _telnet.send(geo); } catch (IOException ioe) { throw new EmulatorCommandException(ioe.getMessage()); } catch (Exception npe) { throw new EmulatorCommandException("Unexpected error within telnet connection."); } } else { // throw an exception or client will think that setLocation() was a success throw new EmulatorCommandException("Not connected to the emulator."); } } /** * {@inheritDoc} */ public String getApiKey() throws EmulatorCommandException { try { return loadGoogleMapsApiKey(); } catch (IOException ioe) { final String message = "Failed to read the Google Maps API Key from " + GOOGLE_MAPS_API_KEY_FILE.getAbsolutePath(); logger.log(Level.SEVERE, message, ioe); throw new EmulatorCommandException(message); } } private String loadGoogleMapsApiKey() throws IOException { // read the entire contents of the file logger.info("Reading Google Maps API Key file at " + GOOGLE_MAPS_API_KEY_FILE.getAbsolutePath()); final String apiKey = new Scanner(GOOGLE_MAPS_API_KEY_FILE).useDelimiter("\\Z").next(); logger.info("Loaded Google Maps API Key: " + apiKey); return apiKey; } } ================================================ FILE: src/main/resources/com/dpdearing/sandbox/gpsemulator/GpsEmulator.gwt.xml ================================================ ================================================ FILE: src/main/webapp/WEB-INF/web.xml ================================================ locationServlet com.dpdearing.sandbox.gpsemulator.server.LocationServiceImpl locationServlet /gpsemulator/location index.html ================================================ FILE: src/main/webapp/gpsemulator/index.html ================================================ Android GPS Emulator: Geospatial Location Emulation