How to control conversion from Asciidoc to HTML - java

I'm in charge of conversion documents from Asciidoc format to HTML format in desktop application. I use AsciidoctorJ Java-wrapper library, like this:
Asciidoctor asciidoctor = Asciidoctor.Factory.create();
Options html = OptionsBuilder.options().
backend("html").
get();
asciidoctor.convertFile(
new File("test.asciidoc"),
html);
I would like to provide an ability to cancel the conversion, for example, when a user clicks "Cancel" button on UI of the application the conversion should stop. In order to keep UI responsive, I run the snipped depicted above in separate thread.
As far as I know, in Java thread can be stopped only in cooperative way. Methods like Thread.stop() are deprecated. And it seems that AsciidoctorJ doesn't provide an ability to cancel the conversion. Thus, org.asciidoctor.Asciidoctor.convertFile() (as well as other methods) doesn't return a kind of handler which can be used for controlling the conversion. There is only one method that is more-or-less suitable: org.asciidoctor.Asciidoctor.shutdown().
Documentation of the method claims:
This method frees all resources consumed by asciidoctorJ module. Keep in mind that if this method is called, instance becomes unusable and you should create another instance.
I'm afraid that shutting down the entire AsciidoctorJ is not good.
Is there better solution?

Related

Is there a way to specify in Java docs that a method should be called from a non-UI thread

I was writing a set of functions for accessing/writing data to the SQLite database in my android application. Since I need to use getWritableDatabase() to get the database instance and this needs to be called in a non-UI thread, I was wondering if there a clean way to specify the same warning in the java docs of these functions?
Also, I needed one more clarification about getting handle over the database instance using getWritableDatabase(). I should call this wherever I need to write things into database right? Or can I call this once at the application level and use the same handle to access db at different places in the app?
There are no fixed rules for such things. You can only rely on conventions/style.
In other words: try to come up with explicit, unambiguous wording and make sure that this part is easy to read and quick to spot in your javadoc (check the generated HTML as well for these properties).
And then be prepared for bug reports from people ignoring your javadoc.
Rather than just leaving a warning in the javadoc, you might add validation, i.e. detect if you're on the UI thread (see How to check if current thread is not main thread), then throw an exception.
Document that exception.

Event-driven programming - node.js, Java

