chrome crash with method call of java in javascript - java

I am trying to use a java application in html5 and javascript, but Chrome always crashes when I try the following:
In the html5 document I have this:
<FORM>
<INPUT type="button" value="call JAVA" onClick = "test()">
</FORM>
<object name="application" type="application/x-java-applet" height="300" width="550" >
<param name="code" value="loader"/>
<param name="java_arguments" value="-Djnlp.packEnabled=true"/>
</object>
In the javascript file I use this function(the onclick test()-function)
function test() {
var app = document.getElementById("applet_test");
alert("Screen Dimension\r\n width:" +
app.getScreenWidth() + " height:" +
app.getScreenHeight() );
}
And finally this is the applet_test.java file:
import java.applet.*;
import java.awt.*;
public class applet_test extends Applet
{ public int getScreenWidth() {
return Toolkit.getDefaultToolkit().getScreenSize().width;
}
public int getScreenHeight() {
return Toolkit.getDefaultToolkit().getScreenSize().height;
}
public void main(String [] args) {
}
}
Does anybody know why this won't work? Eclipse is also complaining about the use of an applet in an html5-document:
Element (applet) is obsolete. Its use is discouraged in HTML5
Could this cause the troubles and if so, how can you get the same result with an element?

This works for me.
<!DOCTYPE html>
<html lang="en"><FORM>
<head>
<script>
function test() {
var app = document.applet_test;
alert("Screen Dimension\r\n width:" + app.getScreenWidth()
+ " height:" + app.getScreenHeight());
}
</script>
<body>
<INPUT type="button" value="call JAVA"
onClick = "test()">
</FORM>
<object name="applet_test" type="application/x-java-applet" height="300" width="550" >
<param name="code" value="loader.class"/>
</object>
</body>
</html>

Change var app = document.getElementById("applet_test"); to
var app = document.applet_test;
Eclipse is also complaining about the use of an applet in an html5-document.
Probably because the applet tag is deprecated. Look at bottom of
https://eyeasme.com/Shayne/HTML5_APPLETS/

Related

How to: Select date, Press Button, Create File, Download File in Struts 2

