List of usage examples for org.eclipse.jdt.core.dom Block statements
ASTNode.NodeList statements
To view the source code for org.eclipse.jdt.core.dom Block statements.
Click Source Link
From source file:org.eclipse.xtend.core.javaconverter.JavaASTFlattener.java
License:Open Source License
@Override public boolean visit(final Block node) { this.appendToBuffer("{"); this.increaseIndent(); boolean _isEmpty = node.statements().isEmpty(); boolean _not = (!_isEmpty); if (_not) {//from www .j ava 2 s . c o m final Procedure2<ASTNode, Integer> _function = (ASTNode child, Integer counter) -> { this.appendLineWrapToBuffer(); child.accept(this); }; IterableExtensions.<ASTNode>forEach(node.statements(), _function); } ASTNode _root = node.getRoot(); if ((_root instanceof CompilationUnit)) { ASTNode _root_1 = node.getRoot(); final CompilationUnit cu = ((CompilationUnit) _root_1); final Function1<Comment, Boolean> _function_1 = (Comment it) -> { int _startPosition = it.getStartPosition(); int _startPosition_1 = node.getStartPosition(); int _length = node.getLength(); int _plus = (_startPosition_1 + _length); return Boolean.valueOf((_startPosition < _plus)); }; final Consumer<Comment> _function_2 = (Comment it) -> { if ((!(it instanceof LineComment))) { this.appendLineWrapToBuffer(); } it.accept(this); this.assignedComments.add(it); }; IterableExtensions.<Comment>filter(this.unAssignedComments(cu), _function_1).forEach(_function_2); } this.decreaseIndent(); this.appendLineWrapToBuffer(); this.appendToBuffer("}"); return false; }
From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerTryBlock.java
License:Open Source License
@Override public void run(IMarker marker) { // TODO Auto-generated method stub IResource res = marker.getResource(); try {//from ww w . j a v a 2 s .c o m String markerMessage = (String) marker.getAttribute(IMarker.MESSAGE); String exception = markerMessage.split(" ")[0]; String[] exceptionPackageArray = exception.split("\\."); String exceptionPackage = ""; for (int i = 0; i < exceptionPackageArray.length - 1; i++) { exceptionPackage += exceptionPackageArray[i] + "."; } exception = exception.substring(exceptionPackage.length()); System.out.println("Package: " + exceptionPackage + ", Exception: " + exception); ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res); CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res); int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1; int line = marker.getAttribute(IMarker.LINE_NUMBER, 0); if (position == 1) { position = compunit.getPosition(line, 0); } AST ast = compunit.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); IJavaElement element = icomp.getElementAt(position); IJavaElement method = getMethod(element); // TypeDeclaration td = (TypeDeclaration) compunit.types().get(0); TypeDeclaration td = (TypeDeclaration) compunit.types().get(0); MethodDeclaration md = td.getMethods()[0]; int counter = 1; while (!md.getName().getFullyQualifiedName().equals(method.getElementName()) && counter < td.getMethods().length) { md = td.getMethods()[counter]; System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName()); counter++; } Block block = md.getBody(); ListRewrite lr = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName(exceptionPackage + exception)); ListRewrite lrClass = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY); lrClass.insertAt(id, 0, null); ASTNode currentNode = null; List<ASTNode> list = new ArrayList<ASTNode>(); for (Object o : lr.getOriginalList()) { if (o instanceof ASTNode) { list.add((ASTNode) o); } } for (int i = 0; i < list.size(); i++) { ASTNode node = list.get(i); int nodeLine = compunit.getLineNumber(node.getStartPosition()); System.out.println(line + " " + nodeLine); if (line == nodeLine) { currentNode = node; break; } List childrenList = node.structuralPropertiesForType(); for (int j = 0; j < childrenList.size(); j++) { StructuralPropertyDescriptor curr = (StructuralPropertyDescriptor) childrenList.get(j); Object child = node.getStructuralProperty(curr); if (child instanceof List) { for (Object ob : (List) child) { if (ob instanceof ASTNode) { list.add((ASTNode) ob); } } } else if (child instanceof ASTNode) { list.add((ASTNode) child); } } } TryStatement ts = ast.newTryStatement(); Statement emptyStatement = (Statement) rewriter.createStringPlaceholder("\n", ASTNode.EMPTY_STATEMENT); Statement emptyStatement2 = (Statement) rewriter.createStringPlaceholder("\n\t", ASTNode.EMPTY_STATEMENT); Block b2 = ast.newBlock(); b2.statements().add(0, ASTNode.copySubtree(b2.getAST(), currentNode)); b2.statements().add(1, emptyStatement); b2.statements().add(0, emptyStatement2); ts.setBody(b2); CatchClause cc = ast.newCatchClause(); SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setName(ast.newSimpleName("e")); Type type = ast.newSimpleType(ast.newName(exception)); svd.setType(type); cc.setException(svd); Block b3 = ast.newBlock(); Statement printStatement = (Statement) rewriter.createStringPlaceholder("e.printStackTrace();", ASTNode.EMPTY_STATEMENT); b3.statements().add(0, printStatement); cc.setBody(b3); ListRewrite parentList = rewriter.getListRewrite(currentNode.getParent(), Block.STATEMENTS_PROPERTY); parentList.replace(currentNode, ts, null); parentList.insertAfter(cc, ts, null); ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager(); IPath path = compunit.getJavaElement().getPath(); try { bm.connect(path, null, null); ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null); IDocument document = textFileBuffer.getDocument(); TextEdit edits = rewriter.rewriteAST(document, null); edits.apply(document); textFileBuffer.commit(null, false); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedTreeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bm.disconnect(path, null, null); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } // (4) } marker.delete(); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
From source file:org.evosuite.testcarver.codegen.CodeGenerator.java
License:Open Source License
@SuppressWarnings("unchecked") private void restorceCodeFromLastPosTo(final String packageName, final int oid, final int end, final boolean postprocessing, final AST ast, final Block block) { final int oidInfoRecNo = this.log.oidRecMapping.get(oid); // start from last OID modification point int currentRecord = log.getRecordIndexOfWhereObjectWasInitializedFirst(oid); if (currentRecord > 0) { // last modification of object happened here // -> we start looking for interesting records after retrieved record currentRecord++;//from w w w .ja v a 2s .co m } else { // object new instance statement // -> retrieved loc record no is included currentRecord = -currentRecord; } String methodName; int currentOID; Object[] methodArgs; Integer methodArgOID; Integer returnValue; Object returnValueObj; for (; currentRecord <= end; currentRecord++) { currentOID = this.log.objectIds.getQuick(currentRecord); returnValueObj = this.log.returnValues.get(currentRecord); returnValue = returnValueObj.equals(CaptureLog.RETURN_TYPE_VOID) ? -1 : (Integer) returnValueObj; if (oid == currentOID || returnValue == oid) { methodName = this.log.methodNames.get(currentRecord); if (CaptureLog.PLAIN_INIT.equals(methodName)) // e.g. String var = "Hello World"; { PostProcessor.notifyRecentlyProcessedLogRecNo(currentRecord); this.createPlainInitStmt(currentRecord, block, ast); currentRecord = findEndOfMethod(currentRecord, currentOID); this.updateInitRec(currentOID, currentRecord); } else if (CaptureLog.NOT_OBSERVED_INIT.equals(methodName)) // e.g. Person var = (Person) XSTREAM.fromXML("<xml/>"); { PostProcessor.notifyRecentlyProcessedLogRecNo(currentRecord); this.createUnobservedInitStmt(currentRecord, block, ast); currentRecord = findEndOfMethod(currentRecord, currentOID); } else if (CaptureLog.PUTFIELD.equals(methodName) || CaptureLog.PUTSTATIC.equals(methodName) || // field write access such as p.id = id or Person.staticVar = "something" CaptureLog.GETFIELD.equals(methodName) || CaptureLog.GETSTATIC.equals(methodName)) // field READ access such as "int a = p.id" or "String var = Person.staticVar" { if (CaptureLog.PUTFIELD.equals(methodName) || CaptureLog.PUTSTATIC.equals(methodName)) { // a field assignment has always one argument methodArgs = this.log.params.get(currentRecord); methodArgOID = (Integer) methodArgs[0]; if (methodArgOID != null && methodArgOID != oid) { // create history of assigned value this.restorceCodeFromLastPosTo(packageName, methodArgOID, currentRecord, postprocessing, ast, block); } this.createFieldWriteAccessStmt(packageName, currentRecord, block, ast); } else { this.createFieldReadAccessStmt(packageName, currentRecord, block, ast); } currentRecord = findEndOfMethod(currentRecord, currentOID); if (CaptureLog.GETFIELD.equals(methodName) || CaptureLog.GETSTATIC.equals(methodName)) { // GETFIELD and GETSTATIC should only happen, if we obtain an instance whose creation has not been observed this.updateInitRec(currentOID, currentRecord); if (returnValue != -1) { this.updateInitRec(returnValue, currentRecord); } } } else // var0.call(someArg) or Person var0 = new Person() { methodArgs = this.log.params.get(currentRecord); for (int i = 0; i < methodArgs.length; i++) { // there can only be OIDs or null methodArgOID = (Integer) methodArgs[i]; if (methodArgOID != null && methodArgOID != oid) { this.restorceCodeFromLastPosTo(packageName, methodArgOID, currentRecord, postprocessing, ast, block); } } PostProcessor.notifyRecentlyProcessedLogRecNo(currentRecord); this.createMethodCallStmt(packageName, currentRecord, postprocessing, block, ast); block.statements().add(ast.newEmptyStatement()); // forward to end of method call sequence currentRecord = findEndOfMethod(currentRecord, currentOID); // each method call is considered as object state modification -> so save last object modification this.updateInitRec(currentOID, currentRecord); if (returnValue != -1) { // if returnValue has not type VOID, mark current log record as record where the return value instance was created // --> if an object is created within an observed method, it would not be semantically correct // (and impossible to handle properly) to create an extra instance of the return value type outside this method this.updateInitRec(returnValue, currentRecord); } // consider each passed argument as being modified at the end of the method call sequence for (int i = 0; i < methodArgs.length; i++) { // there can only be OIDs or null methodArgOID = (Integer) methodArgs[i]; if (methodArgOID != null && methodArgOID != oid) { this.updateInitRec(methodArgOID, currentRecord); } } } } } }
From source file:org.evosuite.testcarver.codegen.CodeGenerator.java
License:Open Source License
@SuppressWarnings("unchecked") private void createMethodCallStmt(final String packageName, final int logRecNo, final boolean postprocessing, final Block methodBlock, final AST ast) { // assumption: all necessary statements are created and there is one variable for reach referenced object final int oid = this.log.objectIds.get(logRecNo); final Object[] methodArgs = this.log.params.get(logRecNo); final String methodName = this.log.methodNames.get(logRecNo); final String methodDesc = this.log.descList.get(logRecNo); final org.objectweb.asm.Type[] methodParamTypes = org.objectweb.asm.Type.getArgumentTypes(methodDesc); final Class<?>[] methodParamTypeClasses = new Class[methodParamTypes.length]; for (int i = 0; i < methodParamTypes.length; i++) { methodParamTypeClasses[i] = getClassForName(methodParamTypes[i].getClassName()); }/*from w w w. j a v a2s . c o m*/ final String typeName = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); Class<?> type = getClassForName(typeName); // Class<?> type; // try { // type = Class.forName(typeName); // } catch (ClassNotFoundException e) { // throw new RuntimeException(e); // } final boolean haveSamePackage = type.getPackage().getName().equals(packageName); // TODO might be nicer... final Statement finalStmt; @SuppressWarnings("rawtypes") final List arguments; if (CaptureLog.OBSERVED_INIT.equals(methodName)) { /* * Person var0 = null; * { * var0 = new Person(); * } * catch(Throwable t) * { * org.uni.saarland.sw.prototype.capture.PostProcessor.captureException(<logRecNo>); * } */ // e.g. Person var0 = null; final String varName = this.createNewVarName(oid, typeName); VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); vd.setName(ast.newSimpleName(varName)); VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); stmt.setType(this.createAstType(typeName, ast)); vd.setInitializer(ast.newNullLiteral()); methodBlock.statements().add(stmt); try { this.getConstructorModifiers(type, methodParamTypeClasses); } catch (Exception e) { e.printStackTrace(); } final int constructorTypeModifiers = this.getConstructorModifiers(type, methodParamTypeClasses); final boolean isPublic = java.lang.reflect.Modifier.isPublic(constructorTypeModifiers); final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage; if (isReflectionAccessNeeded) { this.isNewInstanceMethodNeeded = true; final MethodInvocation mi = this.createCallMethodOrNewInstanceCallStmt(true, ast, varName, typeName, methodName, methodArgs, methodParamTypes); arguments = null; final Assignment assignment = ast.newAssignment(); assignment.setLeftHandSide(ast.newSimpleName(varName)); assignment.setOperator(Operator.ASSIGN); final CastExpression cast = ast.newCastExpression(); cast.setType(this.createAstType(typeName, ast)); cast.setExpression(mi); assignment.setRightHandSide(cast); finalStmt = ast.newExpressionStatement(assignment); } else { // e.g. var0 = new Person(); final ClassInstanceCreation ci = ast.newClassInstanceCreation(); ci.setType(this.createAstType(typeName, ast)); final Assignment assignment = ast.newAssignment(); assignment.setLeftHandSide(ast.newSimpleName(varName)); assignment.setOperator(Operator.ASSIGN); assignment.setRightHandSide(ci); finalStmt = ast.newExpressionStatement(assignment); arguments = ci.arguments(); } } else //------------------ handling for ordinary method calls e.g. var1 = var0.doSth(); { String returnVarName = null; final String desc = this.log.descList.get(logRecNo); final String returnType = org.objectweb.asm.Type.getReturnType(desc).getClassName(); final Object returnValue = this.log.returnValues.get(logRecNo); if (!CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) { Integer returnValueOID = (Integer) returnValue; // e.g. Person var0 = null; returnVarName = this.createNewVarName(returnValueOID, returnType); VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); vd.setName(ast.newSimpleName(returnVarName)); VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); stmt.setType(this.createAstType(returnType, ast)); vd.setInitializer(ast.newNullLiteral()); methodBlock.statements().add(stmt); } final String varName = this.oidToVarMapping.get(oid); final int methodTypeModifiers = this.getMethodModifiers(type, methodName, methodParamTypeClasses); final boolean isPublic = java.lang.reflect.Modifier.isPublic(methodTypeModifiers); final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage; // e.g. Person var0 = var1.getPerson("Ben"); final MethodInvocation mi; if (isReflectionAccessNeeded) { this.isCallMethodMethodNeeded = true; mi = this.createCallMethodOrNewInstanceCallStmt(false, ast, varName, typeName, methodName, methodArgs, methodParamTypes); arguments = null; if (returnVarName != null) { final Assignment assignment = ast.newAssignment(); assignment.setLeftHandSide(ast.newSimpleName(returnVarName)); assignment.setOperator(Operator.ASSIGN); final CastExpression cast = ast.newCastExpression(); cast.setType(this.createAstType(returnType, ast)); cast.setExpression(mi); assignment.setRightHandSide(cast); finalStmt = ast.newExpressionStatement(assignment); } else { finalStmt = ast.newExpressionStatement(mi); } } else { mi = ast.newMethodInvocation(); if (this.log.isStaticCallList.get(logRecNo)) { // can only happen, if this is a static method call (because constructor statement has been reported) final String tmpType = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); mi.setExpression(ast.newName(tmpType.split("\\."))); } else { mi.setExpression(ast.newSimpleName(varName)); } mi.setName(ast.newSimpleName(methodName)); arguments = mi.arguments(); if (returnVarName != null) { final Assignment assignment = ast.newAssignment(); assignment.setLeftHandSide(ast.newSimpleName(returnVarName)); assignment.setOperator(Operator.ASSIGN); assignment.setRightHandSide(mi); finalStmt = ast.newExpressionStatement(assignment); } else { finalStmt = ast.newExpressionStatement(mi); } } } if (postprocessing) { final TryStatement tryStmt = this.createTryStatementForPostProcessing(ast, finalStmt, logRecNo); methodBlock.statements().add(tryStmt); } else { if (this.failedRecords.contains(logRecNo)) { // we just need an empty catch block to preserve program flow final TryStatement tryStmt = this.createTryStmtWithEmptyCatch(ast, finalStmt); methodBlock.statements().add(tryStmt); } else { methodBlock.statements().add(finalStmt); } } if (arguments != null) { // final String methodDesc = this.log.descList.get(logRecNo); // final org.objectweb.asm.Type[] methodParamTypes = org.objectweb.asm.Type.getArgumentTypes(methodDesc); Class<?> methodParamType; Class<?> argType; Integer arg; // is either an oid or null for (int i = 0; i < methodArgs.length; i++) { arg = (Integer) methodArgs[i]; if (arg == null) { arguments.add(ast.newNullLiteral()); } else { methodParamType = CaptureUtil.getClassFromDesc(methodParamTypes[i].getDescriptor()); argType = this.oidToTypeMapping.get(arg); if (methodParamType.isAssignableFrom(argType)) { arguments.add(ast.newSimpleName(this.oidToVarMapping.get(arg))); } else { // we need an up-cast final CastExpression cast = ast.newCastExpression(); cast.setType(ast.newSimpleType(ast.newName(methodParamType.getName()))); cast.setExpression(ast.newSimpleName(this.oidToVarMapping.get(arg))); arguments.add(cast); } } } } }
From source file:org.evosuite.testcarver.codegen.CodeGenerator.java
License:Open Source License
@SuppressWarnings("unchecked") private void createPlainInitStmt(final int logRecNo, final Block methodBlock, final AST ast) { // NOTE: PLAIN INIT: has always one non-null param // TODO: use primitives final int oid = this.log.objectIds.get(logRecNo); if (this.oidToVarMapping.containsKey(oid)) { // TODO this might happen because of Integer.valueOf o.. . Is this approach ok? return;// ww w . ja v a 2 s. c om } final String type = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); final Object value = this.log.params.get(logRecNo)[0]; final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); vd.setName(ast.newSimpleName(this.createNewVarName(oid, value.getClass().getName()))); final VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); if (value instanceof Class) { stmt.setType(ast.newSimpleType(ast.newSimpleName("Class"))); } else { stmt.setType(this.createAstType(type, ast)); } if (value instanceof Number) { if (value instanceof Long) { vd.setInitializer(ast.newNumberLiteral(String.valueOf(value) + 'l')); } else if (value instanceof Double) { vd.setInitializer(ast.newNumberLiteral(String.valueOf(value) + 'd')); } else { vd.setInitializer(ast.newNumberLiteral(String.valueOf(value))); } } else if (value instanceof String) { final StringLiteral literal = ast.newStringLiteral(); literal.setLiteralValue((String) value); vd.setInitializer(literal); } else if (value instanceof Character) { final CharacterLiteral literal = ast.newCharacterLiteral(); literal.setCharValue((Character) value); vd.setInitializer(literal); } else if (value instanceof Boolean) { final BooleanLiteral literal = ast.newBooleanLiteral((Boolean) value); vd.setInitializer(literal); } else if (value instanceof Class) { final TypeLiteral clazz = ast.newTypeLiteral(); clazz.setType(ast.newSimpleType(ast.newName(((Class<?>) value).getName()))); vd.setInitializer(clazz); } else { throw new IllegalStateException("An error occurred while creating a plain statement: unsupported type: " + value.getClass().getName()); } methodBlock.statements().add(stmt); }
From source file:org.evosuite.testcarver.codegen.CodeGenerator.java
License:Open Source License
@SuppressWarnings("unchecked") private void createUnobservedInitStmt(final int logRecNo, final Block methodBlock, final AST ast) { // NOTE: PLAIN INIT: has always one non-null param // TODO: use primitives final int oid = this.log.objectIds.get(logRecNo); final String type = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); final Object value = this.log.params.get(logRecNo)[0]; this.isXStreamNeeded = true; final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); // handling because there must always be a new instantiation statement for pseudo inits this.oidToVarMapping.remove(oid); vd.setName(ast.newSimpleName(this.createNewVarName(oid, type))); final MethodInvocation methodInvocation = ast.newMethodInvocation(); final Name name = ast.newSimpleName("XSTREAM"); methodInvocation.setExpression(name); methodInvocation.setName(ast.newSimpleName("fromXML")); final StringLiteral xmlParam = ast.newStringLiteral(); xmlParam.setLiteralValue((String) value); methodInvocation.arguments().add(xmlParam); final CastExpression castExpr = ast.newCastExpression(); castExpr.setType(this.createAstType(type, ast)); castExpr.setExpression(methodInvocation); vd.setInitializer(castExpr);//from w w w . j a va 2 s . c o m final VariableDeclarationStatement vs = ast.newVariableDeclarationStatement(vd); vs.setType(this.createAstType(type, ast)); methodBlock.statements().add(vs); }
From source file:org.evosuite.testcarver.codegen.CodeGenerator.java
License:Open Source License
@SuppressWarnings("unchecked") private void createFieldWriteAccessStmt(final String packageName, final int logRecNo, final Block methodBlock, final AST ast) { // assumption: all necessary statements are created and there is one variable for reach referenced object final Object[] methodArgs = this.log.params.get(logRecNo); final String methodName = this.log.methodNames.get(logRecNo); final int oid = this.log.objectIds.get(logRecNo); final int captureId = this.log.captureIds.get(logRecNo); final String fieldName = this.log.namesOfAccessedFields.get(captureId); final String typeName = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); Class<?> type = getClassForName(typeName); // try { // type = Class.forName(typeName); // } catch (ClassNotFoundException e) { // throw new RuntimeException(e); // }//from ww w.j a va 2s . co m final int fieldTypeModifiers = this.getFieldModifiers(type, fieldName); final boolean isPublic = java.lang.reflect.Modifier.isPublic(fieldTypeModifiers); final boolean haveSamePackage = type.getPackage().getName().equals(packageName); // TODO might be nicer... final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage; if (isReflectionAccessNeeded) { this.isSetFieldMethodNeeded = true; final String varName = this.oidToVarMapping.get(oid); final MethodInvocation setFieldCall = ast.newMethodInvocation(); setFieldCall.setName(ast.newSimpleName("setField")); StringLiteral stringLiteral = ast.newStringLiteral(); stringLiteral.setLiteralValue(typeName); setFieldCall.arguments().add(stringLiteral); // class name stringLiteral = ast.newStringLiteral(); stringLiteral.setLiteralValue(fieldName); setFieldCall.arguments().add(stringLiteral); // field name setFieldCall.arguments().add(ast.newSimpleName(varName)); // receiver final Integer arg = (Integer) methodArgs[0]; if (arg == null) { setFieldCall.arguments().add(ast.newNullLiteral()); // value } else { setFieldCall.arguments().add(ast.newSimpleName(this.oidToVarMapping.get(arg))); // value } methodBlock.statements().add(ast.newExpressionStatement(setFieldCall)); } else { FieldAccess fa = ast.newFieldAccess(); if (CaptureLog.PUTSTATIC.equals(methodName)) { // final String type = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); fa.setExpression(ast.newName(typeName));//.split("\\."))); } else { final String varName = this.oidToVarMapping.get(oid); fa.setExpression(ast.newSimpleName(varName)); } fa.setName(ast.newSimpleName(fieldName)); final Assignment assignment = ast.newAssignment(); assignment.setLeftHandSide(fa); final Integer arg = (Integer) methodArgs[0]; if (arg == null) { assignment.setRightHandSide(ast.newNullLiteral()); } else { final Class<?> argType = this.oidToTypeMapping.get(arg); final String fieldDesc = this.log.descList.get(logRecNo); final Class<?> fieldType = CaptureUtil.getClassFromDesc(fieldDesc); if (fieldType.isAssignableFrom(argType)) { assignment.setRightHandSide(ast.newSimpleName(this.oidToVarMapping.get(arg))); } else { // we need an up-cast final CastExpression cast = ast.newCastExpression(); cast.setType(ast.newSimpleType(ast.newName(fieldType.getName()))); cast.setExpression(ast.newSimpleName(this.oidToVarMapping.get(arg))); assignment.setRightHandSide(cast); } } methodBlock.statements().add(ast.newExpressionStatement(assignment)); } }
From source file:org.evosuite.testcarver.codegen.CodeGenerator.java
License:Open Source License
@SuppressWarnings("unchecked") private void createFieldReadAccessStmt(final String packageName, final int logRecNo, final Block methodBlock, final AST ast) { // assumption: all necessary statements are created and there is one variable for reach referenced object final String methodName = this.log.methodNames.get(logRecNo); final int oid = this.log.objectIds.get(logRecNo); final int captureId = this.log.captureIds.get(logRecNo); String returnVarName = null;//from ww w . j a v a 2s . c o m final Object returnValue = this.log.returnValues.get(logRecNo); if (!CaptureLog.RETURN_TYPE_VOID.equals(returnValue)) { Integer returnValueOID = (Integer) returnValue; final String descriptor = this.log.descList.get(logRecNo); final String fieldTypeName = org.objectweb.asm.Type.getType(descriptor).getClassName(); final String typeName = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); final String fieldName = this.log.namesOfAccessedFields.get(captureId); final String receiverVarName = this.oidToVarMapping.get(oid); final Class<?> type = getClassForName(typeName); // try { // type = Class.forName(typeName); // } catch (ClassNotFoundException e) { // throw new RuntimeException(e); // } final int fieldTypeModifiers = this.getFieldModifiers(type, fieldName); final boolean isPublic = java.lang.reflect.Modifier.isPublic(fieldTypeModifiers); final boolean haveSamePackage = type.getPackage().getName().equals(packageName); // TODO might be nicer... final boolean isReflectionAccessNeeded = !isPublic && !haveSamePackage; // e.g. Person var0 = Person.BEN; returnVarName = this.createNewVarName(returnValueOID, fieldTypeName); VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); vd.setName(ast.newSimpleName(returnVarName)); if (isReflectionAccessNeeded) { this.isGetFieldMethodNeeded = true; //-- construct getField() call final MethodInvocation getFieldCall = ast.newMethodInvocation(); getFieldCall.setName(ast.newSimpleName("getField")); StringLiteral stringLiteral = ast.newStringLiteral(); stringLiteral.setLiteralValue(fieldTypeName); getFieldCall.arguments().add(stringLiteral); // class name stringLiteral = ast.newStringLiteral(); stringLiteral.setLiteralValue(fieldName); getFieldCall.arguments().add(stringLiteral); // field name if (receiverVarName == null) { getFieldCall.arguments().add(ast.newNullLiteral()); // static call -> no receiver } else { getFieldCall.arguments().add(ast.newSimpleName(receiverVarName)); // receiver } // cast from object to field type final CastExpression cast = ast.newCastExpression(); cast.setType(ast.newSimpleType(ast.newName(fieldTypeName))); cast.setExpression(getFieldCall); vd.setInitializer(cast); } else { FieldAccess fa = ast.newFieldAccess(); if (CaptureLog.GETSTATIC.equals(methodName)) { final String classType = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); fa.setExpression(ast.newName(classType.split("\\."))); } else { fa.setExpression(ast.newSimpleName(receiverVarName)); } fa.setName(ast.newSimpleName(fieldName)); vd.setInitializer(fa); } VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); stmt.setType(this.createAstType(fieldTypeName, ast)); methodBlock.statements().add(stmt); } }
From source file:org.evosuite.testcarver.codegen.CodeGenerator.java
License:Open Source License
@SuppressWarnings({ "rawtypes", "unchecked" }) private void createSetFieldMethod(final TypeDeclaration td, final CompilationUnit cu, final AST ast) { // public static void setField(final String clazzName, final String fieldName, final Object receiver, final Object value) throws Exception // {/*from w w w. j a v a 2 s . c om*/ // final Class<?> clazz = Class.forName(clazzName); // final Field f = clazz.getDeclaredField(fieldName); // f.setAccessible(true); // f.set(receiver, value); // } //-- add necessary import statements List imports = cu.imports(); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName(new String[] { "java", "lang", "reflect", "Field" })); imports.add(id); //-- create method frame: "public static void setProtectedField(final String clazzName, final String fieldName, final Object receiver, final Object value) throws Exception" final MethodDeclaration md = ast.newMethodDeclaration(); td.bodyDeclarations().add(md); md.setName(ast.newSimpleName("setField")); List modifiers = md.modifiers(); modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD)); modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); md.thrownExceptions().add(ast.newSimpleName("Exception")); List parameters = md.parameters(); SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setType(ast.newSimpleType(ast.newSimpleName("String"))); svd.setName(ast.newSimpleName("clazzName")); parameters.add(svd); svd = ast.newSingleVariableDeclaration(); svd.setType(ast.newSimpleType(ast.newSimpleName("String"))); svd.setName(ast.newSimpleName("fieldName")); parameters.add(svd); svd = ast.newSingleVariableDeclaration(); svd.setType(ast.newSimpleType(ast.newSimpleName("Object"))); svd.setName(ast.newSimpleName("receiver")); parameters.add(svd); svd = ast.newSingleVariableDeclaration(); svd.setType(ast.newSimpleType(ast.newSimpleName("Object"))); svd.setName(ast.newSimpleName("value")); parameters.add(svd); //-- create method body // final Class<?> clazz = Class.forName(clazzName); // final Field f = clazz.getDeclaredField(fieldName); // f.setAccessible(true); // f.set(receiver, value); final Block methodBlock = ast.newBlock(); md.setBody(methodBlock); final List methodStmts = methodBlock.statements(); // final Class clazz = Class.forName(clazzName); MethodInvocation init = ast.newMethodInvocation(); init.setName(ast.newSimpleName("forName")); init.setExpression(ast.newSimpleName("Class")); init.arguments().add(ast.newSimpleName("clazzName")); VariableDeclarationFragment varDeclFrag = ast.newVariableDeclarationFragment(); varDeclFrag.setName(ast.newSimpleName("clazz")); varDeclFrag.setInitializer(init); VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag); varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Class"))); methodStmts.add(varDeclStmt); // final Field f = clazz.getDeclaredField(fieldName); init = ast.newMethodInvocation(); init.setName(ast.newSimpleName("getDeclaredField")); init.setExpression(ast.newSimpleName("clazz")); init.arguments().add(ast.newSimpleName("fieldName")); varDeclFrag = ast.newVariableDeclarationFragment(); varDeclFrag.setName(ast.newSimpleName("f")); varDeclFrag.setInitializer(init); varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag); varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Field"))); methodStmts.add(varDeclStmt); // f.setAccessible(true); MethodInvocation minv = ast.newMethodInvocation(); minv.setName(ast.newSimpleName("setAccessible")); minv.setExpression(ast.newSimpleName("f")); minv.arguments().add(ast.newBooleanLiteral(true)); methodStmts.add(ast.newExpressionStatement(minv)); // f.set(receiver, value); minv = ast.newMethodInvocation(); minv.setName(ast.newSimpleName("set")); minv.setExpression(ast.newSimpleName("f")); minv.arguments().add(ast.newSimpleName("receiver")); minv.arguments().add(ast.newSimpleName("value")); methodStmts.add(ast.newExpressionStatement(minv)); }
From source file:org.evosuite.testcarver.codegen.CodeGenerator.java
License:Open Source License
@SuppressWarnings({ "rawtypes", "unchecked" }) private void createGetFieldMethod(final TypeDeclaration td, final CompilationUnit cu, final AST ast) { // public static void setField(final String clazzName, final String fieldName, final Object receiver, final Object value) throws Exception // {// ww w . j a va 2 s . co m // final Class<?> clazz = Class.forName(clazzName); // final Field f = clazz.getDeclaredField(fieldName); // f.setAccessible(true); // f.set(receiver, value); // } //-- add necessary import statements List imports = cu.imports(); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName(new String[] { "java", "lang", "reflect", "Field" })); imports.add(id); //-- create method frame: "public static Object setProtectedField(final String clazzName, final String fieldName, final Object receiver) throws Exception" final MethodDeclaration md = ast.newMethodDeclaration(); td.bodyDeclarations().add(md); md.setName(ast.newSimpleName("getField")); List modifiers = md.modifiers(); modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD)); modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD)); md.thrownExceptions().add(ast.newSimpleName("Exception")); List parameters = md.parameters(); SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setType(ast.newSimpleType(ast.newSimpleName("String"))); svd.setName(ast.newSimpleName("clazzName")); parameters.add(svd); svd = ast.newSingleVariableDeclaration(); svd.setType(ast.newSimpleType(ast.newSimpleName("String"))); svd.setName(ast.newSimpleName("fieldName")); parameters.add(svd); svd = ast.newSingleVariableDeclaration(); svd.setType(ast.newSimpleType(ast.newSimpleName("Object"))); svd.setName(ast.newSimpleName("receiver")); parameters.add(svd); md.setReturnType2(ast.newSimpleType(ast.newSimpleName("Object"))); //-- create method body // final Class<?> clazz = Class.forName(clazzName); // final Field f = clazz.getDeclaredField(fieldName); // f.setAccessible(true); // return f.get(receiver); final Block methodBlock = ast.newBlock(); md.setBody(methodBlock); final List methodStmts = methodBlock.statements(); // final Class clazz = Class.forName(clazzName); MethodInvocation init = ast.newMethodInvocation(); init.setName(ast.newSimpleName("forName")); init.setExpression(ast.newSimpleName("Class")); init.arguments().add(ast.newSimpleName("clazzName")); VariableDeclarationFragment varDeclFrag = ast.newVariableDeclarationFragment(); varDeclFrag.setName(ast.newSimpleName("clazz")); varDeclFrag.setInitializer(init); VariableDeclarationStatement varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag); varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Class"))); methodStmts.add(varDeclStmt); // final Field f = clazz.getDeclaredField(fieldName); init = ast.newMethodInvocation(); init.setName(ast.newSimpleName("getDeclaredField")); init.setExpression(ast.newSimpleName("clazz")); init.arguments().add(ast.newSimpleName("fieldName")); varDeclFrag = ast.newVariableDeclarationFragment(); varDeclFrag.setName(ast.newSimpleName("f")); varDeclFrag.setInitializer(init); varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag); varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Field"))); methodStmts.add(varDeclStmt); // f.setAccessible(true); MethodInvocation minv = ast.newMethodInvocation(); minv.setName(ast.newSimpleName("setAccessible")); minv.setExpression(ast.newSimpleName("f")); minv.arguments().add(ast.newBooleanLiteral(true)); methodStmts.add(ast.newExpressionStatement(minv)); // return f.get(receiver); minv = ast.newMethodInvocation(); minv.setName(ast.newSimpleName("get")); minv.setExpression(ast.newSimpleName("f")); minv.arguments().add(ast.newSimpleName("receiver")); final ReturnStatement returnStmt = ast.newReturnStatement(); returnStmt.setExpression(minv); methodStmts.add(returnStmt); }