eclipse JDT setting the project - eclipse-plugin

I am a beginner to Eclipse JDT. I was going through some tutorial and found one good example for creating the java file. In this below example in which project they will create the package and java file. I could not see any code pointing to any of the project name. Please make me understand if I am wrong. I just run the below example. I could not see any output..
AST ast = AST.newAST(AST.JLS3);
CompilationUnit unit = ast.newCompilationUnit();
PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
packageDeclaration.setName(ast.newSimpleName("example"));
unit.setPackage(packageDeclaration);
ImportDeclaration importDeclaration = ast.newImportDeclaration();
QualifiedName name =
ast.newQualifiedName(
ast.newSimpleName("java"),
ast.newSimpleName("util"));
importDeclaration.setName(name);
importDeclaration.setOnDemand(true);
unit.imports().add(importDeclaration);
TypeDeclaration type = ast.newTypeDeclaration();
type.setInterface(false);
type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
type.setName(ast.newSimpleName("HelloWorld"));
MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
methodDeclaration.setConstructor(false);
List modifiers = methodDeclaration.modifiers();
modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
methodDeclaration.setName(ast.newSimpleName("main"));
methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
variableDeclaration.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("String"))));
variableDeclaration.setName(ast.newSimpleName("args"));
methodDeclaration.parameters().add(variableDeclaration);
org.eclipse.jdt.core.dom.Block block = ast.newBlock();
MethodInvocation methodInvocation = ast.newMethodInvocation();
name =
ast.newQualifiedName(
ast.newSimpleName("System"),
ast.newSimpleName("out"));
methodInvocation.setExpression(name);
methodInvocation.setName(ast.newSimpleName("println"));
InfixExpression infixExpression = ast.newInfixExpression();
infixExpression.setOperator(InfixExpression.Operator.PLUS);
StringLiteral literal = ast.newStringLiteral();
literal.setLiteralValue("Hello");
infixExpression.setLeftOperand(literal);
literal = ast.newStringLiteral();
literal.setLiteralValue(" world");
infixExpression.setRightOperand(literal);
methodInvocation.arguments().add(infixExpression);
ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation);
block.statements().add(expressionStatement);
methodDeclaration.setBody(block);
type.bodyDeclarations().add(methodDeclaration);
unit.types().add(type);

You may take a look at this. It uses Java Model, which means you will need to create a plug-in to make it work.
// create a project with name "TESTJDT"
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("TESTJDT");
project.create(null);
project.open(null);
//set the Java nature
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID });
//create the project
project.setDescription(description, null);
IJavaProject javaProject = JavaCore.create(project);
//set the build path
IClasspathEntry[] buildPath = {
JavaCore.newSourceEntry(project.getFullPath().append("src")),
JavaRuntime.getDefaultJREContainerEntry() };
javaProject.setRawClasspath(buildPath, project.getFullPath().append(
"bin"), null);
//create folder by using resources package
IFolder folder = project.getFolder("src");
folder.create(true, true, null);
//Add folder to Java element
IPackageFragmentRoot srcFolder = javaProject
.getPackageFragmentRoot(folder);
//create package fragment
IPackageFragment fragment = srcFolder.createPackageFragment(
"com.programcreek", true, null);
//init code string and create compilation unit
String str = "package com.programcreek;" + "\n"
+ "public class Test {" + "\n" + " private String name;"
+ "\n" + "}";
ICompilationUnit cu = fragment.createCompilationUnit("Test.java", str,
false, null);
//create a field
IType type = cu.getType("Test");
type.createField("private String age;", null, true, null);

Related

How to Evaluate JavaScript code from .NetCore

