Eclipse Advanced code template - java

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.

Related

Generating BPEL files programmatically?

Is there a way to generate BPEL programmatically in Java?
I tried using the BPEL Eclipse Designer API to write this code:
Process process = null;
try {
Resource.Factory.Registry reg =Resource.Factory.Registry.INSTANCE;
Map<String, Object> m = reg.getExtensionToFactoryMap();
m.put("bpel", new BPELResourceFactoryImpl());//it works with XMLResourceFactoryImpl()
//create resource
URI uri =URI.createFileURI("myBPEL2.bpel");
ResourceSet rSet = new ResourceSetImpl();
Resource bpelResource = rSet.createResource(uri);
//create/populate process
process = BPELFactory.eINSTANCE.createProcess();
process.setName("myBPEL");
Sequence mySeq = BPELFactory.eINSTANCE.createSequence();
mySeq.setName("mainSequence");
process.setActivity(mySeq);
//save resource
bpelResource.getContents().add(process);
Map<String,String> map= new HashMap<String, String>();
map.put("bpel", "http://docs.oasis-open.org/wsbpel/2.0/process/executable");
map.put("tns", "http://matrix.bpelprocess");
map.put("xsd", "http://www.w3.org/2001/XMLSchema");
bpelResource.save(map);
}
catch (Exception e) {
e.printStackTrace();
}
}
but I received an error:
INamespaceMap cannot be attached to an eObject ...
I read this message by Simon:
I understand that using the BPEL model outside of eclipse might be desirable, but it was never intended by us. Thus, this isn't supported
Is there any other API that can help?
You might want to give JAXB a try. It helps you to transform the official BPEL XSD into Java classes. You use those classes to construct your BPEL document and output it.
I had exactly the same problem with the BPELUnit [1], so I started a module in BPELUnit that has the first things necessary for generating and reading BPEL Models [2] although it is far from complete. Supported is only BPEL 2.0 (1.1 will follow later) and handlers are also currently not supported (but will be added). It is under active development because BPELUnit's code coverage component will be based on it so it will get BPEL-feature complete over time. You are happily invited to contribute if you need to close gaps earlier.
You can check it out from GitHub or grap the Maven artifact.
As of now there is no documentation but you can have a look at the JUnit tests that read and write processes.
If this is not suitable for, I'd like to share some experiences with you:
Do not use JAXB: You will need to read and write XML Namespaces which are not preserved with JAXB. That's why I have chosen XMLBeans. DOM would be the other alternative that I can think of.
The inheritance in the XML Schema is not really developer friendly. That's why there are own interface structures and wrappers around the XMLBeans generated classes.
Daniel
[1] http://www.bpelunit.net
[2] https://github.com/bpelunit/bpelunit/tree/master/net.bpelunit.model.bpel
This has been solved using the unify framework API after adding the necessary classes to handle correlation. BPELUnit stated by #Daniel seems to be another alternative.
The Eclipse BPEL API is based on an EMF Model. So you could generate your own artifacts using JET or Xpand based on that. This way there is no requirement to run inside Eclipse.
Although you may can't use BPEL outside of Eclipse, have you considered moving parts of your application inside it?
The BPEL XML Schemas are listed in the appendig of the spec. So you could also base your work on that and integrate with existing BPEL applications where necessary.
In case anyone is looking to solve the above problem while still running inside eclipse environment.
The problem can be resolved as stated by Luca Pino here by adding:
AdapterRegistry.INSTANCE.registerAdapterFactory( BPELPackage.eINSTANCE, BasicBPELAdapterFactory.INSTANCE );
before the resource creation line i.e.
Resource bpelResource = rSet.createResource(uri);
Note: Another solution, to the same problem, also stating how to resolve the dependencies to make this code work, can be found in my other answer here.

JRules Studio - Display values of IN_OUT parameters while testing