What I want:
If someone visits the page, could select two dates and click a (single) button for downloading the data between the two dates selected.
What I already have working:
JSP/web development is new for me. This is my scenario, using datepicker and JSP have a page that make a query to the database, return certain data between two dates, and create a .txt file with this data which saves locally.
Once the file is created, another button can be pressed to download the file.
What I need to work:
I need only one button who made both actions, so once the file is saved locally, a prompt for download appear and the visitor could make the download.
Because of how common the words are, it's hard to find what I need on search engines.
I need a button. I don't want links or anchors that looks like a button, this could be an easy matter for some folks, but I already have lost two days in
Info:
Apache Tomcat: 8.0.27 && Netbeans 8.1 && Ubuntu 14.04
JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<%#taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="resources/css/jtable.css" type="text/css">
<link rel="stylesheet" href="resources/css/style.css" type="text/css">
<link rel="stylesheet" href="resources/css/jquery-ui-1.10.3.custom.css" type="text/css">
<link href="resources/css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<script src="resources/js/jquery-1.11.3.js" type="text/javascript"></script>
<script src="resources/js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="resources/js/recuperacion-datos.js" type="text/javascript"></script>
<title></title>
<script>
$(document).ready(function(){
$("#datepicker1").datepicker({
maxDate: 0
});
$("#datepicker2").datepicker({
maxDate: 0,
onSelect: function(selected) {
$("#datepicker1").datepicker("option","maxDate", selected);
}
});
});
</script>
</head>
<body>
<center>
<div class="jtable-main-container" style="width: 60%;">
<div class="jtable-title">
<div class="jtable-title-text">
RecuperaciĆ³n de Datos
</div>
</div>
<div id="LecturasTableContainer" style="position: relative; text-align: center; font-size: 17px; top: 10px;">
Fecha Inicio: <input type="text" name="fechaInicio" id="datepicker1"> <span> </span><span> </span>
Fecha Fin: <input type="text" name="fechaFin" id="datepicker2">
<!-- Button who generate the file -->
<button type="submit" id="LoadRecordsButton" onclick="return confirm('Datos Recuperados');">Generar</button>
</div>
<br>
<!-- Button who download the file -->
<s:form action="download" method="POST">
<s:submit value="Descargar" type="button"/>
</s:form>
</div>
</center>
</body>
</html>
Action class for "Generar" Button:
package com.raspberry.struts.action;
import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionSupport;
import com.raspberry.dao.control.DBControl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DataRecovery extends ActionSupport implements ServletRequestAware {
public HttpSession session;
public Connection c;
public String fechaFin;// = null;
public String fechaInicio; // = null;
public String goDataRecovery(){
session.setAttribute("mainopt", "dataRecovery");
return SUCCESS;
}
public String doDataRecovery() throws ParseException, FileNotFoundException{
DBControl dato = new DBControl();
fechaInicio = getFechaInicio();
fechaFin = getFechaFin();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
String lectura = dato.selecAlltLecturasFecha(fechaInicio, fechaFin);
File archivo = new File ("/media/recovery"+fecha+".txt");
archivo.getParentFile().mkdirs();
PrintWriter printWriter;
printWriter = new PrintWriter(archivo);
printWriter.println (lectura);
printWriter.close ();
return SUCCESS;
}
public String getFechaFin() {
return fechaFin;
}
public String getFechaInicio() {
return fechaInicio;
}
#Override
public void setServletRequest(HttpServletRequest hsr) {
session = hsr.getSession();
}
}
Action Class for "Descargar" Button:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DownloadAction extends ActionSupport{
private InputStream fileInputStream;
public InputStream getFileInputStream() throws Exception {
return fileInputStream;
}
public String execute() throws Exception {
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
fileInputStream = new FileInputStream(new File ("/media/recovery"+fecha+".txt"));
return SUCCESS;
}
}
Struts.xml:
<action name="GetDataRecovery" class="com.raspberry.struts.action.DataRecovery"
method="doDataRecovery">
<interceptor-ref name="SessionValidationStack" />
<result name="success">main.jsp</result>
<result name="sessionexpired">index.jsp</result>
</action>
<action name="download" class="com.raspberry.struts.action.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="recovery.txt"</param>
<param name="bufferSize">1024</param>
</result>
</action>
If you have followed the example, you should see that he was using two actions. One action is mapped to the JSP page, and another is used to download. First one is used to return an actionless result (class attribute is missing). It's needed to access JSP page through the action. If you follow this technique - first action, second JSP, then you can use Struts2.
You can also share the same JSP among different actions that return this JSP as a result. If you want to share the same JSP for two or more actions you should add a result that contains the name/path to the file.
You can use action class properties (not for actionless results) to hold the state of the action scope objects accessible in JSP via OGNL/JSTL or JSP EL.
Elements of type "submit" you should use inside the form, otherwise use type "button" and use javascript to submit the form (it doesn't concern s:submit tag though).
in the DataRecovery action class you should create a property for download link or some boolean to indicate that download is ready. Just keep the name of the action "download". If the property has a value then display the button for download.
<s:if test="downloadReady">
<s:form action="download" method="POST">
<s:submit type="button" cssClass="btn btn-primary" value="Descargar" />
</s:form>
</s:if>
private boolean isDownloadReady = false;
//getters and setters
and set this variable after saving a file.
First of all, thanks to #user3659052 #BalusC #Tiny and #Roman C , for your comments. All were very helpfull.
I was very confused, so after the comments enlightenment, decide to first start with some tutorials and yesterday get the web app working.
After fixing the struts action for the "Download Button", I tried to generate the file also in the Descargar Action Class, but the query to database was null.
The mistake was the form ID on the datepicker was pointing Generar Action Class, so the Descargar Action Class never get the data. So after change the pointer to the "correct" action, was able to get the dates, create the file (locally) and downloading in one action. (So Generar Action Class was deleted)
Struts .xml (fragment)
<action name="DataRecovery" class="com.raspberry.struts.action.DownloadAction" method="goDataRecovery">
<interceptor-ref name="SessionValidationStack" />
<result name="success">main.jsp</result>
<result name="sessionexpired">index.jsp</result>
</action>
<action name="GetRecovery" class="com.raspberry.struts.action.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="recovery.txt"</param>
<param name="bufferSize">1024</param>
</result>
</action>
Descargar Action Class
package com.raspberry.struts.action;
import static com.opensymphony.xwork2.Action.SUCCESS;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import com.raspberry.dao.control.DBControl;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
public class DownloadAction extends ActionSupport implements ServletRequestAware {
public InputStream fileInputStream;
public HttpSession session;
public Connection c;
public String fechaFin;// = null;
public String fechaInicio; // = null;
public String goDataRecovery(){
session.setAttribute("mainopt", "dataRecovery");
return SUCCESS;
}
public InputStream getFileInputStream() throws Exception {
return fileInputStream;
}
public String doDataRecovery() throws ParseException, FileNotFoundException{
DBControl dato = new DBControl();
fechaInicio = getFechaInicio();
fechaFin = getFechaFin();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
String lectura = dato.selecAlltLecturasFecha(fechaInicio, fechaFin);
File archivo = new File ("/media/recovery"+fecha+".txt");
archivo.getParentFile().mkdirs();
PrintWriter printWriter;
printWriter = new PrintWriter(archivo);
printWriter.println (lectura);
printWriter.close();
return SUCCESS;
}
public String getFechaFin() {
return fechaFin;
}
public String getFechaInicio() {
return fechaInicio;
}
public String execute() throws Exception {
doDataRecovery();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
fileInputStream = new FileInputStream(new File ("/media/recovery"+fecha+".txt"));
return SUCCESS;
}
#Override
public void setServletRequest(HttpServletRequest hsr) {
session = hsr.getSession();
}
}
JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<%#taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="resources/css/jtable.css" type="text/css">
<link rel="stylesheet" href="resources/css/style.css" type="text/css">
<link rel="stylesheet" href="resources/css/jquery-ui-1.10.3.custom.css" type="text/css">
<link href="resources/css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<script src="resources/js/jquery-1.11.3.js" type="text/javascript"></script>
<script src="resources/js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="resources/js/recuperacion-datos.js" type="text/javascript"></script>
<title></title>
<script>
$(document).ready(function(){
$("#datepicker1").datepicker({
maxDate: 0
});
$("#datepicker2").datepicker({
maxDate: 0,
onSelect: function(selected) {
$("#datepicker1").datepicker("option","maxDate", selected);
}
});
});
</script>
</head>
<body>
<center>
<div class="jtable-main-container" style="width: 60%;">
<div class="jtable-title">
<div class="jtable-title-text">
RecuperaciĆ³n de Datos
</div>
</div>
<div style="position: relative; text-align: center; font-size: 17px; top: 10px;">
<s:form theme="simple" action="GetRecovery" method="POST" id="LecturasTableContainer">
Fecha Inicio: <input type="text" name="fechaInicio" id="datepicker1">
<span> </span><span> </span>
Fecha Fin: <input type="text" name="fechaFin" id="datepicker2">
<s:submit value="Descargar" id="LoadRecordsButton" type="button"/>
</s:form>
</div>
</div>
</center>
</body>
</html>
Once again thanks for the help.

Cannot call Play Framework static method from view

I have server and I should make request on button pressed also I have to call this method and when it is works I should parse json but my doesn't see controller method only main method is available
How to call
<input type="submit" onclick="#routes.Login.resp()" value="LOGIN" >
because it is not worrking Cannot resolve symbol
GET /login controllers.Login.main()
My controller:
package controllers;
import play.libs.F;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.Result;
public class Login extends Controller {
public static Result main() {
return ok(views.html.login.render());
}
public static F.Promise<Result> resp() {
String feedUrl="http://validate.jsontest.com/?json=%7B%22key%22:%22value%22%7D";
final F.Promise<Result> resultPromise = WS.url(feedUrl).get().flatMap(
new F.Function<WS.Response, F.Promise<Result>>() {
public F.Promise<Result> apply(WS.Response response) {
return WS.url(response.asJson().findPath("empty").asText()).get().map(
new F.Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("size" + response.asJson().findPath("count").asInt());
}
}
);
}
}
);
return resultPromise;
}
}
view:
<!--
Author: W3layouts
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/stylelogin.css")">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfonts-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:600italic,400,300,600,700' rel='stylesheet' type='text/css'>
<!--//webfonts-->
</head>
<body>
<!-----start-main---->
<div class="main">
<div class="login-form">
<h1>Member Login</h1>
<div class="head">
<img src="#routes.Assets.at("images/user.png")" alt=""/>
</div>
<form>
<input type="text" class="text" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'USERNAME';}" >
<input type="password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}">
<div class="submit">
<input type="submit" onclick="#routes.Login.main()" value="LOGIN" >
</div>
</form>
</div>
<!--//End-login-form-->
<!-----start-copyright---->
<!-----//end-copyright---->
</div>
<!-----//end-main---->
</body>
</html>
I am not sure if I also parse json properly,how to make proper GET,POST requests and parse it
As far as I know with the onclick attribute you always call a function in your JavaScript. If you want to specify an URL you need to put it into your form tag with an action attribute like <form action="#routes.Login.main()">.
The default for the HTML form tag is to send a GET. If you want to send a POST you have to specify it via an additional method="post" like <form action="#routes.Login.main()" method="post">. But then you have to change your routing too: POST /login controllers.Login.main(). If you want to post login data I'd strongly recommend to use POST because with GET your data including the password turns up in the query string of your URL.
Additionally your #routes.Login.main() method just returns the login view return ok(views.html.login.render());. Instead it should evaluate the form data you are sending.