I need to evaluate Javascript code from .netcore 2.1 project
string vRule = "var input = arguments[0]; if (!input) return \"\"; if(input.length != 7) return \"a fixed string length of 7 is required\"; else return \"\"";
string spResponse = "sdfsd23";
string errorText =
_jscriptEval.EvalToString(new List<object>
{
"var args = new Array('" + spResponse +
"');\r\n validateRule(args);\r\n function validateRule(arguments){" + vRule +
"}\r\n"
});
You can use Jint. Jint implements the ECMA 5.1 spec and can be use from any .NET implementation (Xamarin, .NET Framework, .NET Core). Just use the NuGet package and has no dependencies to other stuff - it’s a single .dll and you are done!
Just transform your javascript code into a function and run it like this (this is just an example, not your implementation):
var engine = new Engine()
.Execute("function MyFunction(a, b) { return a + b; }")
;
engine.Invoke("MyFunction", 1, 2); // -> 3
You have more explanations and examples on https://github.com/sebastienros/jint

cross-file reference in xtext

I created a new DSL by using xtext as follows.
(Actually I will access the DSL on RCP application.)
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals
generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"
Configuration:
components+=(Component)*;
Component:
'Component' name=ID
'{'
(('display' display=STRING) &
('dependency' dependency=[Component|ID])?)
'}'
;
I have two files:
sample1.mydsl
Component comp1 {
display "comp1"
dependency comp2
}
sampl2.mydsl
Component comp2 {
display "comp2"
}
To check the reference from another file,
I tried to run a test code as standalone but I couldn't get the eobject exactly.
test code
public static final void main(String arg[]) {
new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../");
Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration();
XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
File file=new File("/Users/nuckee/Work/temp/mydsl/sample1.mydsl");
Resource resource = resourceSet.getResource(
URI.createURI(file.toURI().toString()), true);
Configuration config = (Configuration) resource.getContents().get(0);
Component comp1 = config.getComponents().get(0);
if (comp1 != null) {
System.out.println("configuration displayed name : " + comp1.getDisplay());
Component dep = comp1.getDependency() ;
if (dep != null) {
System.out.println("dep : " + dep);
System.out.println("dep displayed name : " + dep.getDisplay());
}
}
}
result
configuration displayed name : comp1
dep : org.xtext.example.mydsl.myDsl.impl.ComponentImpl#61544ae6 (eProxyURI: file:/Users/nuckee/Work/temp/mydsl/sample1.mydsl#|0)
dep displayed name : null
How can exactly I get the display of "comp2" from another file?
I Hope someone can help me solve it. Thanks.
You have to load all model files into the resourceset. Xtext does not do auto file discovery

Hippo cms add content to repository

This time I'm trying add a values to repository using component. I don't have problem with reading.
Currently, I'm trying add the city to the repository
My code:
Session session = this.getPersistableSession(request);
HippoBean siteBaseBean = request.getRequestContext().getSiteContentBaseBean();
HippoBean hippoFolder = siteBaseBean.getBean("city");
Node node = hippoFolder.getNode();
String path = node.getPath(); // it's working "/content/documents/myhippoproject/city"
node.addNode("4","hippo:handle");
session.save();
after this code nothing happened. I tried also:
node.addNode("4",HippoNodeType.HIPPO_NODE);
No errors and node.
ok, I found a solution.
Session session = this.getPersistableSession(request);
HippoBean siteBaseBean = request.getRequestContext().getSiteContentBaseBean();
HippoBean hippoFolder = siteBaseBean.getBean("city");
Node node = hippoFolder.getNode();
HippoRepository repository = HippoRepositoryFactory.getHippoRepository("vm://");
Session session2 = repository.login("admin", "admin".toCharArray());
HstRequestContext requestContext = request.getRequestContext();
WorkflowPersistenceManager wpm = null;
wpm = getWorkflowPersistenceManager(session2);
wpm.setWorkflowCallbackHandler(new BaseWorkflowCallbackHandler<DocumentWorkflow>() {
public void processWorkflow(DocumentWorkflow wf) throws Exception {
wf.requestPublication();
}
});
String name = "12";
wpm.createAndReturn(node.getPath(), "myhippoproject:City", name, false);
City city = (City) wpm.getObject(node.getPath() + "/" + name);
wpm.update(city);
session2.save();

Eclipse AST not changing files which are not opened in eclipse

