Calling applet's method from JavaScript - javascript

I need to print some information via an applet.
My applet from signed qds-client.jar:
public class PrintText extends Applet implements Printable {
private ClientAccount clientAccount;
public ClientAccount getClientAccount() {
return clientAccount;
}
public void setClientAccount (ClientAccount clientAccount) {
this.clientAccount = clientAccount;
}
public void setClientAccountFromJSON(String json) {
this.clientAccount = toClientAccountFromJSON(json);
System.out.println("------------------------------SetClient");
}
public int print(Graphics g, PageFormat format, int page) throws
...
}
public void printText() throws PrinterException {
...
}
private String getTextToPrint(ClientAccount clientAccount) throws PrinterException {
...
}
private ClientAccount toClientAccountFromJSON(String json) {
return JsonUtils.fromJson(ClientAccount.class, json);
}
public void startPrint () {
System.out.println("------------------------------------------Start");
}
}
Accordinng JNLP:
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.5+" codebase="http://localhost:10099/partials/" href="print.jnlp">
<information>
....
</information>
<resources>
<jar href="/partials/qds-client.jar"/>
<jar href="/partials/core-3.2.1.jar"/>
<jar href="/partials/gson-2.3.1.jar"/>
</resources>
<applet-desc name="printText" main-class="com.qdsrest.utils.printer.PrintText" width="500" height="200"></applet-desc>
<update check="background"/>
<security>
<all-permissions/>
</security>
and HTML tag:
<applet name="printApplet" jnlp_href="/partials/print.jnlp" width="10" height="10">
<param name="permissions" value="all-permissions"/>
</applet>
When I call applet's method from js file like this:
document.printApplet.setClientAccountFromJSON({/not empty/});
I get
Error: Error calling method on NPObject!
in Mozilla and
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.CollectionTypeAdapterFactory: try again ..
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter: try again ..
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.MapTypeAdapterFactory: try again ..
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter: try again ..
basic: JNLP2ClassLoader.findClass: com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory: try again ..
in Java Console and method doesn't work. Why I get "try again .."? What does it mean?
Method toClientAccountFromJSON uses GSON lib gson-2.3.1.jar wich perfectly deserialize JSON object into Java object. What wrong things did I do? Tell me, please, a right thinking way.

I don't recall the current details, but long ago at the age of the first browser wars, there once was an attribute mayscript your applet needed in order to talk to javascript.
Oh and parameter needs to be string:
setClientAccountFromJSON("somestring or stringvar");

Related

zk zAu.send function - org.zkoss.zk.ui.event.MouseEvent cannot be cast to org.zkoss.zk.ui.event.ForwardEvent

I am integrating jquery and zk project.
My goal is to pass value from js/jquery side to java side but in vain.
Here is the code I reference: use zAu to send data from client to server
However, there exists the error:
java.lang.ClassCastException: org.zkoss.zk.ui.event.MouseEvent cannot be cast to org.zkoss.zk.ui.event.ForwardEvent
I have seen some other person saying that we must cast the mouseevent to forwardevent in order to get a NOT NULL getData() value.
At my java side:
public class TryHttpLenovo extends SelectorComposer<Component> {
#Listen("onClick=#btnHttp")
public void serverReceive(Event e) {
ForwardEvent forwardE = (ForwardEvent) e;
System.out.println("forwardE.getData()"+forwardE.getData());
}
}
In my http.zul:
<window apply="foo.TryHttpLenovo" xmlns:w="client">
<button id="btnHttp" w:onClick="sentToServer();">http send</button>
</window>
In my testhttp.js:
function sentToServer(){
var wgt=zk.Widget.$('btnHttp');
zAu.send(new zk.Event(wgt, "serverReceive", {foo: 'my data'}, {toServer:true}));
}
After several trial-and-error, I finally solve this!!!!
The solution is to extend GenericForwardComposer.
I also adjust some other things, but the only important change is to extend GenericForwardComposer instead of SelectorComposer.
The #Listen annotation is not needed in my solution.
in .java
public class TryHttpV2 extends GenericForwardComposer {
public void onUser2$info(Event event) {
ForwardEvent forwardE = (ForwardEvent) event;
System.out.println("forwardE.getOrigin().getData(): " + forwardE.getOrigin().getData());
}
}
in .js
function sendToServer(){
payload = "using generic composer";
zAu.send(new zk.Event(zk.Widget.$(this), 'onUser2', payload));
}
in .zul
<?page title="try using generic composer" contentType="text/html;charset=UTF-8"?>
<?script src="/js/tryhttp_v2.js" ?>
<zk xmlns="http://www.zkoss.org/2005/zul">
<window id="info" apply="foo.TryHttpV2" xmlns:w="client">
<button id="btnExec" w:onClick="sendToServer();" label="to be tested button" />
</window>
</zk>

