How to get input from Output tab in NetBeans - netbeans

I have an Output tab created and I would like to listen for user's input (to do a chat like component). Of course you can't predict when the user is going to type.
I found the org.jivesoftware.smack.util package and the related ObservableReader and ReaderListener that should do the trick, but I'm missing something and can't figure it out... yet.
Here's the code I have:
/*
* Enable/create the tabs we need for the component
*/
package sample.component;
import com.dreamer.outputhandler.OutputHandler;
import org.jivesoftware.smack.util.ObservableReader;
import org.jivesoftware.smack.util.ReaderListener;
import org.openide.modules.ModuleInstall;
/**
* Manages a module's lifecycle. Remember that an installer is optional and
* often not needed at all.
*/
public class Installer extends ModuleInstall implements ReaderListener {
private final String normal = "Output";
#Override
public void restored() {
OutputHandler.output(normal, "Welcome! Type something below.");
OutputHandler.setInputEnabled(normal, true);
ObservableReader reader = new ObservableReader(OutputHandler.getReader(normal));
reader.addReaderListener(this);
}
#Override
public void read(String read) {
System.out.println("Read: " + read);
OutputHandler.output(normal, "You typed: " + read);
}
}
OutPutHandler is a helper class I created to handle the output tabs. You can see its source here
Any idea?

Finally got it! It was a mix of the above code with this forum post and this classes: org.jivesoftware.smack.util.ObservableReader and org.jivesoftware.smack.util.ReaderListener. See the FAQ here

Related

How can I add language setting entries to existing CDT eclipse projects?

