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

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);

Related

Why does adding w:drawing cause corrupted file

I'm trying to add a chart to a docx file using docx4j. I generated what i wanted in Word and with the help of the docx4j webapp i was able to get the corresponding java code. Unfortunately the generated docx file is said to be corrupted by Word. When trying to debug, I realised that if I commented out the line that added the drawing to the run, the file became readable. I can't figure out what's wrong. Below is my code and the link to what i tried to reproduce http://www.filedropper.com/graphique .
I'm using docx4j 8.2 and office 2016
Chart chartPart = new Chart();
Relationship chartRelationship = wordMLPackage.getMainDocumentPart().addTargetPart(chartPart);
chartPart.setJaxbElement(ChartSpace.createChartSpace());
DefaultXmlPart colorPart = new DefaultXmlPart(new PartName("/word/charts/colors1.xml"));
colorPart.setContentType(new ContentType("application/vnd.ms-office.chartcolorstyle+xml"));
colorPart.setRelationshipType("http://schemas.microsoft.com/office/2011/relationships/chartColorStyle");
chartPart.addTargetPart(colorPart);
colorPart.setDocument(new FileInputStream(new File("colors1.xml")));
DefaultXmlPart stylePart = new DefaultXmlPart(new PartName("/word/charts/style1.xml"));
stylePart.setContentType(new ContentType("application/vnd.ms-office.chartstyle+xml"));
stylePart.setRelationshipType("http://schemas.microsoft.com/office/2011/relationships/chartStyle");
chartPart.addTargetPart(stylePart);
stylePart.setDocument(new FileInputStream(new File("style1.xml")));
EmbeddedPackagePart embeddedPackagePart = new EmbeddedPackagePart(
new PartName("/word/embeddings/Microsoft_Excel_Worksheet.xlsx"));
embeddedPackagePart.setContentType(
new ContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
chartPart.addTargetPart(embeddedPackagePart);
embeddedPackagePart.setBinaryData(new java.io.FileInputStream(new File("data.xlsx")));
mainDocumentPart.getContent().add(addGraphic(factory, chartRelationship.getId()));
public static P addGraphic(ObjectFactory factory, String chartId) throws JAXBException {
P p = factory.createP();
// Create object for r
R r = factory.createR();
p.getContent().add(r);
// Create object for drawing (wrapped in JAXBElement)
Drawing drawing = factory.createDrawing();
JAXBElement<org.docx4j.wml.Drawing> drawingWrapped = factory.createRDrawing(drawing);
r.getContent().add(drawingWrapped);
org.docx4j.dml.wordprocessingDrawing.ObjectFactory dmlwordprocessingDrawingObjectFactory = new org.docx4j.dml.wordprocessingDrawing.ObjectFactory();
// Create object for inline
Inline inline = dmlwordprocessingDrawingObjectFactory.createInline();
drawing.getAnchorOrInline().add(inline);
org.docx4j.dml.ObjectFactory dmlObjectFactory = new org.docx4j.dml.ObjectFactory();
// Create object for graphic
Graphic graphic = dmlObjectFactory.createGraphic();
inline.setGraphic(graphic);
// Create object for graphicData
GraphicData graphicdata = dmlObjectFactory.createGraphicData();
graphic.setGraphicData(graphicdata);
graphicdata.setUri("http://schemas.openxmlformats.org/drawingml/2006/chart");
org.docx4j.dml.chart.ObjectFactory dmlchartObjectFactory = new org.docx4j.dml.chart.ObjectFactory();
// Create object for chart (wrapped in JAXBElement)
CTRelId relid = dmlchartObjectFactory.createCTRelId();
JAXBElement<org.docx4j.dml.chart.CTRelId> relidWrapped = dmlchartObjectFactory.createChart(relid);
graphicdata.getAny().add(relidWrapped);
relid.setId(chartId);
// Create object for cNvGraphicFramePr
CTNonVisualGraphicFrameProperties nonvisualgraphicframeproperties = dmlObjectFactory
.createCTNonVisualGraphicFrameProperties();
inline.setCNvGraphicFramePr(nonvisualgraphicframeproperties);
// Create object for extent
CTPositiveSize2D positivesize2d = dmlObjectFactory.createCTPositiveSize2D();
inline.setExtent(positivesize2d);
positivesize2d.setCx(5486400);
positivesize2d.setCy(3200400);
// Create object for effectExtent
CTEffectExtent effectextent = dmlwordprocessingDrawingObjectFactory.createCTEffectExtent();
inline.setEffectExtent(effectextent);
effectextent.setB(0);
effectextent.setL(0);
effectextent.setT(0);
effectextent.setR(0);
// Create object for docPr
CTNonVisualDrawingProps nonvisualdrawingprops = dmlObjectFactory.createCTNonVisualDrawingProps();
inline.setDocPr(nonvisualdrawingprops);
nonvisualdrawingprops.setDescr("");
nonvisualdrawingprops.setName("Graphique 1");
nonvisualdrawingprops.setId(1);
inline.setDistT(Long.valueOf(0));
inline.setDistB(Long.valueOf(0));
inline.setDistL(Long.valueOf(0));
inline.setDistR(Long.valueOf(0));
// Create object for rPr
RPr rpr = factory.createRPr();
r.setRPr(rpr);
// Create object for noProof
BooleanDefaultTrue booleandefaulttrue = factory.createBooleanDefaultTrue();
rpr.setNoProof(booleandefaulttrue);
return p;
}

How to add test case in existing test run through automation

I have created on test set and i want to add test case in existing test run . I used update request to add the test case, but its deleting existing test case in test run and adding it.
if(!testCaseList.isJsonNull()&&!update){
restApi.setApplicationName("PSN")
JsonObject newTS = new JsonObject()
newTS.addProperty("Name", TSName)
newTS.addProperty("PlanEstimate", points)
newTS.addProperty("Project", projectRef)
newTS.addProperty("Owner", userRef)
if (releaseRef!="") newTS.addProperty("Release", releaseRef)
if (iterationRef!="") newTS.addProperty("Iteration", iterationRef)
newTS.add("TestCases", testCaseList)
CreateRequest createRequest = new CreateRequest("testset",newTS)
CreateResponse createResponse = restApi.create(createRequest)
ref = createResponse.getObject().get("_ref").getAsString()
}
else if(!testCaseList.isJsonNull()&&update){
restApi.setApplicationName("PSN")
newTS.addProperty("Name", TSName)
newTS.addProperty("PlanEstimate", points)
newTS.addProperty("Project", projectRef)
newTS.addProperty("Owner", userRef)
if (releaseRef!="") newTS.addProperty("Release", releaseRef)
if (iterationRef!="") newTS.addProperty("Iteration", iterationRef)
newTS.add("TestCases", testCaseList)
UpdateRequest updateRequest = new UpdateRequest(ref,newTS)
UpdateResponse updateResponse = restApi.update(updateRequest)
ref = updateResponse.getObject().get("_ref").getAsString()
}
Rather than setting the TestCases collection directly you want to use the CollectionUpdateRequest and the updateCollection method.
https://github.com/RallyTools/RallyRestToolkitForJava/wiki/User-Guide#update-collection
CollectionUpdateRequest testsetTestCasesAddRequest = new CollectionUpdateRequest(ref + "/testcases", testCaseList, true);
CollectionUpdateResponse testsetTestCasesAddResponse = restApi.updateCollection(testsetTestCasesAddRequest);

How to make GUI Button activate script (JS or C#) in Unity3d

I really need your help to make my GUI.Button start a JS script (or C#) attached to a GameObject. Here is what I have in my application. A JS script "doRotate.js", that does a rotation on a GameObject.
The rotation starts if the value of "public var doRotation = false" is chanced to "true" by click in the Inspector
#pragma strict
public var doRotation = false;
function Update()
{
if (doRotation)
{
transform.Rotate(new Vector3(0, 50, 0) * Time.deltaTime);
}
}
I also have a JS script that renders some GUI.buttons. I want button 2, once pressed to call (run) the "doRotate.js" script, meaning accessing the boolean "doRotation" and chance its value to "true", as if it is done in the Inspector.
Following is what I've tried so far, but I get this error "Error BCE0020: An instance of type 'doRotate' is required to access non static member 'doRotation'. (BCE0020)".
Here is the code on the GUI.button:
var native_width : float = 480;
var native_height : float = 320;
var addImage : Texture2D;
var btnTexture1 : Texture;
var btnTexture2 : Texture;
function OnGUI ()
{
var rx : float = Screen.width / native_width;
var ry : float = Screen.height / native_height;
GUI.matrix = Matrix4x4.TRS (Vector3(0, 0, 0), Quaternion.identity, Vector3 (rx, ry, 1));
GUI.Box( Rect(20, 200, 429, 129) ,addImage, "");
if (!btnTexture1) {
Debug.LogError("Please assign a texture on the inspector");
return;
}
GUI.Button(Rect(54, 222, 52, 35), btnTexture1);
if (!btnTexture2) {
Debug.LogError("Please assign a texture on the inspector");
return;
}
if(GUI.Button(Rect(118, 222, 52, 35), btnTexture2));
var runScript : GameObject[] =
GameObject.FindGameObjectsWithTag("markerObject");
for(var doRotation : GameObject in runScript) {
var script : doRotate = doRotation.GetComponent(doRotate);
if(script)
doRotate.doRotation(); //Error BCE0020: An instance of type 'doRotate' is required to access non static member 'doRotation'. (BCE0020)
}
What have I done wrong? I've trying for days,to make it work without success. How can I access this variable on the click of the GUI.Button?
Can someone, please help me out?
This error occurs because you are trying to access a nonstatic member of "doRotate" with a class, not with an instance of it.
In this following code:
var script : doRotate = doRotation.GetComponent(doRotate);
if(script)
doRotate.doRotation(); //Error BCE0020: An instance of type 'doRotais required to access non static member 'doRotation'. (BCE0020)
You are setting the instance of doRotate to var script, this var stores a reference of doRotate instance, with this you can access the var "doRotation" and change his value.
Something like this:
var script : doRotate = doRotation.GetComponent(doRotate);
if(script)
script.doRotation = true;

eclipse JDT setting the project

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);

Testing grails taglib

Grails 1.1.
My custom tag:
class MyTagLib {
static namespace 'ct'
def textField = {attrs ->
def bean = attrs.remove('bean')
def field = attrs.remove('field')
attrs.name = field
out << render(template:"/templates/textField", model:[
required: !bean.constraints[field].nullable,
display : bean["${bean.trainingExperience.type}"][field],
theTag : g.textField(name : field, value : bean[field]),
value : bean[field]
])
}
Just about all of the taglib unit tests i see just
AssertEquals "Some String", taglib.out.toString()
Is it possible to test that correct template is being rendered with the correct values in the model?
MyTagLibTests
public class CareertracTagLibTests extends TagLibUnitTestCase{
protected void setUp() {
super.setUp()
mockTagLib(FormTagLib)
mockTagLib(RenderTagLib)
def g = new FormTagLib() // interpret "g" namespace as instances of FormTagLib
tagLib.metaClass.g = g
String.metaClass.encodeAsHTML = {org.codehaus.groovy.grails.plugins.codecs.HTMLCodec.encode(it)}
}
void TestTextField() {
tagLib.textField([bean : mockBean, field : 'viewField'])
def x = new RenderTagLib().render(template:"/templates/textField",
model:[required:false,
display:"view",
// Snip
])
assertEquals tagLib.out, x.out // Or something like this
}
}
}
With TagLibUnitTestCase you can use renderArgs to test calls to the render method the same way that you can in ControllerUnitTestCase. The renderArgs property is simply a map that stores the arguments of the last call to the render dynamic method. So, in your example you would want something like this:
assertEquals "/templates/textField", renderArgs.template
assertFalse renderArgs.model.required
and so on.