I have a function that uses an org.eclipse.swt.widget.Display as a parameter. I use that project as a library for another project and call that function and use the same class, but my IDEs (eclipse and ItelliJ IDEA CE) are saying that the parameter is not expected.
What's wrong there?
Here is the Code:
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
startServer(port, getSession());
} catch (RmiException e) {
e.printStackTrace();
SWTErrorDialog.show(e, "Error while attaching JavaEngineServer to rmiregistry.exe", Display.getDefault());
}
return null;
}
});
Related
I would like to display a progress bar when running a custom IntentionAction in my custom IntellIJ IDEA plugin.
However, it is not displayed no matter what I do. To test whether the problem lies in the IntentionAction, I copy-paste the code to a simple implementation of an AnAction. The whole class looks like so:
public class HelloAction extends AnAction {
public HelloAction() {
super("Hello");
}
public void actionPerformed(AnActionEvent event) {
Project project = event.getData(CommonDataKeys.PROJECT);
ProgressManager.getInstance().run(new Task.Modal(project, "daf", false) {
public void run(ProgressIndicator indicator) {
indicator.setText("This is how you update the indicator");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
indicator.setFraction(0.5); // halfway done
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
}
});
Messages.showMessageDialog(project, "Hello world!", "Greeting", Messages.getInformationIcon());
}
}
And it works perfectly. And when I use the same code inside an IntentionAction, nothing is displayed.
public class GenerateIntentionAction extends PsiElementBaseIntentionAction implements IntentionAction {
...
public void invoke(#NotNull Project project, Editor editor, #NotNull PsiElement element) throws IncorrectOperationException {
ProgressManager.getInstance().run(new Task.Modal(project, "daf", false) {
public void run(ProgressIndicator indicator) {
indicator.setText("This is how you update the indicator");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
indicator.setFraction(0.5); // halfway done
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
}
});
I tried to run call runWithProgressSynchronously instead of run, tried making Task Modal and Backgroundable - to no avail. I do not know what is wrong besides the fact that ProgressIndicator inside IntentionAction is always an EmptyProgressIndicator
If your intention action is invoked inside WriteAction, you can't show modal UI from there. Overriding startInWriteAction and returning false might help.
I have the below code where I made a simple GUI. I would like Button2 to navigate to class 'Project2', which should start another piece of code. Just to note, in its current state, 'Project2' has no GUI, though I intend to add one soon. Anyway, this 'code jump' which I used by adding: String[] args = {};
Project2.main(args);
is not working, as the IDE says 'IOException must be caught or thrown'. I know how this works, though I am not sure how to implement it in the program.
Thanks in advance!
You can try to use dynamic class loading for your program. Below you can find lambda, which calls main method from com.stackoverflow.ExternalCaller class.
If you do not like to use lambda, you can create a simple anonymous class.
button.addActionListener(s -> {
try {
Class<?> externalCaller = Class.forName("com.stackoverflow.ExternalCaller");
Method main = externalCaller.getDeclaredMethod("main", new Class[]{String[].class});
main.invoke(null, new Object[]{new String[0]});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
});
ExternalCaller class in its turn looks something like that:
package com.stackoverflow;
public class ExternalCaller {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
In result once you click on the button you will get Hello World output in console.
If you would like to work with external jars etc. please look on Process class. Quick example:
Process proc = Runtime.getRuntime().exec("java -jar External.jar");
Or even more on fork/exec. You can read From Runtime.exec() to ProcessBuilder for more details.
Hope this will help. Good luck.
In most of the IDE's, when you right-click on the Button2 in the Design(GUI) pane, you can travel through:
Events -> Actions -> actionPerformed().
And write this code in the selected method to switch classes:
this.setVisible(false); //turns off the visibility of the current class
outputClass out = new outputClass(); //creating the object of the class you want to redirect to
out.setVisible(true);//turns on the visibility of the class you want to redirect to
In ImageJ , The Interface Plugin has a methods run() like this:
package ij.plugin;
/** Plugins that acquire images or display windows should
implement this interface. Plugins that process images
should implement the PlugInFilter interface. */
public interface PlugIn {
/** This method is called when the plugin is loaded.
'arg', which may be blank, is the argument specified
for this plugin in IJ_Props.txt. */
public void run(String arg);
}
why the run() method can be automatically called when the Plugin is loaded?
the run() method can be automatically called when the Plugin is loaded?
There is nothing automatic about it. There is a line of code in imagej library which says:
thePlugIn.run(arg);
The full snippet is this (from here):
/** Runs the specified plugin and returns a reference to it. */
public static Object runPlugIn(String commandName, String className, String arg) {
if (arg==null) arg = "";
if (IJ.debugMode)
IJ.log("runPlugIn: "+className+argument(arg));
// Load using custom classloader if this is a user
// plugin and we are not running as an applet
if (!className.startsWith("ij.") && applet==null)
return runUserPlugIn(commandName, className, arg, false);
Object thePlugIn=null;
try {
Class c = Class.forName(className);
thePlugIn = c.newInstance();
if (thePlugIn instanceof PlugIn)
((PlugIn)thePlugIn).run(arg);
else
new PlugInFilterRunner(thePlugIn, commandName, arg);
}
catch (ClassNotFoundException e) {
if (IJ.getApplet()==null)
log("Plugin or class not found: \"" + className + "\"\n(" + e+")");
}
catch (InstantiationException e) {log("Unable to load plugin (ins)");}
catch (IllegalAccessException e) {log("Unable to load plugin, possibly \nbecause it is not public.");}
redirectErrorMessages = false;
return thePlugIn;
}
For compatibility reasons, I have to adapt my Eclipse Plugin from JDT 3.7 to 3.6. Unfortunately, the old version doesn't seem to have the handy .getParameters() method yet.
I need to display an ElementTreeSelectionDialog to the user, allowing him to browse through methods of a class and select a parameter of a method. For this, I have written a ITreeContentProvider with this straightforward getChildren - method:
public Object[] getChildren(Object paramObject) {
if(paramObject instanceof ICompilationUnit){
ICompilationUnit icu = (ICompilationUnit) paramObject;
try {
return icu.getAllTypes()[0].getMethods();
} catch (JavaModelException e) {
e.printStackTrace();
}
}
if(paramObject instanceof IType){
IType type = (IType) paramObject;
try {
return type.getMethods();
} catch (JavaModelException e) {
e.printStackTrace();
}
}
if(paramObject instanceof IMethod){
IMethod method = (IMethod) paramObject;
try {
return method.getParameters();
} catch (JavaModelException e) {
e.printStackTrace();
}
}
return null;
}
I'd like to stick to the interfaces to be able to use the JavaUILabelProvider, which displays everything with proper icons, Signatures etc.
So the tricky part is to either create valid LocalVariable objects from the parameters or some other valid IJavaElement implementation, which would be displayed properly by JavaUILabelProvider.
I have tried creating an array of LocalVariable[], but this doesn't really work out, since I can't find any way to get the necessary position markers and Annotation objects for the elements...
There are some task that should't be done in parallel, (for example opening a file, reading, writing, and closing, there is an order on that...)
But... Some task are more like a shoping list, I mean they could have a desirable order but it's not a must..example in communication or loading independient drivers etc..
For that kind of tasks,
I would like to know a java best practice or pattern for manage exceptions..
The java simple way is:
getUFO {
try {
loadSoundDriver();
loadUsbDriver();
loadAlienDetectorDriver();
loadKeyboardDriver();
} catch (loadSoundDriverFailed) {
doSomethingA;
} catch (loadUsbDriverFailed) {
doSomethingB;
} catch (loadAlienDetectorDriverFailed) {
doSomethingC;
} catch (loadKeyboardDriverFailed) {
doSomethingD;
}
}
But what about having an exception in one of the actions but wanting to
try with the next ones??
I've thought this approach, but don't seem to be a good use for exceptions
I don't know if it works, doesn't matter, it's really awful!!
getUFO {
Exception ex=null;
try {
try{ loadSoundDriver();
}catch (Exception e) { ex=e; }
try{ loadUsbDriver();
}catch (Exception e) { ex=e; }
try{ loadAlienDetectorDriver();
}catch (Exception e) { ex=e; }
try{ loadKeyboardDriver()
}catch (Exception e) { ex=e; }
if(ex!=null)
{ throw ex;
}
} catch (loadSoundDriverFailed) {
doSomethingA;
} catch (loadUsbDriverFailed) {
doSomethingB;
} catch (loadAlienDetectorDriverFailed) {
doSomethingC;
} catch (loadKeyboardDriverFailed) {
doSomethingD;
}
}
seems not complicated to find a better practice for doing that.. I still didn't
thanks for any advice
Consider the execute around idiom.
Another option (which isn't really all that different, it just decouples them more) is to do each task in a separate thread.
Edit:
Here is the kind of thing I have in mind:
public interface LoadableDriver {
public String getName();
public void loadDriver() throws DriverException;
public void onError(Throwable e);
}
public class DriverLoader {
private Map<String, Exception> errors = new HashMap<String, Exception>();
public void load(LoadableDriver driver) {
try {
driver.loadDriver();
} catch (DriverException e) {
errors.put(driver.getName(), e);
driver.onError(e);
}
}
public Map<String, Exception> getErrors() { return errors; }
}
public class Main {
public void loadDrivers() {
DriverLoader loader = new DriverLoader();
loader.loadDriver(new LoadableDriver(){
public String getName() { return "SoundDriver"; }
public void loadDriver() { loadSoundDriver(); }
public void onError(Throwable e) { doSomethingA(); }
});
//etc. Or in the alternative make a real class that implements the interface for each driver.
Map<String, Exception> errors = loader.getErrors();
//react to any specific drivers that were not loaded and try again.
}
}
Edit: This is what a clean Java version would ultimately look like if you implemented the drivers as classes (which is what the Java OO paradigm would expect here IMHO). The Main.loadDrivers() method would change like this:
public void loadDrivers(LoadableDriver... drivers) {
DriverLoader loader = ...
for(LoadableDriver driver : drivers) {
loader.load(driver);
}
//retry code if you want.
Set<LoadableDriver> failures = loader.getErrors();
if(failures.size() > 0 && tries++ > MAX_TRIES) {
//log retrying and then:
loadDrivers(drivers.toArray(new LoadableDriver[0]));
}
}
Of course I no longer use a map because the objects would be self-sufficient (you could get rid of the getName() method as well, but probably should override toString()), so the errors are just returned in a set to retry. You could make the retry code even simpler if each driver was responsible for knowing how often it should it retry.
Java won't look as nice as a well done C++ template, but that is the Java language design choice - prefer simplicity over complex language features that can make code hard to maintain over time if not done properly.
Try this:
protected void loadDrivers() {
loadSoundDriver();
loadUsbDriver();
loadAlienDetectorDriver();
loadKeyboardDriver();
}
Then:
protected void loadSoundDriver() {
try {
// original code ...
}
catch( Exception e ) {
soundDriverFailed( e );
}
}
protected void soundDriverFailed( Exception e ) {
log( e );
}
This gives subclasses a chance to change the behaviour. For example, a subclass could implement loading each driver in a separate thread. The main class need not care about how the drivers are loaded, nor should any users of the main class.
IMO, for your case, if the exception is "ignorable" it's best if the "loadSoundDriver" method catches the exception and simply returns an error.
Then in the function that loads stuff, you can record all the errors and at the end of the sequence, decide what to do with them.
[edit]
Something like this:
// init
MyError soundErr = loadSoundDriver();
MyError otherErr = loadOtherDriver();
if(soundErr!=null || otherErr !=null){
// handle the error(s)
}
Just surround every single load operation with its own try / catch block.
try {
loadSoundDriver();
} catch (loadSoundDriverFailed) {
doSomethingA;
}
try {
loadUsbDriver();
} catch (loadUsbDriverFailed) {
doSomethingB;
}
// ...
So you can handle every exception by itself and continue processing the oder operations.