I'm using JRules Studio to develop some extremely simple rules. The rules populate an IN_OUT parameter. When the test finishes, is there a way of interrogating the values in the IN_OUT object?
Initially I'd like to interrogate it in the debugger, but any other ideas would be welcomed.
I am not sure to understand the question:
Your JAVA code is like this:
IlrSessionFactory factory = new IlrJ2SESessionFactory();
IlrStatelessSession session = factory.createStatelessSession();
IlrSessionRequest sessionRequest = factory.createRequest();
sessionRequest.setRulesetPath(“/RuleAppName/rulesetName”);
sessionRequest.setTraceEnabled(true);
sessionRequest.getTraceFilter().setInfoAllFilters(true);
Map inputParameters = new HashMap ();
Report in_report = new Report(); // no-arg constructor
// ... populate the Object ...
inputParameters.put("report", in_report);
sessionRequest.setInputParameters(inputParameters);
IlrSessionResponse sessionResponse = session.execute(sessionRequest);
Report out_report = (Report)sessionResponse.getOutputParameters().get("report“);
And then you play with your "out" parameters... As you would do with any JAVA object
If you want to see them at debug time, I would say:
1/ (not tested) Have a look on the "working memory tab" in the debugger perspective
I am not sure but this is the easiest way to find them if it is visible here
2/ (tested) in the initial action of the starting point of your ruleflow, add:
context.insert(the technical name of your parameter);
Not the "business name". Anyway avoid using BAL in technical artifact such as ruleflow, IRL rules!
By doing this you force the engine to insert your parameter in the working memory.
No duplication (don't worry, it will work like a charm) but as far as I can remember this is the shortest way to make them visible in the Eclipse debugger in JRules
Hope it helps

add import to a groovy file from an eclipse plugin

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.

Eclipse RCP: File association (--launcher.openFile)

I'm developing an eclipse product and i need to associate a file extension to my editor.
I followed several examples (as like as this and
this) but it seems that the editor ever receives the SWT OpenDocument event.
As described in the fileAssociation example i created an eventListener class to process SWT.OpenDocument events and i added this in my Application class to the display before that the PlatformUI.createAndRunWorkbench() method gets called
public Object start(IApplicationContext context) throws Exception {
Object args = context.getArguments().get(IApplicationContext.APPLICATION_ARGS);
OpenDocumentEventProcessor eProc = new OpenDocumentEventProcessor();
Display display = PlatformUI.createDisplay();
display.addListener(SWT.OpenDocument, eProc);
try{
if(!handleWorkspace(display)){
System.exit(0);
return IApplication.EXIT_OK;
}
int returnCode = PlatformUI.createAndRunWorkbench(display, new XVRWorkbenchAdvisor(args, eProc));
In the product file i added the following program arguments:
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-name
XVR Studio Developer
If I use the same code in a new empty RCP project it works like a charm..
I can't figured out which could be the problem..
can you help me?
Thanks a lot!!
This approach is unknown for me, but since there is no explicit editor call in your pasted code I guess you still rely on eclipse to decide which editor has to be opened. So I guess you still have to define contentypes and file associations declaratively. To do that contribute to "org.eclipse.core.contenttype.contentTypes" extension, add a 'file-association' (file extension...). Get your editor declaration in your plugin xml and add the previously created 'contentTypeBinding' id.
As I have just made this work for an RCP app, I thought it would be helpful to document how I did it here, and provide refs.
I had no use for the 'context.getArguments()..', the 'OpenDocumentEventProcessor' handled everything.
I would suggest that the reason this did not work was that the -name value did not match the value of the 'appName' property in the 'org.eclipse.core.runtime.products' extension point. Just to be sure, I removed the spaces from the appName property and in the -name. Then it worked.
Very useful references are:
For the basic coding:
http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fproduct_open_file.htm
For an explanation of how this works:
http://aniefer.blogspot.co.uk/2010/05/opening-files-in-eclipse-from-command.html
One small point that eluded me for some time, was getting the path for the file in several chunks at the place where there was a space in the name. Eventually I realised (in a 'duh!' moment) that I needed to put quotes round the %1 parameter in the installer's (InstallAware) definition for the file association - i.e it became "%1"

Unable to incorporate Eclispe JDT codeAssist facilities outside a Plug-in

Using Eclipse jdt facilities, you can traverse the AST of java code snippets as follows:
ASTParser ASTparser = ASTParser.newParser(AST.JLS3);
ASTparser.setSource("package x;class X{}".toCharArray());
ASTparser.createAST(null).accept(...);
But when trying to perform code complete & code selection it seems that I have to do it in a plug-in application since I have to write codes like
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(somePath));
ICodeAssist i = JavaCore.createCompilationUnitFrom(f);
i.codeComplete/codeSelect(...)
Is there anyway that I can finally get a stand-alone java application which incorporates the jdt code complete/select facilities?
thx a lot!
shi kui
I have noticed it that using org.eclipse.jdt.internal.codeassist.complete.CompletionParser
I can parse a code snippet as well.
CompletionParser parser =new CompletionParser(new ProblemReporter(
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
new CompilerOptions(null),
new DefaultProblemFactory(Locale.getDefault())),
false);
org.eclipse.jdt.internal.compiler.batch.CompilationUnit sourceUnit =
new org.eclipse.jdt.internal.compiler.batch.CompilationUnit(
"class T{f(){new T().=1;} \nint j;}".toCharArray(), "testName", null);
CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0);
CompilationUnitDeclaration unit = parser.dietParse(sourceUnit, compilationResult, 25);
But I have 2 questions:
1. How to retrive the assist information?
2. How can I specify class path or source path for the compiler to look up type/method/field information?
I don't think so, unless you provide your own implementation of ICodeAssist.
As the Performing code assist on Java code mentions, Elements that allow this manipulation should implement ICodeAssist.
There are two kinds of manipulation:
Code completion - compute the completion of a Java token.
Code selection - answer the Java element indicated by the selected text of a given offset and length.
In the Java model there are two elements that implement this interface: IClassFile and ICompilationUnit.
Code completion and code selection only answer results for a class file if it has attached source.
You could try opening a File outside of any workspace (like this FAQ), but the result wouldn't implement ICodeAssist.
So the IFile most of the time comes from a workspace location.

Categories

Resources