List of usage examples for org.eclipse.jdt.core.dom.rewrite ASTRewrite createStringPlaceholder
public final ASTNode createStringPlaceholder(String code, int nodeType)
From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.PathWithUncertaintyTestStrategy.java
License:Open Source License
/** * Generates a class to be used in executing the test plan. * The class is abstract because at this point it is unclear how to assert that a certain state has been reached. * Thus, the assertStateReached will be abstract methods. * @param stateGraph/*from ww w. j a v a2s.com*/ */ public Document generateTestPlan(StateMachineStateGraph stateGraph) { Document doc = new Document( "public abstract class TestPlanForStateMachine" + stateGraph.getStateMachineName() + " { \n"); //from here we use the cumbersome and extremely detailed Eclipse recommended DOM/AST library ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(doc.get().toCharArray()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.recordModifications(); AST ast = cu.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); //create method which will contain one test plan (might be cloned and branched for each if-else in the state machine diagram) MethodDeclaration testPlanMethodDeclaration = ast.newMethodDeclaration(); testPlanMethodDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); testPlanMethodDeclaration.setName(ast.newSimpleName("testPlan")); testPlanMethodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); //return true if successful or false otherwise //create method body Block testPlanMethodBody = ast.newBlock(); testPlanMethodDeclaration.setBody(testPlanMethodBody); //create recursively the test plan by parsing the state graph starting with initial state try { generatePlanForState(stateGraph.getInitialState(), rewriter, testPlanMethodDeclaration, new HashSet<StateMachineStateTransition>()); } catch (NoSuchStateException e) { e.printStackTrace(); } ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY); //add all generated abstract methods for (Map.Entry<String, MethodDeclaration> entry : generatedAbstractMethods.entrySet()) { listRewrite.insertLast(entry.getValue(), null); } if (generatedPlans.isEmpty()) { notifyUser("No test plans containing uncertainty states could have been generated. " + "\n Please ensure selected state machine has at least one state with at least one uncertainty" + "\n Please ensure there is at least one InitialState, one FinalState, and one path between Initial and Final states which passes through" + "at least one state with at least one uncertainty"); } int index = 1; //add generated plan methods for (Map.Entry<String, MethodDeclaration> entry : generatedPlans.entrySet()) { //rename to PLAN_METHOD_LEADING + plan index from PLAN_METHOD_LEADING + UUID MethodDeclaration method = entry.getValue(); method.setName(ast.newSimpleName(PLAN_METHOD_LEADING + index++)); listRewrite.insertLast(method, null); } //add final } listRewrite.insertLast(rewriter.createStringPlaceholder("}\n", ASTNode.EMPTY_STATEMENT), null); TextEdit edits = rewriter.rewriteAST(doc, null); try { UndoEdit undo = edits.apply(doc); } catch (MalformedTreeException | BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(doc.get()); return doc; }
From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.TransitionCorrectnessTestStrategy.java
License:Open Source License
/** * Generates a class to be used in executing the test plan. * The class is abstract because at this point it is unclear how to assert that a certain state has been reached. * Thus, the assertStateReached will be abstract methods. * @param stateGraph/*from ww w . ja v a 2s .com*/ */ public Document generateTestPlan(StateMachineStateGraph stateGraph) { Document doc = new Document( "public abstract class TestPlanForStateMachine" + stateGraph.getStateMachineName() + " { \n"); //from here we use the cumbersome and extremely detailed Eclipse recommended DOM/AST library ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(doc.get().toCharArray()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.recordModifications(); AST ast = cu.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); //create method which will contain one test plan (might be cloned and branched for each if-else in the state machine diagram) MethodDeclaration testPlanMethodDeclaration = ast.newMethodDeclaration(); testPlanMethodDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); testPlanMethodDeclaration.setName(ast.newSimpleName("testPlan")); testPlanMethodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); //return true if successful or false otherwise //create method body Block testPlanMethodBody = ast.newBlock(); testPlanMethodDeclaration.setBody(testPlanMethodBody); //create recursively the test plan by parsing the state graph starting with initial state try { generatePlanForState(stateGraph.getInitialState(), rewriter, testPlanMethodDeclaration, new HashSet<StateMachineStateTransition>()); } catch (NoSuchStateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY); //add all generated abstract methods for (Map.Entry<String, MethodDeclaration> entry : generatedAbstractMethods.entrySet()) { listRewrite.insertLast(entry.getValue(), null); } int index = 1; //add generated plan methods if (generatedPlans.isEmpty()) { notifyUser("No test plans could have been generated. " + "\n Please ensure selected state machine has at least one complete path from initial to final state." + "\n Please ensure there is at least one InitialState, one FinalState, and one path between Initial and Final states"); } for (Map.Entry<String, MethodDeclaration> entry : generatedPlans.entrySet()) { //rename to PLAN_METHOD_LEADING + plan index from PLAN_METHOD_LEADING + UUID MethodDeclaration method = entry.getValue(); method.setName(ast.newSimpleName(PLAN_METHOD_LEADING + index++)); listRewrite.insertLast(method, null); } //add final } listRewrite.insertLast(rewriter.createStringPlaceholder("}\n", ASTNode.EMPTY_STATEMENT), null); TextEdit edits = rewriter.rewriteAST(doc, null); try { UndoEdit undo = edits.apply(doc); } catch (MalformedTreeException | BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(doc.get()); return doc; }
From source file:ch.acanda.eclipse.pmd.java.resolution.design.UseUtilityClassQuickFix.java
License:Open Source License
@SuppressWarnings("unchecked") private void addPrivateConstructor(final TypeDeclaration typeDeclaration, final ASTRewrite rewrite) { final AST ast = typeDeclaration.getAST(); final MethodDeclaration constructor = (MethodDeclaration) ast.createInstance(MethodDeclaration.class); constructor.setConstructor(true);/*from w ww .j ava 2s . c o m*/ final Modifier modifier = (Modifier) ast.createInstance(Modifier.class); modifier.setKeyword(ModifierKeyword.PRIVATE_KEYWORD); constructor.modifiers().add(modifier); constructor.setName(ASTUtil.copy(typeDeclaration.getName())); final Block body = (Block) ast.createInstance(Block.class); constructor.setBody(body); final ListRewrite statementRewrite = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY); final ASTNode comment = rewrite.createStringPlaceholder("// hide constructor of utility class", ASTNode.EMPTY_STATEMENT); statementRewrite.insertFirst(comment, null); final int position = findConstructorPosition(typeDeclaration); final ListRewrite bodyDeclarationRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); bodyDeclarationRewrite.insertAt(constructor, position, null); }
From source file:com.arcbees.gwtp.plugin.core.presenter.CreatePresenterPage.java
License:Apache License
private void addMethodsToNameTokens(ICompilationUnit unit, String nameToken, IProgressMonitor monitor) throws JavaModelException, MalformedTreeException, BadLocationException { String fieldName = getFieldNameFromNameToken(nameToken); Document document = new Document(unit.getSource()); CompilationUnit astRoot = initAstRoot(unit, monitor); // creation of ASTRewrite ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); // find existing method MethodDeclaration method = findMethod(astRoot, getNameTokenMethod(fieldName)); if (method != null) { logger.severe("FYI: the method in nameTokens already exists." + method.toString()); return;//from w ww. j a v a 2 s. c om } List types = astRoot.types(); ASTNode rootNode = (ASTNode) types.get(0); ListRewrite listRewrite = rewrite.getListRewrite(rootNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); ASTNode fieldNode = rewrite.createStringPlaceholder( "public static final String " + fieldName + " = \"" + nameToken + "\";", ASTNode.EMPTY_STATEMENT); StringBuilder nameTokenMethod = new StringBuilder(); nameTokenMethod.append("public static String ").append(getNameTokenMethod(fieldName)).append("() {\n") .append("return " + fieldName + ";\n").append("}\n"); ASTNode methodNode = rewrite.createStringPlaceholder(nameTokenMethod.toString(), ASTNode.EMPTY_STATEMENT); listRewrite.insertFirst(fieldNode, null); listRewrite.insertLast(methodNode, null); // computation of the text edits TextEdit edits = rewrite.rewriteAST(document, unit.getJavaProject().getOptions(true)); // computation of the new source code edits.apply(document); // format code String newSource = new CodeFormattingUtil(getJavaProject(), monitor).formatCodeJavaClass(document); // update of the compilation unit and save it IBuffer buffer = unit.getBuffer(); buffer.setContents(newSource); buffer.save(monitor, true); }
From source file:com.arcbees.gwtp.plugin.core.presenter.CreatePresenterPage.java
License:Apache License
/** * TODO extract this possibly, but I think I'll wait till I get into slots * before I do it see what is common./*from w w w . j a v a 2 s.com*/ */ private void createPresenterGinlink(ICompilationUnit unit, String modulePackageName, String moduleName, IProgressMonitor monitor) throws JavaModelException, MalformedTreeException, BadLocationException { unit.createImport(modulePackageName + "." + moduleName, null, monitor); Document document = new Document(unit.getSource()); CompilationUnit astRoot = initAstRoot(unit, monitor); // creation of ASTRewrite ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST()); // find the configure method MethodDeclaration method = findMethod(astRoot, "configure"); if (method == null) { logger.severe("createPresenterGinLink() unit did not have configure implementation."); return; } // presenter configure method install(new Module()); String installModuleStatement = "install(new " + moduleName + "());"; Block block = method.getBody(); ListRewrite listRewrite = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); ASTNode placeHolder = rewrite.createStringPlaceholder(installModuleStatement, ASTNode.EMPTY_STATEMENT); listRewrite.insertFirst(placeHolder, null); // computation of the text edits TextEdit edits = rewrite.rewriteAST(document, unit.getJavaProject().getOptions(true)); // computation of the new source code edits.apply(document); String newSource = document.get(); // update of the compilation unit and save it IBuffer buffer = unit.getBuffer(); buffer.setContents(newSource); buffer.save(monitor, true); }
From source file:com.google.gdt.eclipse.appengine.rpc.markers.quickfixes.CreateRequestFactoryMethodProposal.java
License:Open Source License
protected MethodDeclaration createMethodDeclaration(ASTRewrite rewriter) { StringBuffer buf = new StringBuffer(); try {//from w w w. j a va 2 s. c o m IMethod method = (IMethod) serviceMethod.resolveBinding().getJavaElement(); projectEntities = RequestFactoryUtils.findTypes(requestContextType.getJavaProject(), RpcType.ENTITY); proxies = RequestFactoryUtils.findTypes(method.getJavaProject(), RpcType.PROXY); entityList = RequestFactoryCodegenUtils.getEntitiesInMethodSignature(method, projectEntities); buf.append(RequestFactoryCodegenUtils.constructMethodSignature(method, projectEntities)); List<String> entityName = new ArrayList<String>(); for (IType entity : entityList) { entityName.add(entity.getFullyQualifiedName()); } for (IType proxy : proxies) { IAnnotation annotation = proxy.getAnnotation("ProxyForName"); //$NON-NLS-N$ IMemberValuePair[] values = annotation.getMemberValuePairs(); for (IMemberValuePair pair : values) { if (pair.getMemberName().equals("value")) { String typeName = (String) pair.getValue(); if (entityName.contains(typeName)) { // entity has proxy, remove from list removeFromEntityList(typeName); } } } } // if any proxies were created, add those methods too for (IType entity : entityList) { String methodString = RequestFactoryCodegenUtils.constructRequestForEntity(entity.getElementName()); buf.append(methodString); } } catch (JavaModelException e) { AppEngineRPCPlugin.log(e); return null; } MethodDeclaration methodDeclaration = (MethodDeclaration) rewriter.createStringPlaceholder( CodegenUtils.format(buf.toString(), CodeFormatter.K_CLASS_BODY_DECLARATIONS), ASTNode.METHOD_DECLARATION); return methodDeclaration; }
From source file:edu.illinois.compositerefactorings.refactorings.copymembertosubtype.CopyMemberToSubtypeRefactoringProcessor.java
License:Open Source License
/** * {@link org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor#copyBodyOfPushedDownMethod(ASTRewrite, IMethod, MethodDeclaration, MethodDeclaration, TypeVariableMaplet[])} *///w ww . j av a 2s . com private void copyBodyOfPushedDownMethod(ASTRewrite targetRewrite, IMethod method, MethodDeclaration oldMethod, MethodDeclaration newMethod, TypeVariableMaplet[] mapping) throws JavaModelException { Block body = oldMethod.getBody(); if (body == null) { newMethod.setBody(null); return; } try { final IDocument document = new Document(method.getCompilationUnit().getBuffer().getContents()); final ASTRewrite rewriter = ASTRewrite.create(body.getAST()); final ITrackedNodePosition position = rewriter.track(body); body.accept(new TypeVariableMapper(rewriter, mapping)); rewriter.rewriteAST(document, getDeclaringType().getCompilationUnit().getJavaProject().getOptions(true)) .apply(document, TextEdit.NONE); String content = document.get(position.getStartPosition(), position.getLength()); String[] lines = Strings.convertIntoLines(content); Strings.trimIndentation(lines, method.getJavaProject(), false); content = Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(method)); newMethod.setBody((Block) targetRewrite.createStringPlaceholder(content, ASTNode.BLOCK)); } catch (MalformedTreeException exception) { JavaPlugin.log(exception); } catch (BadLocationException exception) { JavaPlugin.log(exception); } }
From source file:edu.illinois.keshmesh.transformer.core.LCK03JFixer.java
License:Open Source License
/** * FIXME://from w w w.j av a 2s .c om * * Break the method into smaller ones. * * Rethrow the exception as CoreException * * Preserve comments. * * Preserve formatting. * */ @Override public Change createChange(IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException { ITextFileBufferManager textFileBufferManager = null; try { //Retrieving the Document out of IPath textFileBufferManager = FileBuffers.getTextFileBufferManager(); textFileBufferManager.connect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor); ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(bugPosition.getSourcePath(), LocationKind.IFILE); IDocument document = textFileBuffer.getDocument(); try { Logger.log(document.get(bugPosition.getFirstOffset(), bugPosition.getLength())); } catch (BadLocationException e1) { e1.printStackTrace(); } // Parsing the Document ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(document.get().toCharArray()); parser.setResolveBindings(true); CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(progressMonitor); // Retrieving the begin and end indexes of synchronized command int bugLineOffset = document.getLineInformation(bugPosition.getFirstLine() - 1).getOffset(); int bugLineLength = document.getLineInformation(bugPosition.getFirstLine() - 1).getLength(); String bugLine = document.get(bugLineOffset, bugLineLength); int syncCommandBeginIndex = getSynchronizedCommandBeginIndex(bugLine); int syncCommandLastIndex = getSynchronizedCommandLastIndex(bugLine, syncCommandBeginIndex); // Extracting the synchronized command expression String bugLineAfterSync = bugLine.substring(syncCommandBeginIndex + SYNC_COMMAND.length()); int openParenthesisIndex = bugLineAfterSync.indexOf('(') + syncCommandBeginIndex + SYNC_COMMAND.length(); String synchExpression = bugLine.substring(openParenthesisIndex + 1, syncCommandLastIndex); // Computing the begin and end offset of the synchronized command int syncCommandBeginOffset = bugLineOffset + syncCommandBeginIndex; int syncCommandLastOffset = bugLineOffset + syncCommandLastIndex; // Getting the synchronized command AST node ASTNode monitorNode = NodeFinder.perform(compilationUnit, syncCommandBeginOffset, syncCommandLastOffset - syncCommandBeginOffset + 1); SynchronizedStatement synchronizedStatement = (SynchronizedStatement) monitorNode; List synchBodyStatements = synchronizedStatement.getBody().statements(); // Creating a "local variable assignment" statement and a try/catch/final block to be replaced at monitor node place //AST ast = synchronizedStatement.getAST(); ASTRewrite rewriter = ASTRewrite.create(compilationUnit.getAST()); String localVarNameForLock = "tempLock"; String localVarAssignment = LCK03JBugPattern.LOCK + " " + localVarNameForLock + " = " + synchExpression + ";\n"; String tryFinalBlockStatements = "try {\n" + localVarNameForLock + ".lock();\n"; for (Object statement : synchBodyStatements) { tryFinalBlockStatements += statement; } tryFinalBlockStatements += "} finally {\n" + localVarNameForLock + ".unlock();\n}"; // Rewriting the monitor node ASTNode astNode = rewriter.createStringPlaceholder(localVarAssignment + tryFinalBlockStatements, TryStatement.TRY_STATEMENT); rewriter.replace(synchronizedStatement, astNode, null); TextEdit textEdit = rewriter.rewriteAST(document, null); UndoEdit undoEdit = textEdit.apply(document); //Committing changes to the source file textFileBuffer.commit(progressMonitor, true); } catch (BadLocationException e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to fix LCK03J.", e)); } finally { textFileBufferManager.disconnect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor); } return null; }
From source file:jmockit.assist.MockMethodCompletionProposal.java
License:Open Source License
@SuppressWarnings("unchecked") private void setReturnStatement(final MethodDeclaration stub, final IMethodBinding methodToOverride, final ITypeBinding declaringType, final AST ast, final ASTRewrite rewrite) throws JavaModelException, CoreException { Expression expression = ASTNodeFactory.newDefaultExpression(ast, stub.getReturnType2(), stub.getExtraDimensions());/*w w w .j a va 2 s .c om*/ if (expression != null) { ReturnStatement returnStatement = ast.newReturnStatement(); returnStatement.setExpression(expression); String delimiter = cunit.findRecommendedLineSeparator(); Map<String, String> options = fJavaProject.getOptions(true); String bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, options); String placeHolder = CodeGeneration.getMethodBodyContent(cunit, declaringType.getName(), methodToOverride.getName(), false, bodyStatement, delimiter); if (placeHolder != null) { ASTNode todoNode = rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT); stub.getBody().statements().clear(); stub.getBody().statements().add(todoNode); } } }
From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.UnresolvedElementsSubProcessor.java
License:Open Source License
private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance, int maxProposals) throws CoreException { ImportRewrite importRewrite = null;/* ww w. j a v a2s. co m*/ String simpleName = fullName; String packName = Signature.getQualifier(fullName); if (packName.length() > 0) { // no imports for primitive types, type variables importRewrite = StubUtility.createImportRewrite((CompilationUnit) node.getRoot(), true); simpleName = importRewrite.addImport(fullName); } if (!isLikelyTypeName(simpleName)) { relevance -= 2; } ASTRewriteCorrectionProposal proposal; if (importRewrite != null && node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only // import only String[] arg = { simpleName, packName }; String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, arg); Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); int boost = QualifiedTypeNameHistory.getBoost(fullName, 0, maxProposals); proposal = new AddImportCorrectionProposal(label, cu, relevance + 100 + boost, image, packName, simpleName, (SimpleName) node); proposal.setCommandId(ADD_IMPORT_ID); } else { String label; if (packName.length() == 0) { label = Messages.format( CorrectionMessages.UnresolvedElementsSubProcessor_changetype_nopack_description, simpleName); } else { String[] arg = { simpleName, packName }; label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetype_description, arg); } ASTRewrite rewrite = ASTRewrite.create(node.getAST()); rewrite.replace(node, rewrite.createStringPlaceholder(simpleName, ASTNode.SIMPLE_TYPE), null); Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance, image); } if (importRewrite != null) { proposal.setImportRewrite(importRewrite); } return proposal; }