I found on the internet a solution for Time failure issue(Without adding any random delay), but anytime I add it to my code got an error.
Here is the error:
Test Cases/Logging into account/Logging in - Right details FAILED because (of) (Stack trace: groovy.lang.MissingPropertyException: No such property: G_Timeout_Small for class: internal.GlobalVariable
at groovy.lang.MetaClassImpl.invokeStaticMissingProperty(MetaClassImpl.java:1004)
at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:1859)
at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:1835)
at groovy.lang.MetaClassImpl.getProperty(MetaClassImpl.java:3735)
at org.codehaus.groovy.runtime.callsite.ClassMetaClassGetPropertySite.getProperty(ClassMetaClassGetPropertySite.java:51)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:296)
at Script1543314158625.run(Script1543314158625.groovy:39)
at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:183)
at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:108)
at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:294)
at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:285)
at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:264)
at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:256)
at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:200)
at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:99)
at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:90)
at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:149)
at TempTestCase1543410680790.run(TempTestCase1543410680790.groovy:22)
at groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:263)
at groovy.lang.GroovyShell.run(GroovyShell.java:518)
at groovy.lang.GroovyShell.run(GroovyShell.java:507)
at groovy.ui.GroovyMain.processOnce(GroovyMain.java:653)
at groovy.ui.GroovyMain.run(GroovyMain.java:384)
at groovy.ui.GroovyMain.process(GroovyMain.java:370)
at groovy.ui.GroovyMain.processArgs(GroovyMain.java:129)
at groovy.ui.GroovyMain.main(GroovyMain.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
)
Test Cases/Logging into account/Logging in - Right details.run:39
Here is my code:
import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords as CucumberKW
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import internal.GlobalVariable as GlobalVariable
'Opening the browser.'
WebUI.openBrowser('')
'Importing account details from file.'
def plik = new File('Config.txt')
'Importing account details from file.'
def lines = plik.readLines()
WebUI.waitForPageLoad(0)
'Loading the page.'
WebUI.navigateToUrl(lines[0])
'Typing the account name.\n'
WebUI.setText(findTestObject('Logging into the account/account area'), lines[1])
'Typing the password'
WebUI.setText(findTestObject('Logging into the account/password area'), lines[2])
'Logging into the website with the logging button'
WebUI.click(findTestObject('Logging into the account/log button'), FailureHandling.STOP_ON_FAILURE)
WebUI.waitForPageLoad(GlobalVariable.G_Timeout_Small)
'Verifying wether logged or not.'
WebUI.verifyElementPresent(findTestObject('Logging into the account/main div after being logged'), 0)
'Closing the browser.'
WebUI.closeBrowser()
and place where I found it:
https://docs.katalon.com/katalon-studio/tutorials/solving_common_issue_wait_time.html
Anyone has any idea why there is that error ? In advance "Yes there is importe library for Global Variable.
You need to set initial value for GlobalVariable.G_Timeout_Small.
Go to execution profiles ("Profiles" at the top of the "Tests Explorer" on the right side of Katalon Sudio window) and set G_Timeout_Small to initial (number) value.
Related
I have some issues with javafx and org.controlsfx.control.textfield.TextFields. I'm trying to implement a feature that would get possible user input predictions from a database so that user can only pick the "authorized" options. While working with controlsfx I came across this error.
Error:
Exception in thread "JavaFX Application Thread" java.lang.IllegalAccessError: class org.controlsfx.control.textfield.AutoCompletionBinding (in unnamed module #0x239a4ba) cannot access class com.sun.javafx.event.EventHandlerManager (in module javafx.base) because module javafx.base does not export com.sun.javafx.event to unnamed module #0x239a4ba
at org.controlsfx.control.textfield.AutoCompletionBinding.<init>(AutoCompletionBinding.java:521)
at impl.org.controlsfx.autocompletion.AutoCompletionTextFieldBinding.<init>(AutoCompletionTextFieldBinding.java:107)
at impl.org.controlsfx.autocompletion.AutoCompletionTextFieldBinding.<init>(AutoCompletionTextFieldBinding.java:92)
at org.controlsfx.control.textfield.TextFields.bindAutoCompletion(TextFields.java:187)
at sample.Controller.lambda$listenKey$0(Controller.java:40)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$KeyHandler.process(Scene.java:4058)
at javafx.graphics/javafx.scene.Scene$KeyHandler.access$1500(Scene.java:4004)
at javafx.graphics/javafx.scene.Scene.processKeyEvent(Scene.java:2121)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2595)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$1(GlassViewEventHandler.java:248)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:390)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
at javafx.graphics/com.sun.glass.ui.View.handleKeyEvent(View.java:547)
at javafx.graphics/com.sun.glass.ui.View.notifyKey(View.java:971)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:834)
I've learnt that, quote Since Java Web Start is no longer a part of Java SE 11 and later, we will not look into this.. I don't know if it's because of that or I'm doing something wrong.
Here's my code:
package sample;
/**
* Sample Skeleton for 'sample.fxml' Controller Class
*/
import java.net.URL;
import java.util.*;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import org.controlsfx.control.textfield.TextFields;
public class Controller{
#FXML // ResourceBundle that was given to the FXMLLoader
private ResourceBundle resources;
#FXML // URL location of the FXML file that was given to the FXMLLoader
private URL location;
// fx:id="inputAutoComplete";
#FXML
private TextField inputAutoComplete;
#FXML // This method is called by the FXMLLoader when initialization is complete
void initialize() {
System.out.println("XD");
listenKey();
}
ArrayList<String> possibleWordSet = new ArrayList<>();
public void listenKey(){
databaseConnection dbconn = new databaseConnection();
inputAutoComplete.setOnKeyPressed((event) -> {
if(inputAutoComplete.getText().length() > 4){
System.out.println(inputAutoComplete.getText());
possibleWordSet = dbconn.getSuggestedData(inputAutoComplete.getText());
System.out.println(possibleWordSet);
TextFields.bindAutoCompletion(inputAutoComplete,possibleWordSet);
}
});
}
}
Can someone give me some examples of how to implement this feature or just tell what am I doing wrong?
If you are using ControlsFX 11, add the following VM option to your runtime command line:
--add-exports javafx.base/com.sun.javafx.event=org.controlsfx.controls
Note: Previous answers (on other sites and also here on SO) have suggested the following:
--add-exports javafx.base/com.sun.javafx.event=ALL-UNNAMED
However, recent versions of ControlFX appear to be modularized and the modules are no longer unnamed. If you are using a previous version (say, version 9), use the ALL-UNNAMED variant of the command line option.
If you ended up here and are using the maven plugin (javafx:run) to run your app, you can use the following configuration to get it running.
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.4</version>
<configuration>
<mainClass>some.package.App</mainClass>
<options>
<option>--add-exports</option>
<option>javafx.base/com.sun.javafx.event=org.controlsfx.controls</option>
</options>
</configuration>
</plugin>
I'm trying to write my first Pact-python test using pytest, Could someone please tell me what's wrong with my code?
import unittest
import requests
import json
import pytest
import atexit
from pact import Consumer, Provider
pact = Consumer('Consumer').has_pact_with(Provider('Provider'), host_name='mockservice', port=8080)
pact.start_service()
atexit.register(pact.stop_service)
class InterviewDetails(unittest.TestCase):
def test_candidate_report_api(self):
candidate_report_payload = {}
resp = requests.post("http://localhost:1234/users/",data=json.dumps(candidate_report_payload))
response = json.loads(resp.text)
return response
#pytest.mark.health1
def test_candidate_report(self):
expected = {}
(pact.given('Comment')
.upon_receiving('comment')
.with_request(method='POST', path="http://localhost:1234/users/", headers={})
.will_respond_with(200, body=expected))
with pact:
pact.setup()
result = self.test_candidate_report_api()
self.assertEqual(result, expected)
pact.verify()
The error from stacktrace:
AttributeError: module 'pact' has no attribute 'Like'
Can you please confirm you're using pact-python from https://github.com/pact-foundation/pact-python/ (and not pactman, a project that is not maintained by the Pact Foundation)?
It might be related to the way you have setup your test?
Here is an example project you can use for reference: https://github.com/pactflow/example-consumer-python/
Relevant test code:
"""pact test for product service client"""
import json
import logging
import os
import requests
from requests.auth import HTTPBasicAuth
import pytest
from pact import Consumer, Like, Provider, Term, Format
from src.consumer import ProductConsumer
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
print(Format().__dict__)
PACT_MOCK_HOST = 'localhost'
PACT_MOCK_PORT = 1234
PACT_DIR = os.path.dirname(os.path.realpath(__file__))
#pytest.fixture
def consumer():
return ProductConsumer(
'http://{host}:{port}'
.format(host=PACT_MOCK_HOST, port=PACT_MOCK_PORT)
)
#pytest.fixture(scope='session')
def pact(request):
pact = Consumer('pactflow-example-consumer-python').has_pact_with(
Provider('pactflow-example-provider-python'), host_name=PACT_MOCK_HOST, port=PACT_MOCK_PORT,
pact_dir="./pacts", log_dir="./logs")
try:
print('start service')
pact.start_service()
yield pact
finally:
print('stop service')
pact.stop_service()
def test_get_product(pact, consumer):
expected = {
'id': "27",
'name': 'Margharita',
'type': 'Pizza'
}
(pact
.given('a product with ID 10 exists')
.upon_receiving('a request to get a product')
.with_request('GET', '/product/10')
.will_respond_with(200, body=Like(expected)))
with pact:
user = consumer.get_product('10')
assert user.name == 'Margharita'
Have you ever had a problem with Play framework? In my case, first of all I have build all in one jar: spark-assebmly-1.2.0-hadoop2.4.0.jar, and Spark works perfectly from a shell. But there are two questions:
Should I use this assebmled Spark_jar in Play_project and how?? Because I try to move it into the lib_directiry and it did n`t help to provide any Spark_imports.
If I'm defining Spark library like: "org.apache.spark" %% "spark-core" % "1.2.0"
PLAY FRAMEWORK CODE:
Build.scala :
val appDependencies = Seq(
jdbc
,"org.apache.spark" %% "spark-streaming" % "1.2.0"
,"org.apache.spark" %% "spark-core" % "1.2.0"
,"org.apache.spark" %% "spark-sql" % "1.2.0"
TestEntity.scala :
package models
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.hadoop.conf.Configuration
import models.SparkMain
import org.apache.spark.rdd.RDD
import org.apache.spark.SparkContext._
object TestEntity {
val TestEntityPath = "/home/t/PROD/dict/TestEntity .txt"
val TestEntitySpark= SparkMain.sc.textFile(TestEntityPath, 4).cache
val TestEntityData = TestEntitySpark.flatMap(_.split(","))
def getFive() : Seq[String] = {
println("TestEntity.getFive")
TestEntityData.take(5)
}
}
SparkMain.scala :
package models
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.hadoop.conf.Configuration
import org.apache.spark.rdd.RDD
import org.apache.spark.SparkContext._
import org.apache.spark.streaming.{ Seconds, StreamingContext }
import StreamingContext._
import org.apache.spark.sql.SQLContext
import org.apache.spark.SparkConf
object SparkMain {
val driverPort = 8080
val driverHost = "localhost"
val conf = new SparkConf(false) // skip loading external settings
.setMaster("local[4]") // run locally with enough threads
.setAppName("firstSparkApp")
.set("spark.logConf", "true")
.set("spark.driver.port", s"$driverPort")
.set("spark.driver.host", s"$driverHost")
.set("spark.akka.logLifecycleEvents", "true")
val sc = new SparkContext(conf)
}
and controller code, which use Spark stuff :
def test = Action {
implicit req => {
val chk = TestEntity.getFive
Ok("it works")
}
}
..in runtime a have this errors:
[info] o.a.s.SparkContext - Spark configuration:
spark.akka.logLifecycleEvents=true
spark.app.name=firstSparkApp
spark.driver.host=localhost
spark.driver.port=8080
spark.logConf=true
spark.master=local[4]
[warn] o.a.s.u.Utils - Your hostname, uisprk resolves to a loopback address: 127.0.1.1; using 10.0.2.15 instead (on interface eth0)
[warn] o.a.s.u.Utils - Set SPARK_LOCAL_IP if you need to bind to another address
[info] o.a.s.SecurityManager - Changing view acls to: t
[info] o.a.s.SecurityManager - Changing modify acls to: t
[info] o.a.s.SecurityManager - SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(t); users with modify permissions: Set(t)
[error] application -
! #6l039e8d5 - Internal server error, for (GET) [/ui] ->
play.api.Application$$anon$1: Execution exception[[RuntimeException: java.lang.NoSuchMethodError: akka.util.Helpers$.ConfigOps(Lcom/typesafe/config/Config;)Lcom/typesafe/config/Config;]]
at play.api.Application$class.handleError(Application.scala:293) ~[play_2.10-2.2.3.jar:2.2.3]
at play.api.DefaultApplication.handleError(Application.scala:399) [play_2.10-2.2.3.jar:2.2.3]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$13$$anonfun$apply$1.applyOrElse(PlayDefaultUpstreamHandler.scala:166) [play_2.10-2.2.3.jar:2.2.3]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$13$$anonfun$apply$1.applyOrElse(PlayDefaultUpstreamHandler.scala:163) [play_2.10-2.2.3.jar:2.2.3]
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:33) [scala-library-2.10.4.jar:na]
at scala.util.Failure$$anonfun$recover$1.apply(Try.scala:185) [scala-library-2.10.4.jar:na]
Caused by: java.lang.RuntimeException: java.lang.NoSuchMethodError: akka.util.Helpers$.ConfigOps(Lcom/typesafe/config/Config;)Lcom/typesafe/config/Config;
at play.api.mvc.ActionBuilder$$anon$1.apply(Action.scala:314) ~[play_2.10-2.2.3.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:109) ~[play_2.10-2.2.3.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:109) ~[play_2.10-2.2.3.jar:2.2.3]
at play.utils.Threads$.withContextClassLoader(Threads.scala:18) ~[play_2.10-2.2.3.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:108) ~[play_2.10-2.2.3.jar:2.2.3]
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:107) ~[play_2.10-2.2.3.jar:2.2.3]
Caused by: java.lang.NoSuchMethodError: akka.util.Helpers$.ConfigOps(Lcom/typesafe/config/Config;)Lcom/typesafe/config/Config;
at akka.remote.RemoteSettings.<init>(RemoteSettings.scala:48) ~[akka-remote_2.10-2.3.4-spark.jar:na]
at akka.remote.RemoteActorRefProvider.<init>(RemoteActorRefProvider.scala:114) ~[akka-remote_2.10-2.3.4-spark.jar:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_72]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) ~[na:1.7.0_72]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.7.0_72]
at java.lang.reflect.Constructor.newInstance(Constructor.java:526) ~[na:1.7.0_72]
How to tie the library? through dependency or assembled_jar?
Any advice, please.
nosuchmethodeersrror exception is 100 % due to mismatch of jars version at compile time and runtime.
check the versions of jar. Also I have some questions about architecture of your app
Instead of calling spark code from play framework you can also call spark submit from shell scripts which looks better in your case. Even you can do it from your play application. no need to include jar in play app classpath.
The problem with the configuration is Akka dependency of Apache Spark and Play Framework -- they both depend on Akka and, as you've faced it, different and incompatible versions should be resolved at build time with evicted command in sbt.
You may want to use update command and find the reports in target/resolution-cache/reports quite useful.
I faced a problem in depolying JavaFX app in web and I got issue only with IE10 or IE9 and to be more precisely when the Document Mode is 9 , issue is that Browser cannot recognize the object 'app' which will be defined by JavaFx after being loaded . This object 'app' calls function 'tellme' with parameters. What I expect to see log on browser console: "____a OK maher", but what I get is an error message:
SCRIPT438: Object doesn't support property or method 'tellme'
Other info:
after launching Java there is prompt about publisher, permissions, see Image#1
just accept and go on.
Website requests access and control over JavaFx app ( there is JS <==> JavaFX ) and so there is a security warning about that and requests user to allow. see Image #2
Here I noted that in Document Mode IE9 I got this warning immediately after first one ..but on other browsers ( including DM IE8,DM IE7 ) its appearing after pressing clicl that means after calling JavaFx from JS via app.tellme
Again Issue only with IE, with other browser its OK ( Chrome, Opera, FF,.. etc ) also no issue with earlier versions of IE 7 and 8 ; briefly I have the problem only if IE document mode is set to IE9
This has nothing with Signing .. I have a valid sign code cert ..and surely I set correct permissions on manifest ( codebase, permissions, ...etc) but really this has nothing with this issue .. only 2nd warning disappears but issue still persists.
To simulate the issue:
1-Open main.html (codes below) with IE9 or IE10, press F12 to set Document Mode to IE 9.
2-press start, and accept to run that app, then accept the following prompt to allow accessing
JavaFx via JS.
3-press clicl, on browser console you will see the error message .. what I expected to solve this issue to see output :"____a OK maher"
codes:
main.java ( JavaFX app) :updated
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.im.oor;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
/**
*
* #author maher
*/
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
publishServices();
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
private static JSObject jsWin;
private void publishServices() {
try {
JSObject jsWins = getHostServices().getWebContext();
jsWins.setMember("app", new JavaAplicationCallBack());
} catch (Exception e) {
System.err.println("error with JSObject : "+e.getMessage());
}
}
public class JavaAplicationCallBack {
public String tellme(String uu) {
return "OK " + uu;
}
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
main.html (webpage):updated
<!DOCTYPE html>
<html>
<head>
<!--<meta http-equiv="X-UA-Compatible" content="IE=8">-->
<script src="web-files/dtjava.js" type="text/javascript" ></script>
<script src="jfx.js" type="text/javascript" ></script>
<script src="http://code.jquery.com/jquery-1.7.min.js">
</script>
<script>
$(document).ready(function() {
$("a.ll").live("click", function(event) {
callit('hi ');
});
});
</script>
</head>
<body>
<a href="#" onclick="launchit();" >start</a>
<a class='ll' href="#" >clicl</a>
<!-- Applet will be inserted here -->
<div id='javafx-app-placeholder'></div>
</body>
</html>
jfx.js ( javascript used on main.html ):updated
function javafxEmbed() {
dtjava.embed(
{
url : 'TestIdleCallJavaFx.jnlp',
//url: 'Testjfx.jnlp',
placeholder: 'javafx-app-placeholder',
width: 300,
height: 100,
jnlp_content: 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxqbmxwIHNwZWM9IjEuMCIgeG1sbnM6amZ4PSJodHRwOi8vamF2YWZ4LmNvbSIgaHJlZj0iVGVzdElkbGVDYWxsSmF2YUZ4LmpubHAiPg0KICA8aW5mb3JtYXRpb24+DQogICAgPHRpdGxlPlRlc3RJZGxlQ2FsbEphdmFGeDwvdGl0bGU+DQogICAgPHZlbmRvcj5NYWhlcjwvdmVuZG9yPg0KICAgIDxkZXNjcmlwdGlvbj5TYW1wbGUgSmF2YUZYIDIuMCBhcHBsaWNhdGlvbi48L2Rlc2NyaXB0aW9uPg0KICAgIDxvZmZsaW5lLWFsbG93ZWQvPg0KICA8L2luZm9ybWF0aW9uPg0KICA8cmVzb3VyY2VzPg0KICAgIDxqZng6amF2YWZ4LXJ1bnRpbWUgdmVyc2lvbj0iMi4yKyIgaHJlZj0iaHR0cDovL2phdmFkbC5zdW4uY29tL3dlYmFwcHMvZG93bmxvYWQvR2V0RmlsZS9qYXZhZngtbGF0ZXN0L3dpbmRvd3MtaTU4Ni9qYXZhZngyLmpubHAiLz4NCiAgPC9yZXNvdXJjZXM+DQogIDxyZXNvdXJjZXM+DQogICAgPGoyc2UgdmVyc2lvbj0iMS42KyIgaHJlZj0iaHR0cDovL2phdmEuc3VuLmNvbS9wcm9kdWN0cy9hdXRvZGwvajJzZSIvPg0KICAgIDxqYXIgaHJlZj0iVGVzdElkbGVDYWxsSmF2YUZ4LmphciIgc2l6ZT0iMjE3MTkiIGRvd25sb2FkPSJlYWdlciIgLz4NCiAgPC9yZXNvdXJjZXM+DQo8c2VjdXJpdHk+DQogIDxhbGwtcGVybWlzc2lvbnMvPg0KPC9zZWN1cml0eT4NCiAgPGFwcGxldC1kZXNjICB3aWR0aD0iODAwIiBoZWlnaHQ9IjYwMCIgbWFpbi1jbGFzcz0iY29tLmphdmFmeC5tYWluLk5vSmF2YUZYRmFsbGJhY2siICBuYW1lPSJUZXN0SWRsZUNhbGxKYXZhRngiID4NCiAgICA8cGFyYW0gbmFtZT0icmVxdWlyZWRGWFZlcnNpb24iIHZhbHVlPSIyLjIrIi8+DQogIDwvYXBwbGV0LWRlc2M+DQogIDxqZng6amF2YWZ4LWRlc2MgIHdpZHRoPSI4MDAiIGhlaWdodD0iNjAwIiBtYWluLWNsYXNzPSJvcmcuaW0ub29yLk1haW4iICBuYW1lPSJUZXN0SWRsZUNhbGxKYXZhRngiIC8+DQogIDx1cGRhdGUgY2hlY2s9ImFsd2F5cyIvPg0KPC9qbmxwPg0K'
//jnlp_content: 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxqbmxwIHNwZWM9IjEuMCIgeG1sbnM6amZ4PSJodHRwOi8vamF2YWZ4LmNvbSIgaHJlZj0iVGVzdGpmeC5qbmxwIj4NCiAgPGluZm9ybWF0aW9uPg0KICAgIDx0aXRsZT5UZXN0amZ4PC90aXRsZT4NCiAgICA8dmVuZG9yPm1haGVyPC92ZW5kb3I+DQogICAgPGRlc2NyaXB0aW9uPlNhbXBsZSBKYXZhRlggMi4wIGFwcGxpY2F0aW9uLjwvZGVzY3JpcHRpb24+DQogICAgPG9mZmxpbmUtYWxsb3dlZC8+DQogIDwvaW5mb3JtYXRpb24+DQogIDxyZXNvdXJjZXM+DQogICAgPGpmeDpqYXZhZngtcnVudGltZSB2ZXJzaW9uPSIyLjIrIiBocmVmPSJodHRwOi8vamF2YWRsLnN1bi5jb20vd2ViYXBwcy9kb3dubG9hZC9HZXRGaWxlL2phdmFmeC1sYXRlc3Qvd2luZG93cy1pNTg2L2phdmFmeDIuam5scCIvPg0KICA8L3Jlc291cmNlcz4NCiAgPHJlc291cmNlcz4NCiAgICA8ajJzZSB2ZXJzaW9uPSIxLjYrIiBocmVmPSJodHRwOi8vamF2YS5zdW4uY29tL3Byb2R1Y3RzL2F1dG9kbC9qMnNlIi8+DQogICAgPGphciBocmVmPSJUZXN0amZ4LmphciIgc2l6ZT0iMjAyODkiIGRvd25sb2FkPSJlYWdlciIgLz4NCiAgPC9yZXNvdXJjZXM+DQo8c2VjdXJpdHk+DQogIDxhbGwtcGVybWlzc2lvbnMvPg0KPC9zZWN1cml0eT4NCiAgPGFwcGxldC1kZXNjICB3aWR0aD0iMzAwIiBoZWlnaHQ9IjEwMCIgbWFpbi1jbGFzcz0iY29tLmphdmFmeC5tYWluLk5vSmF2YUZYRmFsbGJhY2siICBuYW1lPSJUZXN0amZ4IiA+DQogICAgPHBhcmFtIG5hbWU9InJlcXVpcmVkRlhWZXJzaW9uIiB2YWx1ZT0iMi4yKyIvPg0KICA8L2FwcGxldC1kZXNjPg0KICA8amZ4OmphdmFmeC1kZXNjICB3aWR0aD0iMzAwIiBoZWlnaHQ9IjEwMCIgbWFpbi1jbGFzcz0idGVzdGpmeC5UZXN0amZ4IiAgbmFtZT0iVGVzdGpmeCIgLz4NCiAgPHVwZGF0ZSBjaGVjaz0iYWx3YXlzIi8+DQo8L2pubHA+DQo='
},
{
javafx: '2.2+'
},
{}
);
}
function launchit(){
dtjava.addOnloadCallback(javafxEmbed);
}
function callit(aa){
alert(aa);
console.log("____ "+aa);
var ttt=app.tellme("maher ");
console.log("____a "+ttt);
}
Note that if you build code it may generate different jnlp_content that what I have. so just update it.
* I zipped all files into http://ulozto.cz/xV2vrQTd/javafx-dm-ie9-zip
* Source code is here : http://247workers.com/JFX_src/TestIdleCallJavaFx.zip
Here some steps how to successfully get it work:
1- I am using latest version of JDK/JRE 7u45
2- using Menu File ==> import ==> import from zip
3- Clean And Build
4-copy all content under dist in project into directory work and overwrite any thing if you already have something there.
5- it will be better to show Java Console during deploying via Control Panel ==> Java ==> Advanced ==> under Java console, choose show console.
About using
< meta http-equiv="X-UA-Compatible" content="IE=8">
to enforce using older rendering engine but this wont be accepted on our enterprise project Im working on.
I hope I will get assistance here ... sorry for long post but I wanted to be very specific and provide all necessary info .
This is due to a bug in the Java plugin. As far as I can tell there is no workaround and the bug is still present in Java 8.
For some reason in IE9 and IE10 (edge won't load Java at all for me) the toString() method is called on the object you want to expose to the browser. This is evident by using the developer tools to inspect app.
I've turned on debug for the browser and plugin (JPI_PLUGIN2_DEBUG=1 and JPI_PLUGIN2_VERBOSE=1) and I'm seeing some differences between IE8 and IE9 mode, but nothing showing me exactly where in the plugin code the object is being transformed to a String.
The next course of action is to try and override the plugin with a custom build to see where the problem is actually occurring. However, that may be more trouble than it's worth since it's already been determined the bug is in the plugin and there's no known workaround. In other words, even if a fix was found you probably couldn't deploy a patched version of Java to your enterprise customers. It looks like the only solution is to use a different browser or IE in documentMode 8 or less.
I've included some logs for completeness. Note: I changed the names of the jnlp and classes to mirror my environment, but the result is the same.
IE9 Console Log
NativeLibLoader: resolving loaded C:\Program Files (x86)\Java\jre8\bin\jp2iexp.d
ll
(Succeeded)
IExplorerPlugin.IExplorerPlugin(0x3aaefe8)
IExplorerPlugin.IExplorerPlugin(1.8.0)
NativeLibLoader: C:\PROGRA~2\Java\jre8\lib\bin\jp2native.dll doesn't exist
NativeLibLoader: trying to load C:\PROGRA~2\Java\jre8\bin\jp2native.dll
(Succeeded)
IExplorerPlugin.addParameters(cAxControl = 0x3aaefe8)
IExplorerPlugin.CreateControlWindow(cAxControl = 0x3aaefe8, hWndParent = 0x3071e
, hWndControlWindow = 0x1d0348)
IExplorerPlugin.SetObjectRects(cAxControl = 0x3aaefe8, left = 8, right = 308, to
p = 26, bottom = 126, appletID = null, activated = false)
{IExplorerPlugin.InPlaceActivate(cAxControl = 0x3aaefe8) entered
}IExplorerPlugin.InPlaceActivate(cAxControl = 0x3aaefe8) exited
IExplorerPlugin.SetObjectRects(cAxControl = 0x3aaefe8, left = 8, right = 308, to
p = 26, bottom = 126, appletID = null, activated = true)
Attempting to start applet
1 JavaFX runtime found.
1) JavaFX 8.0.0 found at C:\PROGRA~2\Java\jre8\
JVMLauncher.start: launcher params:
<-Djnlp.fx=8.0.0>
<-Xbootclasspath/a:C:\PROGRA~2\Java\jre8\lib\deploy.jar;C:\PROGRA~2\Java
\jre8\lib\javaws.jar;C:\PROGRA~2\Java\jre8\lib\plugin.jar>
<-Djava.class.path=C:\PROGRA~2\Java\jre8\classes>
<--->
<-->
<sun.plugin2.main.client.PluginMain>
<read_pipe_name=jpi2_pid2136_pipe2,write_pipe_name=jpi2_pid2136_pipe3>
JVMLauncher.start(): now - user.startApplet(): 14520 us
JVMLauncher.processArg[0]: C:\Program Files (x86)\Java\jre8\bin\jp2launcher.exe
JVMLauncher.processArg[1]: -D__jvm_launched=22791732422
JVMLauncher.processArg[2]: -D__applet_launched=22791717902
JVMLauncher.processArg[3]: -Djnlp.fx=8.0.0
JVMLauncher.processArg[4]: sun.plugin2.main.client.PluginMain
JVMLauncher.processArg[5]: read_pipe_name=jpi2_pid2136_pipe2,write_pipe_name=jpi
2_pid2136_pipe3
JVMLauncher.processArgs total len: 234, custArgsMaxLen: 8044
JVMLauncher.afterStart(): starting JVM process watcher
JVMInstance.start: JVMID original params array:
[0][0]: <-Djnlp.fx=8.0.0>
[0][1]: <-Xbootclasspath/a:C:\PROGRA~2\Java\jre8\lib\deploy.jar;C:\PROGR
A~2\Java\jre8\lib\javaws.jar;C:\PROGRA~2\Java\jre8\lib\plugin.jar>
[0][2]: <-Djava.class.path=C:\PROGRA~2\Java\jre8\classes>
[4][0]: <null>
JVMInstance for 1.8.0.ea sending start applet message
isRelaunch: false
appletLaunchTime: 22791717902
Parameters:
jnlp_href=Main.jnlp
launchjnlp=
code=dummy.class
java_status_events=true
type=application/x-java-applet
separate_jvm=true
javafx_version=2.2+
javafx_applet_id=dtjava-app-1
codebase=http://172.16.218.1/
width=300
name=dtjava-app-1
id=dtjava-app-1
scriptable=true
height=100
JVMInstance.registerApplet for applet ID 1, plugin sun.plugin2.main.server.IExpl
orerPlugin#44dec8
Received applet ID [AppletID 1]
JVMInstance (1.8.0.ea) processing GetProxyMessage
Delegate to plugin instance on browser main thread.
Browser main thread handle GetProxyMessage.
JVMInstance (1.8.0.ea) processing GetProxyMessage
Delegate to plugin instance on browser main thread.
Browser main thread handle GetProxyMessage.
JVMInstance (1.8.0.ea) processing CookieOpMessage
JVMInstance (1.8.0.ea) processing CookieOpMessage
JVMInstance (1.8.0.ea) processing StartAppletAckMessage with:
appletID: 1
JVMInstance (1.8.0.ea) processing StartAppletAckMessage with:
appletID: 1
JVMInstance (1.8.0.ea) processing JavaScriptGetWindowMessage
LiveConnectSupport: retained [BrowserSideObject 0x3ecd730] for applet 1
JVMInstance (1.8.0.ea) processing StartAppletAckMessage with:
appletID: 1
JVMInstance (1.8.0.ea) processing JavaScriptGetWindowMessage
JVMInstance (1.8.0.ea) processing JavaScriptEvalMessage
JVMInstance (1.8.0.ea) processing JavaScriptMemberOpMessage
LiveConnectSupport.sendRemoteJavaObjectOp: CALL_METHOD "toString"
AbstractPlugin.doJavaObjectOp starting to wait for result ID 1
JVMInstance (1.8.0.ea) processing JavaReplyMessage
JVMInstance received JavaReplyMessage with result ID 1
AbstractPlugin.doJavaObjectOp ending wait for result ID 1
LiveConnectSupport: result [ResultID 1] = JavaApplicationCallBack Test
JVMInstance for 1.8.0.ea sending release remote object message for ID 1
JVMInstance (1.8.0.ea) processing JavaScriptReleaseObjectMessage
JVMInstance (1.8.0.ea) processing JavaScriptReleaseObjectMessage
LiveConnectSupport: schedule release [BrowserSideObject 0x3ecd730] for applet
1
IE8 Console Log
NativeLibLoader: resolving loaded C:\Program Files (x86)\Java\jre8\bin\jp2iexp.d
ll
(Succeeded)
IExplorerPlugin.IExplorerPlugin(0x4c1efe8)
IExplorerPlugin.IExplorerPlugin(1.8.0)
NativeLibLoader: C:\PROGRA~2\Java\jre8\lib\bin\jp2native.dll doesn't exist
NativeLibLoader: trying to load C:\PROGRA~2\Java\jre8\bin\jp2native.dll
(Succeeded)
IExplorerPlugin.addParameters(cAxControl = 0x4c1efe8)
IExplorerPlugin.CreateControlWindow(cAxControl = 0x4c1efe8, hWndParent = 0xd04b4
, hWndControlWindow = 0x1a030a)
IExplorerPlugin.SetObjectRects(cAxControl = 0x4c1efe8, left = -9990, right = -96
90, top = 28, bottom = 128, appletID = null, activated = false)
{IExplorerPlugin.InPlaceActivate(cAxControl = 0x4c1efe8) entered
}IExplorerPlugin.InPlaceActivate(cAxControl = 0x4c1efe8) exited
IExplorerPlugin.SetObjectRects(cAxControl = 0x4c1efe8, left = -9990, right = -96
90, top = 28, bottom = 128, appletID = null, activated = true)
Attempting to start applet
1 JavaFX runtime found.
1) JavaFX 8.0.0 found at C:\PROGRA~2\Java\jre8\
JVMLauncher.start: launcher params:
<-Djnlp.fx=8.0.0>
<-Xbootclasspath/a:C:\PROGRA~2\Java\jre8\lib\deploy.jar;C:\PROGRA~2\Java
\jre8\lib\javaws.jar;C:\PROGRA~2\Java\jre8\lib\plugin.jar>
<-Djava.class.path=C:\PROGRA~2\Java\jre8\classes>
<--->
<-->
<sun.plugin2.main.client.PluginMain>
<read_pipe_name=jpi2_pid2740_pipe2,write_pipe_name=jpi2_pid2740_pipe3>
JVMLauncher.start(): now - user.startApplet(): 12763 us
JVMLauncher.processArg[0]: C:\Program Files (x86)\Java\jre8\bin\jp2launcher.exe
JVMLauncher.processArg[1]: -D__jvm_launched=25562522742
JVMLauncher.processArg[2]: -D__applet_launched=25562509979
JVMLauncher.processArg[3]: -Djnlp.fx=8.0.0
JVMLauncher.processArg[4]: sun.plugin2.main.client.PluginMain
JVMLauncher.processArg[5]: read_pipe_name=jpi2_pid2740_pipe2,write_pipe_name=jpi
2_pid2740_pipe3
JVMLauncher.processArgs total len: 234, custArgsMaxLen: 8044
JVMLauncher.afterStart(): starting JVM process watcher
JVMInstance.start: JVMID original params array:
[0][0]: <-Djnlp.fx=8.0.0>
[0][1]: <-Xbootclasspath/a:C:\PROGRA~2\Java\jre8\lib\deploy.jar;C:\PROGR
A~2\Java\jre8\lib\javaws.jar;C:\PROGRA~2\Java\jre8\lib\plugin.jar>
[0][2]: <-Djava.class.path=C:\PROGRA~2\Java\jre8\classes>
[4][0]: <null>
JVMInstance for 1.8.0.ea sending start applet message
isRelaunch: false
appletLaunchTime: 25562509979
Parameters:
jnlp_href=Main.jnlp
launchjnlp=
code=dummy.class
java_status_events=true
type=application/x-java-applet
separate_jvm=true
javafx_version=2.2+
javafx_applet_id=dtjava-app-1
codebase=http://172.16.218.1/
width=300
name=dtjava-app-1
id=dtjava-app-1
scriptable=true
height=100
JVMInstance.registerApplet for applet ID 1, plugin sun.plugin2.main.server.IExpl
orerPlugin#66906f
Received applet ID [AppletID 1]
JVMInstance (1.8.0.ea) processing GetProxyMessage
Delegate to plugin instance on browser main thread.
Browser main thread handle GetProxyMessage.
JVMInstance (1.8.0.ea) processing GetProxyMessage
Delegate to plugin instance on browser main thread.
Browser main thread handle GetProxyMessage.
JVMInstance (1.8.0.ea) processing CookieOpMessage
JVMInstance (1.8.0.ea) processing CookieOpMessage
JVMInstance (1.8.0.ea) processing StartAppletAckMessage with:
appletID: 1
JVMInstance (1.8.0.ea) processing StartAppletAckMessage with:
appletID: 1
JVMInstance (1.8.0.ea) processing JavaScriptGetWindowMessage
LiveConnectSupport: retained [BrowserSideObject 0x397ca24] for applet 1
JVMInstance (1.8.0.ea) processing StartAppletAckMessage with:
appletID: 1
JVMInstance (1.8.0.ea) processing JavaScriptGetWindowMessage
JVMInstance (1.8.0.ea) processing JavaScriptEvalMessage
JVMInstance (1.8.0.ea) processing JavaScriptMemberOpMessage
IExplorerPlugin.SetObjectRects(cAxControl = 0x4c1efe8, left = 10, right = 310, t
op = 28, bottom = 128, appletID = [AppletID 1], activated = true)
JVMInstance (1.8.0.ea) processing JavaScriptReleaseObjectMessage
JVMInstance (1.8.0.ea) processing JavaScriptReleaseObjectMessage
LiveConnectSupport: schedule release [BrowserSideObject 0x397ca24] for applet
1
Stacktrace of toString() being called in IE9
at Main$JavaAplicationCallBack.toString(Main.java:75)
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 sun.plugin.javascript.Trampoline.invoke(Unknown Source)
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 sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport.doObjectOp(Unknown Source)
at sun.plugin2.main.client.MessagePassingJSObject.waitForReply(Unknown Source)
at sun.plugin2.main.client.MessagePassingJSObject.doMemberOp(Unknown Source)
at sun.plugin2.main.client.MessagePassingJSObject.setMember(Unknown Source)
at Main.publishServices(Main.java:55)
at Main.start(Main.java:38)
at com.sun.javafx.applet.FXApplet2$2.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl$6$1.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl$6$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(Unknown Source)
at com.sun.glass.ui.win.WinApplication$4$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I haven't quite found the answer yet in other threads with similar titles. Let's say I have a logging.conf that looks like this:
[loggers]
keys=root,analyzer
[handlers]
keys=consoleHandler,analyzerFileHandler
[formatters]
keys=consoleFormatter,logFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler,analyzerFileHandler
[logger_analyzer]
level=DEBUG
handlers=consoleHandler,analyzerFileHandler
qualname=analyzer
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)
[handler_analyzerFileHandler]
class=FileHandler
level=DEBUG
formatter=logFormatter
args=('analyzer.log','w')
[formatter_consoleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s | %(message)s
datefmt=%m/%d/%Y %X
[formatter_logFormatter]
format=%(asctime)s - %(levelname)s | %(message)s
datefmt=%m/%d/%Y %X
A logger = logging.getLogger('analyzer') will send text to the log file and the console, how can I make that sys.stdout go towards a QPlainTextEdit() widget instead of the console?
edit
OK looking at this post I made this code. The post's code is good, but for some reason it doesn't address the issue, you can comment out all the instances of logger and still end up with print events going to Qwidget. The logger, as is, has no real interaction with the rest of the program, it is just there. I thought I could rectify the problem by writing a class that took whatever I wanted as text and sent it off to print and logger respectively:
import logging
from logging.config import fileConfig
from os import getcwd
import sys
from PyQt4.QtCore import QObject,\
pyqtSignal
from PyQt4.QtGui import QDialog, \
QVBoxLayout, \
QPushButton, \
QTextBrowser,\
QApplication
class XStream(QObject):
_stdout = None
_stderr = None
messageWritten = pyqtSignal(str)
def flush( self ):
pass
def fileno( self ):
return -1
def write( self, msg ):
if ( not self.signalsBlocked() ):
self.messageWritten.emit(unicode(msg))
#staticmethod
def stdout():
if ( not XStream._stdout ):
XStream._stdout = XStream()
sys.stdout = XStream._stdout
return XStream._stdout
#staticmethod
def stderr():
if ( not XStream._stderr ):
XStream._stderr = XStream()
sys.stderr = XStream._stderr
return XStream._stderr
class XLogger():
def __init__(self, name):
self.logger = logging.getLogger(name)
def debug(self,text):
print text
self.logger.debug(text)
def info(self,text):
print text
self.logger.info(text)
def warning(self,text):
print text
self.logger.warning(text)
def error(self,text):
print text
self.logger.error(text)
class MyDialog(QDialog):
def __init__( self, parent = None ):
super(MyDialog, self).__init__(parent)
# setup the ui
self._console = QTextBrowser(self)
self._button = QPushButton(self)
self._button.setText('Test Me')
# create the layout
layout = QVBoxLayout()
layout.addWidget(self._console)
layout.addWidget(self._button)
self.setLayout(layout)
# create connections
XStream.stdout().messageWritten.connect( self._console.insertPlainText )
XStream.stderr().messageWritten.connect( self._console.insertPlainText )
self.xlogger = XLogger('analyzer')
self._button.clicked.connect(self.test)
def test( self ):
# log some stuff
self.xlogger.debug("Testing debug")
self.xlogger.info('Testing info')
self.xlogger.warning('Testing warning')
self.xlogger.error('Testing error')
if ( __name__ == '__main__' ):
fileConfig(''.join([getcwd(),'/logging.conf']))
app = None
if ( not QApplication.instance() ):
app = QApplication([])
dlg = MyDialog()
dlg.show()
The "cross logger" sends everything to the log and to the Qwidget, however it also sends everything but debug to the aptana console:
02/05/2013 17:38:42 - analyzer - INFO | Testing info
02/05/2013 17:38:42 - analyzer - WARNING | Testing warning
02/05/2013 17:38:42 - analyzer - ERROR | Testing error
While the analyzer.log has:
02/05/2013 17:38:42 - DEBUG | Testing debug
02/05/2013 17:38:42 - INFO | Testing info
02/05/2013 17:38:42 - WARNING | Testing warning
02/05/2013 17:38:42 - ERROR | Testing error
Weird that debug is the only one who doesn't make it to the Aptana console, removing consoleHandler from handlers under [logger_analyzer] in my logging.conf solves the problem of it writing out to the Aptana console, probably has something to do with the args=(sys.stdout,) under [handler_consoleHandler]. I suppose it solves my problem without having to code in a handler for the Qtext object and thus negate the logging.conf file. If someone has a more elegant solution to using a logging.conf file that somehow manages to redirect its console output to a Qwidget of your choice, please feel free to post. Thanks.