How to send form object to Java in JavaFX WebView

I was able to send a simple String from javascript/local html in Webview to Java.
How do I send the whole form object to Java ?
public class JFXTest1 extends Application {
WebView webview = new WebView();
webview.getEngine().load(JFXTest1.class.getResource("local1.html").toExternalForm());
JSObject jsobj = (JSObject) webview.getEngine().executeScript("window");
Local1JSBridge bridge = new Local1JSBridge();
bridge.setWindow(jsobj);
jsobj.setMember("java", bridge);
And my bridge.
public class Local1JSBridge {
public void printFormData(String data1){
System.out.println( data1);
}
}
The javascript part that calls the method in the Java class.
<html>
<head></head>
<body>
hi :)
<form id="form1" name="form1">
<input type="text" id="text1">text value</input>
</form>
<button onclick="java.printFormData(document.getElementById('text1').value);">Submit</button>
<br/>
<button onclick="java.exit()">Exit</button>
</body>
I can't find a way to actually get the form data without executing Javascript back in the HTML document, but the following seems to basically work:
public void printFormData(Object form) {
System.out.println(form.getClass() + " " + form);
if (form instanceof Element) {
NodeList inputs = ((Element)form).getElementsByTagName("input");
for (int i = 0 ; i < inputs.getLength(); i++) {
Node input = inputs.item(i);
Element inputEl = (Element)input ;
String id = inputEl.getAttribute("id");
String value = (String) engine.executeScript(id+".value");
System.out.printf("%s : %s %n", id, value);
}
}
}
and then in the HTML:
<html>
<head></head>
<body>
hi :)
<form id="form1" name="form1">
<input type="text" id="text1">text value</input>
</form>
<button onclick="java.printFormData(document.getElementById('form1'));">Submit</button>
<br/>
<button onclick="java.exit()">Exit</button>
</body>
</html>

