add import to a groovy file from an eclipse plugin - java

I want to add some import statements in a groovy class via my plugin.
I m trying to do
compilationUnit.createImport(type.getFullyQualifiedName(), null, null);
where type is what i want to import. I get a null pointer exception. I
am using the same code for a Java class and it works.
Can somebody suggest me what could be wrong.
Thanks in advance!!

If you want to properly add an import to a file using proper APIs, then your best bet is to use greclipse.org.eclipse.jdt.core.dom.rewrite.ImportRewrite, which is a groovy-eclipse variant of a JDT class of the same name.
Look in org.codehaus.groovy.eclipse.refactoring.actions.OrganizeGroovyImports for an example of how to use it.
You can create it like this:
ImportRewrite rewriter = CodeStyleConfiguration.createImportRewrite(unit, false);
And then, add your import:
rewriter.addImport(qualifiedClassName);
And then do the rewrite:
TextEdit edit = rewriter.rewriteImports(null);
unit.applyTextEdit(edit, null);
Things are a little bit trickier if you want to add static, star, or aliased imports, but you can look at the code for that.

Related

Xamarin.Android Binding an AAR generated from Go - how to handle tuple returns?

I try to create a Xamarin.Android-Bindings Project for the following AAR:
https://jcenter.bintray.com/io/storj/libuplink-android/0.6/
It basically works. But the problem is that the included Java code got generated from Go-Code and it seems that all functions returning a tuple are not included in the binding. See this function:
https://github.com/storj/storj/blob/057d30152c80847a4edb0e7e91c31b012108b6ff/mobile/uplink.go#L65
This gets generated.
But the following does not (as it returns a tuple?):
https://github.com/storj/storj/blob/057d30152c80847a4edb0e7e91c31b012108b6ff/mobile/uplink.go#L44
Is this something a can overcome by specifying something in the metadata.xml? Anything else I can do?
Thank you!

How to know the Java interfaces an OpenOffice Calc UNO object supports (through queryInterface)

I'm developing a "macro" for OpenOffice Calc. As the language, I chose Java, in order to get code assistance in Eclipse. I even wrote a small ant build script that compiles and embeds the "macro" in an *.ods file. In general, this works fine and surprisingly fast; I'm already using some simple stuff quite successfully.
BUT
So often I get stuck because with UNO, I need to "query" an interface for any given non-trivial object, to be able to access data / call methods of that object. I.e., I literally need to guess which interfaces a given object may provide. This is not at all obvious and not even visible during Java development (through some sort of meta-information, reflection or the like), and also sparsely documented (I downloaded tons of stuff, but I don't find the source or maybe JavaDoc for the interfaces I'm using, like XButton, XPropertySet, etc. - XButton has setLabel, but not getLabel - what??).
There is online documentation (for the most fundamental concepts, which is not bad at all!), but it lacks many details that I'm faced with. It always magically stops exactly at the point I need to solve.
I'm willing to look at the C++ code to get a clue what interfaces an object (e.g. the button / event I'm currently stuck with) may provide. Confusingly, the C++ class and file names don't exactly match the Java interfaces. It's almost what I'm looking for, but then in Java I don't really find the equivalent, or calling queryInterface on a given object returns null.. It's becoming a bit frustrating.
How are the UNO Java interfaces generated? Is there some kind of documentation in the code that serves as the origin for the generated (Java) code?
I think I really need to know what interfaces are available at which point, in order to become a bit more fluent during Java-UNO-macro development.
For any serious UNO project, use an introspection tool.
As an example, I created a button in Calc, then used the Java Object Inspector to browse to the button.
Right-clicking and choosing "Add to Source Code" generated the following.
import com.sun.star.awt.XControlModel;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XNameAccess;
import com.sun.star.drawing.XControlShape;
import com.sun.star.drawing.XDrawPage;
import com.sun.star.drawing.XDrawPageSupplier;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
//...
public void codesnippet(XInterface _oUnoEntryObject){
try{
XSpreadsheetDocument xSpreadsheetDocument = (XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class, _oUnoEntryObject);
XSpreadsheets xSpreadsheets = xSpreadsheetDocument.getSheets();
XNameAccess xNameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, xSpreadsheets);
Object oName = xNameAccess.getByName("Sheet1");
XDrawPageSupplier xDrawPageSupplier = (XDrawPageSupplier) UnoRuntime.queryInterface(XDrawPageSupplier.class, oName);
XDrawPage xDrawPage = xDrawPageSupplier.getDrawPage();
XIndexAccess xIndexAccess = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class, xDrawPage);
Object oIndex = xIndexAccess.getByIndex(0);
XControlShape xControlShape = (XControlShape) UnoRuntime.queryInterface(XControlShape.class, oIndex);
XControlModel xControlModel = xControlShape.getControl();
XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xControlModel);
String sLabel = AnyConverter.toString(xPropertySet.getPropertyValue("Label"));
}catch (com.sun.star.beans.UnknownPropertyException e){
e.printStackTrace(System.out);
//Enter your Code here...
}catch (com.sun.star.lang.WrappedTargetException e2){
e2.printStackTrace(System.out);
//Enter your Code here...
}catch (com.sun.star.lang.IllegalArgumentException e3){
e3.printStackTrace(System.out);
//Enter your Code here...
}
}
//...
Python-UNO may be better than Java because it does not require querying specific interfaces. Also XrayTool and MRI are easier to use than the Java Object Inspector.