I am coming from Java but have been doing some Node.js lately, and have been looking at the EventEmitter module in Node.
What I don't understand is the fundamental difference between Event-driven programming and 'regular' programming.
Here is some psuedo-code to demonstrate my idea of "event-driven" programming.
EventEmitter ee = new EventEmitter();
Function f = new SpecialFunction();
ee.on('grovel',f);
ee.emit('grovel'); //calls function 'f'
the only work the EventEmitter object seems to be doing is creating a hash relationship between the String representation of an event (in this case 'grovel') and a function to respond with. Seems like that's it, not much magic there.
however, my question is - how does event-driven programming really work behind the scenes with low-level events like mouse-clicks and typing? In other words, how do we take a click and turn it into a string (like 'grovel') in our program?
Okay. I will take a run at this.
There are a couple of major reasons to use event emitters.
One of the main reasons is that the browser, which is where JavaScript was born, sometimes forces you to. Whether you are wiring your events straight into your HTML, using jQuery or some other framework/library, or whatever, the underlying code is still basically the same (erm, basically...)
So first, if you want to react to a keyboard or mouse event, like you mentioned, you could just hard bind directly to an event handler (callback) like this:
<div onclick="myFunc(this)">Click me</div>
...or you could do the exact same thing in JS by DOM reference:
document.getElementById('my_element').onclick = function (evt) {
alert('You clicked me');
};
This used to be the primary way we wired up click handlers. One lethal drawback to this pattern is that you can only attach one callback to each DOM event. If you wanted to have a second callback that reacted to the same event, you would either need to combine write it into the existing click handler or build a delegate function to handle the job of calling the two functions. Plus, your event emitter ends up being tightly coupled to the event listener, and that is generally a bad thing.
As applications became more complex, it makes more sense to use event listeners, instead. Browser vendors (eventually) settled on a single way to do this:
// Build the handler
var myHandler = function (evt) {
alert('You clicked me too');
window.myHandlerRef = this; // Watch out! See below.
};
// Bind the handler to the DOM event
document.getElementById('my_element').addEventListener('click', myHandler);
The advantage to this pattern is that you can attach multiple handlers to a single DOM event, or call one single event handler from several different DOM events. The disadvantage is that you have to be careful not to leak: depending on how you write them, event-handling closures (like myHandler above) can continue to exist after the DOM element to which they were attached have been destroyed and GCed. This means it is good practice to always do a removeEventListener('click', myHandler). (Some libraries have an off() method that does the same thing).
This pattern works well for keyboard events as well:
var giveUserAHeadache = function (evt) {
alert('Annoying, isn\'t it?');
};
document.addEventListener('keypress', giveUserAHeadache);
Okay. So that is how you usually handle native browser events. But developers also like to use this pattern of event delegation in their own code. The reason you would want to do this is so you can decouple your code as much as possible.
For example, in a UI, you could have an event emitted every time the user's browser goes offline (you might watch navigator.onLine for example). Maybe you could have a green/red lamp on your page header to show the online state, and maybe you could disable all submit buttons when offline, and maybe also show a warning message in the page footer. With event listeners/emitters, you could write all of these as completely decoupled modules and they still can work in lock-step. And if you need to refactor your UI, you can remove one component (the lamp, for example), replace it with something else without worrying about screwing up the logic in some other module.
As another example, in a Node app you might want your database code to emit an error condition to a particular controller and also log the error -- and maybe send out an email. You can see how these sorts of things might get added iteratively. With event listeners, this sort of thing is easy to do.
You can either write your own, or you can use whatever pattern is available in your particular environment. jQuery, Angular, Ember and Node all have their particular methods, but you are free to also build your own -- which is what I would encourage you to try.
These are all variations of the same basic idea and there is a LOT of blur over the exact definition or most correct implementation (in fact, some might question if these are different at all). But here are the main culprits:
Observer
Pub-Sub
Mediator

Understanding Android's webview addjavascriptinterface