Flash external interface does nothing with javascript

My actionscript 2 code in my frame 1 (called main) is as follows:
import flash.external.ExternalInterface;
ExternalInterface.addCallback('getStr', getStr);
function getStr(): String {
return "Hello World!";
}
And here is how my javascript code is trying to call it:
<!DOCTYPE html>
<html>
<head>
<script>
function getStr() {
var swf = document.getElementById("GETSTRSWF");
var str = swf.gtStr();
alert(str);
return false;
}
</script>
</head>
<body>
Get Str
<object id="GETSTRSWF" type="application/x-shockwave-flash" data="getStr.swf" width="0" height="0">
<param name="movie" value="getStr.swf" />
<param name="allowscriptaccess" value="always" />
</object>
</body>
</html>
But I get this error, and it fails:
TypeError: swf.gtStr is not a function
var str = swf.gtStr();

appletviewr - getParameter returns null

I compile this code and use applet viewer for testing. But I see string "value: null" instead of "value: VALUE".
1) What did I do wrong?
/* <applet code="Demo" width="100" height="100">
<param name="name1" value="VALUE">
</applet>
*/
import java.applet.*;
import java.awt.*;
public class Demo extends Applet
{
String str=null;
public void init()
{
str=getParameter("name1");
}
public void paint(Graphics g)
{
g.drawString("value: "+str,100,50);
}
}
But if I open HTML file which is located in same folder with Demo.class
<html>
<body>
<applet code=Demo.class width="200" height="200" >
<param name="name1" value="VALUE">
</applet>
</body>
</html>
I get desired output "value: VALUE". (However for this result I should kill process java.exe, otherwise I get non-updated applet although Demo.class was updated).
2) Why won't the applet update until I will the java.exe?
I am getting value: VALUE in the applet viewer here. But then that is after increasing the width of the applet element from 100 to 200 in the comment at the top of the source. Thinner than that, and the text becomes truncated.

Categories