Is there any API in drools to create the drl files dynamically by just passing values?

I know how to create DRL files inside KIE workbench by using all the methods. But what my problem is without using the KIE workbench, can we create the .drl file by using our required values.If any possibility is there please suggest me. Same way suggest me any API is regarding to that. Thanks in advance.
You can use Drools Fluent API. Try below sample code :
package com.sample;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import org.drools.lang.DrlDumper;
import org.drools.lang.api.DescrFactory;
import org.drools.lang.descr.PackageDescr;
#SuppressWarnings("restriction")
public class Drl_Creator {
public static void main(String str[]){
PackageDescr pkg = DescrFactory.newPackage()
.name("org.drools.example")
.newRule().name("Xyz")
.attribute("ruleflow-grou","bla")
.lhs()
.and()
.pattern("Foo").id( "$foo", false ).constraint("bar==baz").constraint("x>y").end()
.not().pattern("Bar").constraint("a+b==c").end().end()
.end()
.end()
.rhs( "System.out.println();" ).end()
.getDescr();
DrlDumper dumper=new DrlDumper();
String drl=dumper.dump(pkg);
System.out.print(drl);
try{
// create new file
File file = new File("src/main/rules/test.drl");
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(drl);
// close connection
bw.close();
System.out.println("File Created Successfully");
}catch(Exception e){
System.out.println(e);
}
}
}
I interpret your question in two different ways.
1. Is it possible to write rules for Drools without using the KIE workbench?
Yes, it should support importing rules so all you need to do is open up a text editor and start typing. The rules are written as text using a fairly simple syntax that you can figure out in about 1-2 hours of reading. I do not know what your environment looks like but there should be a mechanism to parse and import a new rule. All rules you write will start out in a text editor looking like this:
rule "<name>"
<attribute>
when
<conditional element>
then
<action>
end
You will add to the conditions and actions. Of course you will have to know what conditions you can create which is limited to your environment and likewise for the actions.
2. Is it possible to create rules and use them programatically through some sort of API?
Yes, I do it all of the time for the processing we do using the Java API. We have 2 types of rules that we use, static and dynamic. The static ones have pre-canned conditions and are written to perform the same comparisons (LHS) over and over and performing the same actions each time the conditions are met (RHS). The dynamic ones are created on the fly based upon a minimalistic set of object types and comparisons (LHS) specified by the user when they are created. The actions (RHS) are pre-canned but are selected for use depending on the need for the overall rule use. The entire rule is created as text then passed to the Drools parser before being added to the list of rules to evaluate.
Hope this helps.
Another option is to use the "descr" APIs, starting from the factory:
org.drools.compiler.lang.api.DescrFactory
These APIs build the Drools AST, which can be passed directly to the compiler,
bypassing the parser. The AST can also be used to recreate DRL, using the
helper class org.drools.compiler.lang.DrlDumper
The standard tools don't produce DRL files. Instead they encourage you to have templates which are applied to your data at runtime.
You should take a look at the documentation on Decision Tables (specially structured spreadsheets):
http://docs.jboss.org/drools/release/6.0.1.Final/drools-docs/html_single/#d0e4221
... and Rule Templates:
http://docs.jboss.org/drools/release/6.0.1.Final/drools-docs/html_single/#d0e4969
Even i have used the same implementation that #apandey846 suggested. I would just like to add one more thing: If you want to import the required classes, you can do it as follows:
PackageDescr pkg = DescrFactory.newPackage()
.newImport("classname").target().end()
.name("org.drools.example")
.newRule().name("Xyz")
.attribute("ruleflow-grou","bla")
.lhs()
.and()
.pattern("Foo").id( "$foo", false ).constraint("bar==baz").constraint("x>y").end()
.not().pattern("Bar").constraint("a+b==c").end().end()
.end()
.end()
.rhs( "System.out.println();" ).end()
.getDescr();
To add multiple conditions in the LHS, you can do:
pattern("eval").constraint("condition1").end().
pattern("eval").constraint("condition2").end().
pattern("eval").constraint("condition3").end().
Hope it helps.. :)
Decesion tables have worked for me alternatively you could try using the new Drools workbench.
I have used the DrlDescr dump method but it is Not updating the drl file, Does anybody have any idea why?
Code:-
pkg1.addRule(rules);
System.out.println(dDump.dump(pkg1));