I know that to interact from Javascript to Java you have to inject a Java object using the addjavascriptInterface method in webview.
Here is the problem I am facing.
I register a java object using addJavascriptInterface method to be available in my JS.
I inject few JS in the webview using webview.loadURL("javascript:XXX");
I send a JS event when I am done with injecting the JS.
The problem is that if immediately after step 1, if I execute the following Javascript:
mWebView.loadUrl("javascript:if(window.myobject) console.log('myobject found---------'); else {console.log('myobject not found----');}");
I get "myobject not found" in my console's log.
I want to know that if there is some time before I can access my object and if so, how do I get to know how much time should I wait to call my object?
I want to know that if there is some time before i can access my object
Yes, I think there is a delay, because WebView.addJavascriptInterface will run in the WebView's internal worker thread. Perhaps you've thought about this, and realized that WebView has to maintain at least one worker thread to do asynchronous network IO. Maybe you also noticed these threads in DDMS while using a WebView.
It turns out that it also uses a thread to do work for a number of other public methods. I really wish the docs from Google made this clearer! But I hope I can help and show you how I tried to confirm this for myself.
Follow me as I take a look at the source for WebView. It's reasonably readable, even if you can't follow exactly what's going on, it's possible to trace through answer some questions with respect to threads.
You can download the Android framework source through the SDK manager tool, but it's also mirrored on Github, so that's what I've linked to here. I guessed and picked a tag that's close to some version of ICS. It's not hard to find WebView.addJavascriptInterface. I just Googled "WebView.java site:github.com/android".
The method WebView.addJavascriptInterface sends a message to an instance of WebViewCore:
mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
In WebViewCore.java there are a bunch of overloaded methods called sendMessage, but we don't really need to know which exactly is being called, since they do pretty much the same thing. There's even a nice comment to give us a hint that we're in the right place! All of them are delegating to an instance of EventHub which is some inner class. This method turns out to be synchronized, and is sending a message to an instance of Handler, which is a good indication that this is probably running in another thread, but for completeness sake, let's find out!
That Handler is instantiated in EventHub.transferMessages which is called from WebViewCore.initialize. There are a few more hops here, but eventually I found out that this is called from run in WebCoreThread (subclass of Runnable), which is instantiated along with a new Thread right here.
What an adventure! So, even though I really can't say for sure what's going on with all these moving parts, I am pretty confident to say that this method is not synchronous, and sends a message to the WebView's worker thread. I hope that makes sense!
if so, how do i get to know how much time should i wait to call my object?
Unfortunately, I don't know the answer to this. I was researching this exact issue and found this question on StackOverflow in the course of my Googling. I think you have the following options, some of which are nicer or easier than others:
1) Just Thread.sleep for 100 ms or something between addJavascriptInterface and loadUrl("javascript:..."). Blech, I don't like this, but it is potentially the easiest.
2) Another possibility is that you could call WebView.loadUrl with a snippet of JavaScript that specifically tests if the interface is set, and catches the ReferenceError that is thrown if it's not set yet. However, as you might have guessed, this kind of involves adding a JavaScript interface to the WebView!
3) Call WebView.setWebChromeClient instead, and catch JavaScript's alert() or console.log instead. From my experiments, this method is synchronous, so there is no delay. (I have confirmed this in source, but I'll leave details as an exercise for the reader) You should probably come up with some special string to call alert with and check for it inside onJsAlert, so you aren't just catching all alert()s.
Sorry for the length of this answer, I hope that helps. Good luck!
Ensure your Javascript objects declared in your HTML / Javascript that you need to access from Java are declared global otherwise they will most likely be collected. I have code that does this (where Android is my interface added with addJavascriptInterface):
<script>
var cb = function(location) {
alert('location is ' + location);
}
Android.getLocation('cb');
</script>
The getLocation method invokes Android's LocationManager.requestSingleUpdate which then invokes the callback when the LocationListener fires.
Without the "var" I find that by the time the location lookup invokes the callback the callback function has been garbage collected.
(copied from my response on a similar question)
I've taken Jason Shah's and Mr S's implementation as the building block for my fix and improved upon it greatly.
There's just far too much code to put into this comment I'll just link to it.
Details: http://twigstechtips.blogspot.com/2013/09/android-webviewaddjavascriptinterface.html
Source: https://github.com/twig/twigstechtips-snippets/blob/master/GingerbreadJSFixExample.java
Key points are:
Applies to all versions of Gingerbread (2.3.x)
Calls from JS to Android are now synchronous
No longer have to map out interface methods manually
Fixed possibility of string separators breaking code
Much easier to change JS signature and interface names

Questions: controlling a Swing GUI from an external class and separating logic from user interface