How does sitecore's treeviewex get associated with the javascripts?

I am currently trying to create a control in sitecore much like the treeviewex.
But its unclear to me how I would go about including javascripts like sitecore does.
If someone could point me in the right direction I would appreciate that very much, thank you :)
/Robin
You can create your own processor and add it into the renderContentEditor pipeline. You can find info and code in this blog post about Adding custom Javascript and Stylesheets in the Content Editor
Create a new processor class:
public class InjectScripts
{
private const string JavascriptTag = "<script src=\"{0}\"></script>";
private const string StylesheetLinkTag = "<link href=\"{0}\" rel=\"stylesheet\" />";
public void Process(PipelineArgs args)
{
AddControls(JavascriptTag, "CustomContentEditorJavascript");
AddControls(StylesheetLinkTag, "CustomContentEditorStylesheets");
}
private void AddControls(string resourceTag, string configKey)
{
Assert.IsNotNullOrEmpty(configKey, "Content Editor resource config key cannot be null");
string resources = Sitecore.Configuration.Settings.GetSetting(configKey);
if (String.IsNullOrEmpty(resources))
return;
foreach (var resource in resources.Split('|'))
{
Sitecore.Context.Page.Page.Header.Controls.Add((Control)new LiteralControl(resourceTag.FormatWith(resource)));
}
}
}
And then patch in the processor:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<renderContentEditor>
<processor patch:before="*[1]" type="HideDependentFields.SC.Pipelines.RenderContentEditor.InjectScripts, HideDependentFields.Types" />
</renderContentEditor>
</pipelines>
</sitecore>
</configuration>

Action and ActionListener are not invoked for p:remoteCommand

I'm using p:remoteCommand,its working fine for update and process except its not invoking either action method nor actionListener
Xhtml Code
<h:form id="mainForm">
<h:outputLabel id="tempAge" value="#{remoteBean.tempAge}"/>
<h:inputText id="age" value="#{remoteBean.age}" onkeypress="callRem()">
<f:validateLongRange minimum="18"/>
</h:inputText>
<script type="text/javascript">
var timex=0;
function callRem(){
clearTimeout(timex);
timex = setTimeout("remote()",2000);
}
</script>
<p:remoteCommand name="remote"
process="age"
update="tempAge"
action="#{remoteBean.act}"
actionListener="#{remoteBean.listen}">
</p:remoteCommand>
</h:form>
Managed Bean Code
#ManagedBean
public class RemoteBean {
private int age=18;
private int tempAge=20;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
System.out.println("Setting age :"+age);
}
public int getTempAge() {
return tempAge;
}
public void setTempAge(int tempAge) {
this.tempAge = tempAge;
}
public void act(){
System.out.println("in action()");
tempAge+=age+2;
}
public void listen(ActionEvent event) {
System.out.println("in Action Listener");
tempAge+=age+2;
}
}
I can't figure out where I'm doing wrong, may be its the Javascript code i've written.
If anyone faces and solved same issue please help.
Using: Primefaces 3.5
I tried yours example and found problem.
Seemse when you processing only age (process="age"), it executes only age input and ignores remoteCommand actionListener and action.
So you can change it to:
process="#form"
or
process="#this age"
worked both for me.
ps. I used View scope here.

JavascriptResult puts javascript to the page as a string?