Eclipse Advanced code template

I have been researching about how to create my own Eclipse's editor template or customize code template to fit my need but to no avail.
Here is my requirement:
I need to have to this kind of script.
${class} ${classname:newName(class)} = new ${class}();
${classname}.toString();
So when I try to use use this. I can automatically generate the code below just by typing "MyClass" to the ${class} part of the code
MyClass myClass = new MyClass();
myClass.toString();
But just by using that script. "myClass" cannot be automatically generated when I input the class name "MyClass"
So for example, I will have
MyClass classname = new MyClass();
classname.toString();
I have found these resources, but it didn't help me. Can anyone point me to the right direction as I can't seem to find a solution for this problem.
http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fpreferences%2Fjava%2Fcodestyle%2Fref-preferences-code-templates.htm
Can you define your own template variables in Eclipse
Is there a Eclipse template variable for short version of enclosing type name
OR, is there a way to create my own Eclipse's "Generate Getters and Setters..",
which can be achieved my right clicking on any eclipse source file -> Source -> "Generate Getters and Setters"
This is the best I've found so far: https://marketplace.eclipse.org/content/fast-code-eclipse-plugin
It does exactly what I want, but it lacks polish and documentation. I've also had it crash on me to the point where I needed to reinstall it.
But it's still the best I've found so far.

Eclipse JDT: Call 'correct indentation' programmatically?

I am working on an Eclipse plugin that modifies Java code in a user's project.
Basically the result of this plugin is that Java annotations are added to some methods, so
void foo() { ... }
becomes
#MyAnnotation
void foo() { ... }
Except that it doesn't quite look like that; the indentation on the newly inserted annotation is wack (specifically, the new annotation is all the way to the left-hand side of the line). I'd like to make all my changes to the file, and then programmatically call "Correct Indentation."
Does anyone know how to do this? I can't find the answer here or in the JDT forums, and all the classes that look relevant (IndentAction, JavaIndenter) are in internal packages which I'm not supposed to use...
Thanks!
Well I think I may have figured out the solution I want. Guess I should have spend more time searching before asking... but for future reference, here's what I did! The good stuff was in the ToolFactory...
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.text.edits.TextEdit;
import org.eclipse.jdt.core.ICompilationUnit;
...
ICompilationUnit cu = ...
...
CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
ISourceRange range = cu.getSourceRange();
TextEdit indent_edit =
formatter.format(CodeFormatter.K_COMPILATION_UNIT,
cu.getSource(), range.getOffset(), range.getLength(), 0, null);
cu.applyTextEdit(indent_edit, null);
cu.reconcile();
This reformats the entire file. There are other options if you need to reformat less...
It's probably easier to add the indentation as you process the Java code.
Your Eclipse plugin had to read the void foo() { ... } line to know to add the #MyAnnotation, right? Just get the indentation from the Java line, and append your annotation to the indentation.

Categories

Resources