I am following the steps found here to try to add build settings to files in existing Eclipse CDT projects using the LanguageSettingsProvider extension point, but my settings provider doesn't seem to show in the UI, and its methods aren't queried for settings.
I previously succeeded in adding settings to a project using an external settings provider, but I couldn't find a way to add file-specific settings.
I have implemented a subclass of LanguageSettingsSerializableProvider (let's call it MyProvider), and added it to my plugin.xml thus:
<extension
point="org.eclipse.cdt.core.LanguageSettingsProvider">
<provider
class="com.example.MyProvider"
id="MyProvider_id"
name="I would like to see this in the UI">
<language-scope id="org.eclipse.cdt.core.gcc"/>
<language-scope id="org.eclipse.cdt.core.g++"/>
</provider>
</extension>
The class is implemented approximately thus:
public class MyProvider
extends LanguageSettingsSerializableProvider
implements ILanguageSettingsProvider,
IResourceChangeListener,
ILanguageSettingsEditableProvider,
ILanguageSettingsBroadcastingProvider {
/** The ID of this settings provider */
public static final String MY_PROVIDER_ID = "MyProvider_id"; //$NON-NLS-
/**
* Constructor. Initialises super class with appropriate values.
*/
public MyProvider() {
super( MY_PROVIDER_ID , Messages.UiLabel );
}
#Override
public String getId() {
return MY_PROVIDER_ID ;
}
#Override
public String getName() {
return Messages.UiLabel;
}
#Override
public List<ICLanguageSettingEntry> getSettingEntries(ICConfigurationDescription cfgDescription, IResource resource, String languageId) {
//breakpoint on this line that never gets hit...
return super.getSettingEntries( cfgDescription, resource, languageId );
}
...
}
The real implementation contains some other logic to actually create the settings entries, including registering itself as a resource change listener. The resourceChanged code works fine, calls setSettingsEntries, and then serializeSettings. However, getSettingEntries is never called to obtain these settings.
Is there something I'm missing?
My guess is the plugin.xml is lacking something, but I'm not sure what. There are paragraphs of guidance in the various interfaces that the class implements, but one simple working example would be worth more than a thousand words. I've tried looking at the xml for the built-in settings providers (e.g. GCCBuiltinCompilerSettingsMinGW), but they're defined alongside a lot of other parts of CDT, and it's hard to tell which bits are relevant to my use case.
What I ended up doing was:
someMethod {
final IProject myProject = getProjectFromSomewhere();
final ICProjectDescription projDesc = CoreModel.getDefault().getProjectDescription( myProject );
for (ICConfigurationDescription config : projDesc.getConfigurations()) {
try {
ensureMySettingsProvidedFor( (ILanguageSettingsProvidersKeeper) config );
} catch (ClassCastException e) {
logger.log( Level.WARNING, "Unexpected class was not a keeper of language settings:" + config.getClass().getName(), e );
}
}
}
/**
* Will ensure my settings provider is registered as a settings provider for...
* #param settingsKeeper ...the given configuration.
*/
public static void ensureMySettingsProvidedFor(final ILanguageSettingsProvidersKeeper settingsKeeper) {
if (settingsKeeper instanceof CConfigurationDescriptionCache) {
logger.log(Level.SEVERE, "Got non-writable cached settings. We can't update this!! "
+ "How do we get a writeable version?");
return;
}
for ( ILanguageSettingsProvider provider : settingsKeeper.getLanguageSettingProviders() ) {
if (MyProvider.MY_PROVIDER_ID.equals( provider.getId() )) {
return;
}
}
addMyProvider( settingsKeeper );
}
/**
* Adds my language settings provider to the given configuration by means of its ID.
* #param settingsKeeper The existing configuration.
*/
private static void addMyProvider( final ILanguageSettingsProvidersKeeper settingsKeeper ) {
List<String> ids = new ArrayList<String>();
for ( ILanguageSettingsProvider provider : settingsKeeper.getLanguageSettingProviders() ) {
ids.add( provider.getId() );
}
ids.add(MyProvider.MY_PROVIDER_ID);
List<ILanguageSettingsProvider> newProviders = LanguageSettingsManager.createLanguageSettingsProviders( ids.toArray( new String[ids.size()] ) );
settingsKeeper.setLanguageSettingProviders(newProviders);
}
It doesn't feel like the best answer, but it seems to work most of the time.
One problem is knowing when to do this such that it happens for all projects that don't yet have the provider, but doesn't get called repeatedly, or too often.
Another problem is that we sometimes get a CConfigurationDescriptionCache, and then the code can't do anything.
I'm open to better solutions.

Add sql comment with distributed tracing id globally on mybatis

Is there a cool way to add sql comment like below on Mybatis.
SELECT * FROM users; /* TraceID: foo-bar-baz */
I would like to add sql comment with TraceID/RequestID/CorrelationID in the context of distributed tracing to all executed sql.
This comment enables to identify a transaction from the comment of a slow query.
I found Interceptor API, but I seem that cannot add commnet.
I seem that we can use scripting like thymeleaf-scripting in this way.
But, We need to add sql comment in all sql...
Any advice will be appreciated.
In your case, a custom language driver might be a good fit.
Implementation
The below implementation is mostly the same as the default XMLLanguageDriver.
import org.apache.ibatis.builder.xml.XMLMapperEntityResolver;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.parsing.PropertyParser;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.TextSqlNode;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;
public class CommentLanguageDriver extends XMLLanguageDriver {
#Override
public SqlSource createSqlSource(Configuration configuration,
XNode script, Class<?> parameterType) {
// Append comment
script.getNode().setTextContent(
script.getNode().getTextContent() + getComment());
return super.createSqlSource(configuration, script,
parameterType);
}
#Override
public SqlSource createSqlSource(Configuration configuration,
String script, Class<?> parameterType) {
if (script.startsWith("<script>")) {
XPathParser parser = new XPathParser(script, false,
configuration.getVariables(), new XMLMapperEntityResolver());
return createSqlSource(configuration,
parser.evalNode("/script"), parameterType);
} else {
// Append comment
script = PropertyParser.parse(script + getComment(),
configuration.getVariables());
TextSqlNode textSqlNode = new TextSqlNode(script);
if (textSqlNode.isDynamic()) {
return new DynamicSqlSource(configuration, textSqlNode);
} else {
return new RawSqlSource(configuration, script, parameterType);
}
}
}
private String getComment() {
// OGNL expression invoking the static method
return " /* ${#org.slf4j.MDC#get(\"requestid\")} */";
}
}
The appended comment contains an OGNL expression invoking the static method.
This expression is evaluated at runtime.
Configuration
To register the custom language driver globally, you need to set defaultScriptingLanguage in the config.
<settings>
<setting name="defaultScriptingLanguage"
value="pkg.CommentLanguageDriver" />
</settings>
If you are using mybatis-spring-boot-starter, add the following line to your application.properties.
default-scripting-language-driver=pkg.CommentLanguageDriver

How to call Z-functions from a plugin on ImageJ

Good Morning
I'm currently doing a plugIn for ImageJ in JAVA that needs to call the function "Maximum Intensity Z-projection", which I know that is already in ImageJ if you go for "Image/Stacks/Z Project...". Documentation here: http://imagej.net/Z-functions#Maximum_Intensity_Z-projection
I know how to call plugins from another plugins, but doing the same thing in this case I get all the time my "Error" message.
public class Maximum_Intensity implements PlugIn{
ImagePlus img = WindowManager.getCurrentImage();
#Override
public void run(String arg0) {
// TODO Auto-generated method stub
Object ZProjector = null;
ZProjector = IJ.runPlugIn(img, "ZProjector", arg0);
if(ZProjector==null){
String arg = "Error";
IJ.showMessage(arg);
}
}
}
How can I do it? Thank you so much.
You can easily use the macro recorder for help to record all commands in ImageJ, see:
https://imagej.nih.gov/ij/docs/guide/146-31.html#sub:Record...
Enable Java for the recorder and then use the "Create" action to create an ImageJ plugin from the recorded interface actions.
In the following example (created with the Recorder) I applied the Max. Intensity function on a stack.
import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.*;
public class My_Plugin implements PlugIn {
public void run(String arg) {
ImagePlus imp = IJ.openImage("http://imagej.nih.gov/ij/images/mri-stack.zip");
IJ.run(imp, "Z Project...", "projection=[Max Intensity]");
imp.show();
}
}
The ZProjector class description can be found here (for instantiation):
https://imagej.nih.gov/ij/developer/api/ij/plugin/ZProjector.html

Load a ListBox content dynamically on page load

I'm currently working on a simple GWT project. One of the things I'd like to do is that when the page loads I can dynamically populate the contents of a ListBox based on certain criteria. I actually don't see any handlers for a ListBox to handle the initial render event but I see change handlers.
How does one populate a ListBox contents with data from the server side on pageload with GWT?
Right now I have a class that implements EntryPoint that has a
final ListBox fooList = new ListBox();
I also have a set of beans but I also have a class implementing RemoteService. Since I can't seem to get direct calls to my user defined packages directly in the EntryPoint (which makes sense) how do I populate that ListBox with server side content on initial page load? Right now I'm using a List but I figure if I cant get that to work I can get a DB call to work...
I've tried things in the EntryPoint like:
for (String name : FOOS) {
fooList.addItem(name, name);
}
However FOOS would derive from a server side data and the EntryPoint is supposed to be largerly limited to what can compile to JS! I can't get user defined classes to be recognized on that side as that string is the result of a set of user defined classes.
I also tried creating a method in the class implementing RemoteService that returns a ListBox. This also didn't compile when I tried to call this method. Perhaps I don't fully understand how to call methods in a RemoteService service implementing class.
I've searched a lot and I can't find anything that clearly explains the fundamentals on this. My background is much more ASP.NET and JSPs so perhaps I'm missing something.
I'm using GWT 2.6 is that is relevant.
The usual procedure is the following:
Create a bean class for the data you want to transmit between client and server. Let's call it MyBean.
Place MyBean in the shared package of your project.
This class has to implement either Serializable or IsSerializable, otherwise GWT will complain that it doesn't know how to transmit it.
Create your RemoteService that contains the method you want to use to transmit MyBean from/to the server.
Once you get your data on the client using an AsyncCallback and your RemoteService, fill the ListBox using your beans, e.g. by calling MyBean#getName() or MyBean#toString().
Success!
I based my example on the GWT sample project ( I named it example), just replace the classes and it should work :
public class Example implements EntryPoint {
/**
* Create a remote service proxy to talk to the server-side Greeting
* service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
final ListBox listBox = new ListBox();
RootPanel.get("sendButtonContainer").add(listBox);
greetingService.getSomeEntries(new AsyncCallback<String[]>() {
#Override
public void onSuccess(String[] result) {
for (int i = 0; i < result.length; i++) {
listBox.addItem(result[i]);
}
}
#Override
public void onFailure(Throwable caught) {
}
});
}
}
This is our EntryPoint, it creates a listbox and calls the server with a AsyncCallback to get some dynamic data. If the call is successfull (onSuccess), the data is written into the listbox.
The GreetingService interface define the synchronous methods, it is implemented in the GreetingServiceImpl class :
#RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String[] getSomeEntries() ;
}
The asynchronous counterpart is the GreetingServiceAsync interface, we used it before to call the server :
public interface GreetingServiceAsync {
void getSomeEntries(AsyncCallback<String[]> callback) ;
}
The GreetingServiceImpl class is located on the server. Here you could call for example a database:
#SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
#Override
public String[] getSomeEntries() {
String[] entries = { "Entry 1","Entry 2","Entry 3" };
return entries;
}
}
Now if you want to use some Bean/Pojo between the server and client, replace the String[] in each class/interface with the object name, put the class in the shared package and consider that it implements Serializable/IsSerializable.

Writing to stdout from an Eclipse plugin

My aim is to extend the eclipse QuickFix component and automate the process of solving syntax errors. Basically, the QuickFix component provides a list of solutions and my task is to select the best possible fix and apply it to the buggy code. But, for now I've been requested to print the resolutions for a marker in the console. I've tried to work out a tutorial and I'm kind of stuck right now. The tutorial I've tried to workout is: http://www.informit.com/articles/article.aspx?p=370625&seqNum=21
I've first added the extension in my plugin.xml file
<extension point="org.eclipse.ui.ide.markerResolution">
<markerResolutionGenerator
markerType="org.eclipse.core.resources.problemmarker"
class="org.eclipse.escript.quickfix.QuickFixer"/>
</extension>
Then i have created the two classes QuickFixer and QuickFix.
package quickfixer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.IMarkerResolutionGenerator;
class QuickFixer implements IMarkerResolutionGenerator {
public IMarkerResolution[] getResolutions(IMarker arg0) {
try {
Object problem = arg0.getAttribute("Whatsup");
return new IMarkerResolution[] {
new QuickFix("Fix #1 for "+problem),
new QuickFix("Fix #2 for "+problem),
};
} catch(CoreException e) {
return new IMarkerResolution[0];
}
}
}
then the class QuickFix:
package quickfixer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IMarkerResolution;
public class QuickFix implements IMarkerResolution {
String label;
QuickFix(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void run(IMarker arg0) {
MessageDialog.openInformation(null, "QuickFix Demo",
"This quick-fix is not yet implemented");
System.out.println("Label: " + label);
}
}
I've managed to correct all the errors i encountered and then i have run the plugin.
I have not been able to get the label printed out in the console.Any suggestions???...
Using System.out is not a good idea. Check the relevant FAQ on why
you should avoid using standard output or standard error in your
plug-in
and use proper logging (or the debugger).