Iam a newbie of .NET MVC. I was trying to run all return types of MVC but I couldnt do work javascriptResult. The below is in my controller:
public ActionResult DoSomething() {
string s = "alert('Hello world!');";
return JavaScript(s);
}
This is in my view
#Ajax.ActionLink("click", "DoSomething", new AjaxOptions())
When I clicked the link, it puts "alert('Hello world!');" as a string and so not firing the alert. Whats wrong here ?
Seems that the documentation is "wrong" and the Controller.JavaScript action result is most likely only considered to return JavaScript include files (see also this thread):
Controller
public ActionResult JavaScript()
{
string s = "alert('Hello world!');";
return JavaScript(s);
}
View
<script type="text/javascript" src="~/Controller/JavaScript"></script>
If you want to return inline JavaScript you can use Controller.Content as your action result in combination with Html.RenderAction:
Controller
public ActionResult JavaScript()
{
string s = "alert('Hello world!');";
return Content(s);
}
View
<script type="text/javascript">
#{ Html.RenderAction("JavaScript", "Controller"); }
</script>

Display HTML and XML content on the same HTML page

I have a HTML page in which I have a button; pressing that button a javascript function is called - here results a String which is the representation of an xml. I want to represent this xml on the same page with the button, similar with what is in the picture below:!
Here is the simplified code I've tried but did not worked (see under the code the result of it - nothing displayed):
<html>
<head>
<script type="text/javascript">
function xml_test()
{
var xmlString = "<note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var my_div = document.getElementById("labelId");
alert(xmlString)
my_div.innerHTML += xmlString;
}
</script>
</head>
<body>
<input type="button" value="TEST" onclick="xml_test()"/>
<br><br>
<label id="labelId">XML: </label>
</body>
</html>
I've tried with an iframe also, but I do not have an file for the src attribute.
What I've tried is:
<html>
<head>
<script type="text/javascript">
function populateIframe() {
var xml = "<?xml version='1.0' encoding='UTF8' standalone='yes'?><note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var iframe = document.getElementById('myIframe');
var idoc= iframe.contentDocument || iframe.contentWindow.document; // IE compat
idoc.open("text/xml"); // I know idoc.open(); exists but about idoc.open("text/xml"); I'm not sure if exists;
idoc.write('<textarea name="xml" rows="5" cols="60"></textarea>');
//idoc.write(xml); // doesn't work
idoc.getElementsByTagName('textarea')[0].value= xml;
idoc.close();
}
</script>
</head>
<body onload="populateIframe();">
<iframe id="myIframe" width="900" height="400"></iframe>
</body>
</html>
and the result is:
I've already looked over How to display XML in a HTML page as a collapsible and expandable tree using Javascript?
I took some ideas from here
Thank you for helping me!
Just Create am HttpHandler, and open it in a Iframe:
public class Handler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
XmlSerializer serializer = new XmlSerializer(typeof(Note));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.Unicode);
serializer.Serialize(writer, new Note() { Name = "Kundan Sinha", Place = "Bangalore", State = "Karnataka" });
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding();
stream.Close();
writer.Close();
context.Response.ContentType = "text/xml;charset=utf-8";
context.Response.Write(utf.GetString(arr).Trim());
context.Response.Flush();
}
#endregion
}
public class Note
{
public string Name { get; set; }
public string Place { get; set; }
public string State { get; set; }
}
You can pass your received xml string to this where I am doing
context.Response.Write('Pass you XML data here');
You must use your favorite JavaScript library with a tree widget to display that XML in tree form.
Note that the "tree-like" view you see is actually IE's default view for XML files. Other browsers will have different views for XML files, and some do not even let you view XML files without a plug-in.
You should not depend on browser-specific functionality if viewing the XML in tree form is important to your page's functionality.
If you, however, just want to press a button and then the whole page gets turned into an XML, then by all means just redirect to that XML URI on button press. IE will show that XML file in tree form, while other browsers may either ask you to download the file, or display the XML file in whatever format that is determined by their plugin's.
I set the xml data in the src attribute:
iframeElement.setAttribute('src', 'data:text/xml,<test>data</test>');

Categories

Resources