I am trying to modify source code using eclipse plugin, JDT and AST (Abstract Syntax Tree). I can read all Java files and make operation on all those file, But when i am saving those changes (Edits) in to files using
TextEdit edits = rewriter.rewriteAST();
// apply the text edits to the compilation unit
edits.apply(document);
iCompilationUnit.getBuffer().setContents(document.get());
It only make changes in file those are open in eclipse in unsaved mode. Rest of files are not affected.
Find my code snippet below:
CompilationUnit cu = parse(iCompilationUnit);
MethodVisitor visitor = new MethodVisitor();
cu.accept(visitor);
String source = iCompilationUnit.getSource();
Document document= new Document(source);
ASTRewrite rewriter = ASTRewrite.create(cu.getAST());
cu.recordModifications();
for (MethodDeclaration methodDeclaration : visitor.getMethods()) {
System.out.print("Method name: " + methodDeclaration.getName()
+ " Return type: " + methodDeclaration.getReturnType2());
MethodDeclaration methodDecl = methodDeclaration;
Block block = methodDecl.getBody();
ListRewrite listRewrite = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);
Statement placeHolder = (Statement) rewriter.createStringPlaceholder("System.out.println(\"Test Print\");", ASTNode.EMPTY_STATEMENT);
listRewrite.insertFirst(placeHolder, null);
}
TextEdit edits = rewriter.rewriteAST();
// apply the text edits to the compilation unit
edits.apply(document);
iCompilationUnit.getBuffer().setContents(document.get());
Try to:
Apply the TextEdit directly to the ICompilationUnit instead of using Document.
Use ICompilationUnit.commitWorkingCopy to save the changes
I use code similar to this:
iCompilationUnit.becomeWorkingCopy(new NullProgressMonitor());
CompilationUnit cu = parse(iCompilationUnit);
ASTRewrite rewriter = ASTRewrite.create(cu.getAST());
... process AST ...
iCompilationUnit.applyTextEdit(rewrite.rewriteAST(), new NullProgressMonitor());
iCompilationUnit.commitWorkingCopy(false, new NullProgressMonitor());

How to use JavaParser to add new methods to a parsing file?

I have parsed a java file and get the Compilation Unit
CompilationUnit
cu = JavaParser.parse(in); in a java file
How can I add some new methods by using this cu?
I just want to add the new methods in my original class.
This is an example on how you can create a method and add it to your compilation unit:
// create the type declaration
ClassOrInterfaceDeclaration type = cu.addClass("GeneratedClass");
// create a method
EnumSet<Modifier> modifiers = EnumSet.of(Modifier.PUBLIC);
MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), "main");
modifiers.add(Modifier.STATIC);
method.setModifiers(modifiers);
type.addMember(method);
// or a shortcut
MethodDeclaration main2 = type.addMethod("main2", Modifier.PUBLIC, Modifier.STATIC);
// add a parameter to the method
Parameter param = new Parameter(new ClassOrInterfaceType("String"), "args");
param.setVarArgs(true);
method.addParameter(param);
// or a shortcut
main2.addAndGetParameter(String.class, "args").setVarArgs(true);
// add a body to the method
BlockStmt block = new BlockStmt();
method.setBody(block);
// add a statement do the method body
NameExpr clazz = new NameExpr("System");
FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
MethodCallExpr call = new MethodCallExpr(field, "println");
call.addArgument(new StringLiteralExpr("Hello World!"));
block.addStatement(call);
here i am adding a new test method to some testing classes:
for (Node childNode : compilationUnit.getChildNodes()) {
if (childNode instanceof ClassOrInterfaceDeclaration) {
ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration) childNode;
MethodDeclaration method = classOrInterfaceDeclaration.addMethod("testingGetterAndSetter", Modifier.PUBLIC);
method.addMarkerAnnotation("Test");
NodeList<Statement> statements = new NodeList<>();
BlockStmt blockStmt = JavaParser.parseBlock(String.format(TestMethod, className));
method.setBody(blockStmt);
}
}
the Testmethod contains the body of the method
An example of creating a class with annotation and adding a method to that class is as follows.
ClassOrInterfaceDeclaration controllerClass = cu.addClass("SomeClass")
.setPublic(true)
.addAnnotation(org.springframework.web.bind.annotation.RestController.class);
MethodDeclaration indexMethod = controllerClass.addMethod("index", Keyword.PUBLIC);