UPDATE: I'm using Netbeans and Matise and it's possible that it could be Matise causing the problems I describe below.
UPDATE 2: Thanks to those who offered constructive suggestions. After rewriting the code without Matise's help, the answer offered by ignis worked as he described. I'm still not sure how the code the Netbeans code generator interfered.
Though I've been programming in Java for awhile I've never done any GUI programming until now. I would like to control a certain part of my program externally (updating a jTextArea field with output from an external source) without requiring any user action to trigger the display of this output in the jTextArea.
Specifically, I want this output to begin displaying on startup and to start and stop depending on external conditions that have nothing to do with the GUI or what the user is doing. From what I understand so far you can trigger such events through action listeners, but these action listeners assume they are listening for user activity. If I must use action listeners, is there a way to trick the GUI into thinking user interaction has happened or is there a more straightforward way to achieve what I want to do?
Also, I'd really like to know more about best practices for separating GUI code from the application logic. From the docs I've come across, it seems that GUI development demands more of a messy integration of logic and user interface than, say, a web application where one can achieve complete separation. I'd be very interested in any leads in this area.
There is no need to use listeners. GUI objects are just like any other objects in the program, so actually
you can use the listener pattern in any part of the program, even if it is unrelated to the GUI
you can invoke methods of objects of the GUI whenever you want during the program execution, even if you do not attach any listeners to the objects in the GUI.
The main "rule" you must follow is that every method invocation performed on objects of the GUI must be run on the AWT Event Dispatch Thread (yes, that's true for Swing also).
http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
So you must wrap code accessing the GUI objects, into either
javax.swing.SwingUtilities.invokeLater( new Runnable() { ... } )
or
javax.swing.SwingUtilities.invokeAndWait( new Runnable() { ... } )
http://download.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html
About "separating GUI code from the application logic": google "MVC" or "model view controller". This is the "standard" way of separating these things. It consists in making the GUI code (the "view") just a "facade" for the contents (the "model"). Another part of the application (the "controller") creates and invokes the model and the view as needed (it "controls" program execution, or it should do that, so it is named "controller"), and connects them with each other.
http://download.oracle.com/javase/tutorial/uiswing/components/model.html
For example, a JFoo class in the javax.swing package, that defines a Swing component, acts as the view for one or more FooModel class or interface defined either under javax.swing or one of its subpackages. You program will be the "controller" which instantiates the view and an implementation of the model properly (which may be one of the default implementations found under those packages I mentioned, or a custom implementation defined among your custom packages in the program).
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/package-summary.html
That's a really good question, IMHO... one I asked a couple of years ago on Sun's Java Forums (now basically defunct, thanx to Oracle, the half-witted pack of febrile fiscal fascists).
On the front of bringing order to kaos that is your typical "first cut" of an GUI, Google for Swing MVC. The first article I read on the topic was JavaWorld's "MVC meets Swing". I got lucky, because it explains the PROBLEMS as well as proposes sane solutions (with examples). Read through it, and google yourself for "extended reading" and hit us with any specific questions arrising from that.
On the "simulated user activity" front you've got nothing to worry about really... you need only observe your external conditions, say you detect that a local-file has been updated (for instance) and in turn "raise" a notification to registered listener(s)... the only difference being that in this case you're implementing both the "talker" and the "listener". Swings Listener interface may be re-used for the messaging (or not, at your distretion). Nothing tricky here.
"Raising" an "event" is totally straight forward. Basically you'd just invoke the "EventHappened" method on each of the listeners which is currently registered. The only tricky bit is dealing with "multithreaded-ness" innate to all non-trivial Swing apps... otherwise they'd run like three-legged-dogs, coz the EDT (google it) is constantly off doing everything, instead of just painting and message brokering (i.e. what it was designed for). (As said earlier by Ignis) The SwingUtilies class exposes a couple of handy invoke methods for "raising events" on the EDT.
There's nothing really special about Swing apps... Swing just has a pretty steep learning curve, that's all, especially multithreading... a topic which I had previously avoided like the plague, as "too complicated for a humble brain like mine". Needless to say that turned out to be a baseless fear. Even an old idiot like myself can understand it... it just takes longer, that's all.
Cheers. Keith.
This doesn't exactly answer your question, but you might be interested in using Netbeans for Java GUI development. You can use GUI in Netbeans to do Java GUI development.
Here's a good place to get started -
http://netbeans.org/kb/trails/matisse.html

JSF Lifecycle and Custom components

There are a couple of things that I am having a difficult time understanding with regards to developing custom components in JSF. For the purposes of these questions, you can assume that all of the custom controls are using valuebindings/expressions (not literal bindings), but I'm interested in explanations on them as well.
Where do I set the value for the valuebinding? Is this supposed to happen in decode? Or should decode do something else and then have the value set in encodeBegin?
Read from the Value Binding - When do I read data from the valuebinding vs. reading it from submittedvalue and putting it into the valuebinding?
When are action listeners on forms called in relation to all of this? The JSF lifecycle pages all mention events happening at various steps, but its not completely clear to me when just a simple listener for a commandbutton is being called
I've tried a few combinations, but always end up with hard to find bugs that I believe are coming from basic misunderstandings of the event lifecycle.
There is a pretty good diagram in the JSF specification that shows the request lifecycle - essential for understanding this stuff.
The steps are:
Restore View. The UIComponent tree is rebuilt.
Apply Request Values. Editable components should implement EditableValueHolder. This phase walks the component tree and calls the processDecodes methods. If the component isn't something complex like a UIData, it won't do much except call its own decode method. The decode method doesn't do much except find its renderer and invokes its decode method, passing itself as an argument. It is the renderer's job to get any submitted value and set it via setSubmittedValue.
Process Validations. This phase calls processValidators which will call validate. The validate method takes the submitted value, converts it with any converters, validates it with any validators and (assuming the data passes those tests) calls setValue. This will store the value as a local variable. While this local variable is not null, it will be returned and not the value from the value binding for any calls to getValue.
Update Model Values. This phase calls processUpdates. In an input component, this will call updateModel which will get the ValueExpression and invoke it to set the value on the model.
Invoke Application. Button event listeners and so on will be invoked here (as will navigation if memory serves).
Render Response. The tree is rendered via the renderers and the state saved.
If any of these phases fail (e.g. a value is invalid), the lifecycle skips to Render Response.
Various events can be fired after most of these phases, invoking listeners as appropriate (like value change listeners after Process Validations).
This is a somewhat simplified version of events. Refer to the specification for more details.
I would question why you are writing your own UIComponent. This is a non-trivial task and a deep understanding of the JSF architecture is required to get it right. If you need a custom control, it is better to create a concrete control that extends an exisiting UIComponent (like HtmlInputText does) with an equivalent renderer.
If contamination isn't an issue, there is an open-source JSF implementation in the form of Apache MyFaces.
Action listeners, such as for a CommandButton, are called during the Invoke Application phase, which is the last phase before the final Render Response phase. This is shown in The JSF Lifecycle - figure 1.
It is the only framework that I've
ever used where component creation is
a deep intricate process like this.
None of the other web frameworks
(whether in the .net world or not)
make this so painful, which is
completely inexplicable to me.
Some of the design decisions behind JSF start to make a little more sense when you consider the goals. JSF was designed to be tooled - it exposes lots of metadata for IDEs. JSF is not a web framework - it is a MVP framework that can be used as a web framework. JSF is highly extensible and configurable - you can replace 90% of the implementation on a per-application basis.
Most of this stuff just makes your job more complicated if all you want to do is slip in an extra HTML control.
The component is a composition of
several inputtext (and other) base
components, btw.
I'm assuming JSP-includes/tooling-based page fragments don't meet your requirements.
I would consider using your UIComponentELTag.createComponent to create a composite control with a UIPanel base and creating all its children from existing implementations. (I'm assuming you're using JSPs/taglibs and making a few other guesses.) You'd probably want a custom renderer if none of the existing UIPanel renderers did the job, but renderers are easy.
The best article I've found is Jsf Component Writing,
as for 2 where do I read the value for a value binding in your component you have a getter that looks like this
public String getBar() {
if (null != this.bar) {
return this.bar ;
}
ValueBinding _vb = getValueBinding("bar");
return (_vb != null) ? (bar) _vb.getValue(getFacesContext()) : null;
}
how did this get into the getValueBinding?
In your tag class setProperties method
if (bar!= null) {
if (isValueReference(bar)) {
ValueBinding vb = Util.getValueBinding(bar);
foo.setValueBinding("bar", vb);
} else {
throw new IllegalStateException("The value for 'bar' must be a ValueBinding.");
}
}

Categories