So I have been searching for a way to get current location in java (not using any Android APIs) and something that is quite accurate. What I have so far is running an HTML file inside of Java and what I want to do is retrieve the GPS coordinates from a google API (html file).
What I have so far:
HtmlRun.java
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class HtmlRun {
public static void main(String[] args) throws IOException {
File htmlFile = new File("findLocation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
}
}
findLocation.html
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBTQzs7iZUtr7v-VbvAWhAql5LiQ9zZrFE&callback=initMap">
</script>
</body>
</html>
When I run this, it opens up my default app for html files and everything is sorted... but how could I retrieve the information I need? (GPS coordinates)
It occurs over here:
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
But I don't know how to retrieve that data back into my Java application.
This here:
public static void main(String[] args) throws IOException {
File htmlFile = new File("findLocation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
}
is just opening the html doc in a web browser, after that you have no control AT ALL about what is happening with the web content, the user can even click all the buttons/ pois in the map and you will never get access to that information.
What you need is a webserver that SERVES the content of that app, you can implement REST/full services or even WebSockets to exchange the data between Browser and server
Related
Does Eclipse Orion WebIDE support JSP? I am trying to create a simple application and jsp files are not working.
index.html
<html>
<head>
<script type="text/javascript" src="jquery-1.12.4.js"></script>
<script>
function getInput()
{
$.ajax({
type:"GET",
url: "./test.jsp",
success: function(success) {
console.log(success);
}
});
}
</script>
</head>
<body onload="getInput()">
test.jsp
<%#import="./javaMethod*"%>
<%javaMethod a = new javaMethod();
var value = a.initiate();
%>
<input type="hidden" id="test" value="<%=value%>">
javaMethod.java
public class javaMethod
{
public int initiate()
{
return 1;
}
}
This should add a hidden input field which will hold the value from the java method. However, it is not working and the jsp is just displaying as plain text.
This should add a hidden input field - no, this should log anything comes from test.jsp to the browser console. To add the output of the JSP to the body element, use $(document.body).append(success);.
I have the following Verticle class:
public class SendFileExample extends AbstractVerticle {
public void start(Future<Void> fut) throws Exception {
Router router = Router.router(vertx);
router.route("/hello").handler(StaticHandler.create("client"));
router.route("/hello").handler(routingContext -> {
HttpServerResponse response = routingContext.response();
System.out.println("Hello");
response.sendFile("client/index.html");
});
vertx.createHttpServer().requestHandler(router::accept).listen(3000,
result -> {
if (result.succeeded()) {
fut.complete();
} else {
fut.fail(result.cause());
}
}
);
}
}
My html file is:
<html>
<head>
<title> hello </title>
</heade>
<body>
<h1> Hello World </h1>
<button> Hello </button>
<script src="app.js"></script>
</body>
</html>
I used "StaticHandler.create..." in order to serve all static files inside client folder.
As you can understand, I want that once the server gets a GET request to "localhost:3000/hello", the client will get an HTML page, which will call app.js file.
Unfortunately, I can't do it. index.html is loaded and the browser can't load app.js.
It's important to note that index.html and app.js both are located exactly in the same path which is ${PROJECT_ROOT}/client.
The code, however, is located in:
${PROJECT_ROOT}/src/main/java/com/company.
You simply missed the star sign when you defined your static handler:
router.route("/hello*").handler(StaticHandler.create("client"));
Why don't you try something straight-forward like:
if (req.path().equals("/")) {
res.sendFile("client/index.html");
}else{
res.sendFile( "client" + req.path() );
}
I think that there is a problem with the JavaScript Java Bridge API in JxBrowser 6.1 . I have tried a very simple code to call a method of a java class in Javascript. Here are the codes. In java, java is set as a property on javascript window object to an instance of Events class and then the html is loaded. In html, I simply call Close method of Events class. But when I click the Close button, java Close function doesn't get called and there is a message in console from JxBrowser saying :
Uncaught TypeError: Cannot read property 'Close' of undefined
which means that java property for window object is not defined.
Main.java:
public class Main extends Application {
private Browser browser;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Platform.setImplicitExit(false);
browser = new Browser();
JSValue window = browser.executeJavaScriptAndReturnValue("window");
window.asObject().setProperty("java", new Events());
BrowserView browserView = new BrowserView(browser);
StackPane pane = new StackPane();
pane.getChildren().add(browserView);
Scene scene = new Scene(pane, 330, 470);
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.setScene(scene);
primaryStage.show();
browser.loadURL(Main.class.getResource("templates/simple.html").toExternalForm());
}
}
class Events {
public void Close() {
System.out.println("close button clicked");
}
}
simple.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<button id="Close">Close</button>
<script>
document.getElementById('Close').onclick = function () {
window.java.Close();
}
</script>
</body>
</html>
Here is the article i've used to do this:
https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013062-calling-java-from-javascript
Please correct me if i'm wrong.
Thanks in advance.
Please make sure that you load required web page before you access its JavaScript and register Java objects. For example:
browser.addLoadListener(new LoadAdapter() {
#Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
Browser browser = event.getBrowser();
JSValue value = browser.executeJavaScriptAndReturnValue("window");
value.asObject().setProperty("Account", new Account());
}
}
});
browser.loadURL("form.html");
I m doing one Java web application and i need to display image and text at same time from MySQL database.Please help me to display image and text on same "JSP" page from database.My image is stored as blob in MySQL.
You can define servlet which can send the image to user
http://www.javatpoint.com/example-to-display-image-using-servlet
Then define image retrieving from blob
http://codeglobe.blogspot.com/2009/03/readwrite-blob-fromto-mysql-in-java_21.html
In your jsp page just add link to the image
<img src="http://example.com/getImage?imageId=1234">
Thus when user clicks on the link your servlet will be called. The servlet reads the image from the BLOB and send it to the response.
UPDATE:
You can also try http://www.roseindia.net/tutorial/java/jsp/jspdisplayblob.html
That is not how HTML works.
The browser first requests the server to give it all the text content. Then the browser individually requests the server for image content, js content, css content etc. So you cannot "write" your image on the page using jsp, just how you write your texts, tables etc. An image needs to have a src "URL".
If you image content is coming from DB, then the URL needs to be a servlet. Which basically gets the image from DB, converts it into a stream and send back to the browser.
If you absolutely want that the text and the image to come from the same servlet, then maybe you can use request parameters...
here is a sample servlet and html. See if you can use similar style in your project
Servlet (This loads image from Disk. Change code to load from DB)
#WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
if(id!=null && "1".equalsIgnoreCase(id)){
response.setContentType("image/jpeg");
response.getOutputStream().write( Files.readAllBytes(new File(getServletContext().getRealPath("****.jpg")).toPath()));
response.getOutputStream().close();
}else {
response.getWriter().println("Sample text");
response.getWriter().close();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
}
}
HTML (Text is loaded via AJAX. You can use AJAX to load both text and image if you want)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function load()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("textDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Servlet2?id=2",true);
xmlhttp.send();
}
</script>
</head>
<body onload="load()">
<div id="textDiv"></div>
<br/>
<input type="image" src="http://localhost:8080/ImageCanvas/Servlet2?id=1"/>
</body>
</html>
I have a web page with an applet as the only element that looks something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>...</title>
</head>
<body>
<applet style="padding:1px; border:1px solid gray" mayscript="mayscript" codebase="..." name="AppletName" code="..." archive="..." width="600" height="500" alt="Alt Text">
<param name="initial_focus" value="true"/>
Alt Text
</applet>
</body>
</html>
When the page initially loads, focus is set in the applet and I can tab through and interact with the applet just fine. However, if I leave the browser window and then come back to it, I can no longer regain focus on the applet just using the tab key.
Pressing F5 to reload the page fixes the page so that the Applet regains focus, but this solution is unacceptable.
How do I solve this problem? Thanks.
Tentative solution:
//Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
window.onfocus = function() {
if(!document.AppletName.isActive())
document.AppletName.requestFocus();
};
}
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*#end #*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
Note that the key part for detecting whether the applet needs focus and requesting it if so is (this only works if mayscript is enabled):
if(!document.AppletName.isActive())
document.AppletName.requestFocus();
The rest of the code is just attaching the window on focus handling after the page is loaded (using the script JQuery.ready is based off of).
Better solutions welcome.