List of usage examples for org.eclipse.jdt.core ICompilationUnit applyTextEdit
public UndoEdit applyTextEdit(TextEdit edit, IProgressMonitor monitor) throws JavaModelException;
From source file:com.ecfeed.ui.common.JavaDocSupport.java
License:Open Source License
private static void exportJavadoc(IMember member, String comments) throws JavaModelException { if (member != null) { if (comments == null || comments.length() == 0) { removeJavadoc(member);/*ww w . jav a 2s . co m*/ } else { ISourceRange currentJavaDocRange = member.getJavadocRange(); TextEdit edit = null; String indent = getIndent(member); if (currentJavaDocRange != null) { String javadoc = addJavadocFormatting(comments, indent); edit = new ReplaceEdit(currentJavaDocRange.getOffset(), currentJavaDocRange.getLength(), javadoc); } else if (member.getSourceRange().getOffset() >= 0) { boolean moveToNewLine = false; if (indent.matches("\\s*") == false) { indent = trimIndent(indent); moveToNewLine = true; } String javadoc = addJavadocFormatting(comments, indent); String comment = javadoc + "\n" + indent; if (moveToNewLine) { comment = "\n" + indent + comment; } edit = new InsertEdit(member.getSourceRange().getOffset(), comment); } if (edit != null) { ICompilationUnit unit = member.getCompilationUnit(); if (unit != null) { unit.becomeWorkingCopy(null); unit.applyTextEdit(edit, null); unit.commitWorkingCopy(true, null); } } } } }
From source file:com.ecfeed.ui.common.JavaDocSupport.java
License:Open Source License
private static void removeJavadoc(IMember member) throws JavaModelException { ISourceRange currentJavaDocRange = member.getJavadocRange(); if (currentJavaDocRange != null) { ICompilationUnit unit = member.getCompilationUnit(); String source = unit.getSource(); int offset = currentJavaDocRange.getOffset(); int length = currentJavaDocRange.getLength(); while (((Character) source.charAt(offset + length)).toString().matches("\\s")) { ++length;/*from w w w . j a v a 2 s . c om*/ } unit.applyTextEdit(new DeleteEdit(offset, length), null); unit.commitWorkingCopy(false, null); } }
From source file:com.google.gdt.eclipse.appengine.rpc.util.CodegenUtils.java
License:Open Source License
public static void applyEdit(ICompilationUnit cu, TextEdit edit, boolean save, IProgressMonitor monitor) throws CoreException { IFile file = (IFile) cu.getResource(); if (!save || !file.exists()) { cu.applyTextEdit(edit, monitor); } else {/* w w w . j a v a2 s . c om*/ if (monitor == null) { monitor = new NullProgressMonitor(); } monitor.beginTask("Apply edits", 2); //$NON-NLS-1$ try { IStatus status = Resources.makeCommittable(file, null); if (!status.isOK()) { AppEngineRPCPlugin.getLogger().logError("Rpc Service generation: unable to apply edit to file " //$NON-NLS-1$ + cu.getElementName()); } cu.applyTextEdit(edit, new SubProgressMonitor(monitor, 1)); cu.save(new SubProgressMonitor(monitor, 1), true); } finally { monitor.done(); } } }
From source file:com.gowan.plugin.handlers.JUnit3Handler.java
License:Open Source License
/** * /* w w w . j a va 2 s . c om*/ * @param unit * @throws JavaModelException */ private void createAST(ICompilationUnit unit) throws JavaModelException { CompilationUnit parse = parse(unit); JUnit3Visitor visitor = new JUnit3Visitor(); parse.accept(visitor); IDocument doc = new Document(unit.getSource()); AST ast = parse.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); JUnit3 junit = visitor.getJUnit3(); TypeDeclaration td = (TypeDeclaration) parse.types().get(0); ITrackedNodePosition tdLocation = rewrite.track(td); if (junit.getKlass() != null) { rewrite.replace(td.getSuperclassType(), null, null); } else { return; // Skip if the class does not extend junit.framework.TestCase } // imports ImportDeclaration afterImport = ast.newImportDeclaration(); afterImport.setName(ast.newName(AFTER)); ImportDeclaration beforeImport = ast.newImportDeclaration(); beforeImport.setName(ast.newName(BEFORE)); ImportDeclaration testImport = ast.newImportDeclaration(); testImport.setName(ast.newName(TEST)); ListRewrite lrw = rewrite.getListRewrite(parse, CompilationUnit.IMPORTS_PROPERTY); if (junit.getTestCaseImport() != null) { lrw.remove(junit.getTestCaseImport(), null); lrw.insertLast(afterImport, null); lrw.insertLast(beforeImport, null); lrw.insertLast(testImport, null); } if (junit.getSetUp() != null) { transformSetUp(ast, rewrite, junit); } if (junit.getTearDown() != null) { transformTearDown(ast, rewrite, junit); } if (junit.getTest() != null && !junit.getTest().isEmpty()) { transformTest(ast, rewrite, junit); } TextEdit edits = rewrite.rewriteAST(doc, null); unit.applyTextEdit(edits, null); }
From source file:com.ixenit.membersort.handlers.SortHandler.java
License:Apache License
private void _processUnit(ICompilationUnit cu) throws JavaModelException, MalformedTreeException, BadLocationException { // Parse the javacode to be able to modify it ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(cu);// w w w.j a va2 s .co m // Create a copy of the CompilationUnit to work on CompilationUnit copyOfUnit = (CompilationUnit) parser.createAST(null); MemberComparator comparator = new MemberComparator(); // This helper method will sort our java code with the given comparator TextEdit edits = CompilationUnitSorter.sort(copyOfUnit, comparator, 0, null, null); // The sort method gives us null if there weren't any changes if (edits != null) { ICompilationUnit workingCopy = cu.getWorkingCopy(new WorkingCopyOwner() { }, null); workingCopy.applyTextEdit(edits, null); // Commit changes workingCopy.commitWorkingCopy(true, null); } }
From source file:com.motorola.studio.android.generatecode.JavaCodeModifier.java
License:Apache License
/** * Insert code into the class (activity / fragment) and adds imports if necessary. * @throws JavaModelException Thrown if there were problems parsing the java file. */// w ww .j ava 2s . c o m public void insertCode(IProgressMonitor monitor, IEditorPart editor) throws JavaModelException { final SubMonitor theMonitor = SubMonitor.convert(monitor); IResource resource = codeGeneratorData.getResource(); if (resource instanceof IFile) { IFile java = (IFile) resource; StudioLogger.info("Trying to insert code for class: " + java.getFullPath() + " based on resource " //$NON-NLS-1$ + getDataResource()); IDocument document = null; try { document = ((AbstractTextEditor) editor).getDocumentProvider().getDocument(editor.getEditorInput()); final ICompilationUnit compUnit = getCodeGeneratorData().getICompilationUnit(); CompilationUnit cpU = getCodeGeneratorData().getCompilationUnit(); try { cpU.recordModifications(); initVariables(); codeGenerators.clear(); codeGenerators = populateListOfCodeGenerators(getCodeGeneratorData()); theMonitor.beginTask(CodeUtilsNLS.JavaViewBasedOnLayoutModifier_InsertingCode, 1000 * getNumberOfTasks()); callCodeGenerators(theMonitor, java); addImportsIfRequired(theMonitor, cpU); Map<?, ?> mapOptions = JavaCore.create(java.getProject()).getOptions(true); final TextEdit edit = cpU.rewrite(document, mapOptions); PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { try { compUnit.applyTextEdit(edit, theMonitor); } catch (JavaModelException e) { StudioLogger.error(this.getClass(), "Error applying changes: " + e.getMessage(), e); //$NON-NLS-1$ } } }); } catch (CoreException e) { StudioLogger.error(this.getClass(), "Error changing AST activity/fragment: " + e.getMessage()); //$NON-NLS-1$ throw new JavaModelException(e); } catch (RuntimeException rte) { StudioLogger.error(this.getClass(), "Error changing AST activity/fragment: " + rte.getMessage()); //$NON-NLS-1$ throw new JavaModelException(rte, IJavaModelStatusConstants.CORE_EXCEPTION); } } catch (CoreException e) { StudioLogger.error(this.getClass(), "Error creating IDocument from java file: " + java + " message: " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ throw new JavaModelException(e, IJavaModelStatusConstants.CORE_EXCEPTION); } finally { theMonitor.done(); } } }
From source file:com.motorola.studio.android.model.ActivityBasedOnTemplate.java
License:Apache License
/** * Creates the Java Class file based on text template file * /* w w w . j a v a 2 s . c o m*/ * @param sourcePath The path to the file * @param monitor The progress monitor * @throws JavaModelException * @throws AndroidException */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void createJavaClassFileFromTemplate(String[] sourcePath, IProgressMonitor monitor) throws JavaModelException, AndroidException { //only one class supported for (int i = 0; i < sourcePath.length; i++) { String loadedTemplate = EclipseUtils.readEmbeddedResource(CodeUtilsActivator.getDefault().getBundle(), sourcePath[i]); String packageName = getPackageFragment().getElementName(); loadedTemplate = loadedTemplate.replaceAll(CLASS_REPLACE_TAG, getName()); loadedTemplate = loadedTemplate.replaceAll(PACKAGE_REPLACE_TAG, packageName); loadedTemplate = loadedTemplate.replaceAll("#FILL_PARENT_LPARAM#", getApiVersion() > 7 ? "MATCH_PARENT" : "FILL_PARENT"); try { loadedTemplate = loadedTemplate.replaceAll("#ManifestPackageName#", //$NON-NLS-1$ getManifestPackageName(getProject())); } catch (CoreException e) { throw new AndroidException("Failed to get manifest file to add import from R", e); //$NON-NLS-1$ } if ((sample != null) && sample.equals(ActivityBasedOnTemplate.DATABASE_LIST_SAMPLE_LOCALIZED)) { collector = getDatabaseSampleActivityParametersWizardCollector(); if (collector != null) { collector.setDatabaseName(this.collectorDatabaseName); collector.setTable(this.collectorTable); collector.setSelectedColumns(collectorColumnList); collector.setSqlOpenHelperClassName(getSqlOpenHelperClassName()); collector.setSqlOpenHelperPackageName(getSqlOpenHelperPackageName()); collector.setCreateOpenHelper(isCreateOpenHelper()); //using Database list sample - it is an special case because it get data from an specific .db table loadedTemplate = loadedTemplate.replaceAll("#dbName#", collector.getDatabaseName()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#tableName#", collector.getTableName()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#tableNameUpperCase#", collector.getTableName() //$NON-NLS-1$ .toUpperCase()); loadedTemplate = loadedTemplate.replaceAll("#tableNameLowerCase#", collector.getTableName() //$NON-NLS-1$ .toLowerCase()); loadedTemplate = loadedTemplate.replaceAll("#columsNames#", collector.getColumnsNames()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#constColumnsNames#", //$NON-NLS-1$ collector.getConstColumnsNames()); loadedTemplate = loadedTemplate.replaceAll("#columnGetValues#", collector.getCursorValues()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#columnAddRows#", collector.getAddColumnsToRow()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#sqlOpenHelperName#", //$NON-NLS-1$ getSqlOpenHelperClassName()); loadedTemplate = loadedTemplate.replaceAll("#imports#", collector.getImports()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#getReadableDatabase#", //$NON-NLS-1$ collector.getReadableDatabase()); if (isCreateOpenHelper()) { collector.createSqlOpenHelper(getProject(), monitor); } } } //replace the main activity of the project, first used by action_bar template try { //assume mainActivity be the activity we are creating (if the project has no main activity). Try to find the real main activity if the isMainActivity flag is false. String mainActivityName = getName(); if (!isMainActivity) { ActivityNode mainActivityNode = AndroidProjectManifestFile.getFromProject(getProject()) .getMainActivity(); if (mainActivityNode != null) { mainActivityName = mainActivityNode.getNodeProperties().get("android:name"); //remove a possible '.' that activities may contain before the name if ((mainActivityName.length() > 0) && (mainActivityName.charAt(0) == '.')) { mainActivityName = mainActivityName.substring(1, mainActivityName.length()); } } } loadedTemplate = loadedTemplate.replaceAll(MAIN_ACTIVITY_REPLACE_TAG, mainActivityName); } catch (CoreException e) { StudioLogger.error("Could not get Android Manifest File from project."); } loadedTemplate = replaceResourceNames(loadedTemplate); IPackageFragment targetPackage = getPackageFragmentRoot() .getPackageFragment(getPackageFragment().getElementName()); if (!targetPackage.exists()) { getPackageFragmentRoot().createPackageFragment(targetPackage.getElementName(), true, monitor); } /* * Create activity class. Only the first src resource will become the Activity subclass. * The other classes will be copied AS IS */ String resourceName = i == 0 ? getName() + JAVA_EXTENSION : Path.fromPortableString(sourcePath[i]).lastSegment(); ICompilationUnit cu = targetPackage.createCompilationUnit(resourceName, loadedTemplate, true, monitor); //indent activity class try { ICompilationUnit workingCopy = cu.getWorkingCopy(monitor); IDocument document = new DocumentAdapter(workingCopy.getBuffer()); //get project indentation configuration Map mapOptions = JavaCore.create(getProject()).getOptions(true); //changes to be applyed to the document TextEdit textEdit = CodeFormatterUtil.format2( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, document.get(), 0, System.getProperty("line.separator"), mapOptions); //$NON-NLS-1$ workingCopy.applyTextEdit(textEdit, monitor); workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null); workingCopy.commitWorkingCopy(true, monitor); workingCopy.discardWorkingCopy(); } catch (Exception ex) { //do nothing - indentation fails } } }
From source file:com.motorolamobility.preflighting.samplechecker.findviewbyid.quickfix.FindViewByIdMarkerResolution.java
License:Apache License
public void run(IMarker marker) { IResource resource = marker.getResource(); final ICompilationUnit iCompilationUnit = JavaCore.createCompilationUnitFrom((IFile) resource); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(JavaCore.create(resource.getProject())); parser.setResolveBindings(true);//from w w w . j a va 2s . c om parser.setSource(iCompilationUnit); parser.setStatementsRecovery(true); parser.setBindingsRecovery(true); final CompilationUnit compUnit = (CompilationUnit) parser.createAST(null); try { final int lineNumber = marker.getAttribute(IMarker.LINE_NUMBER, -1); MethodInvocation invokedMethod = null; //Look for the invokedMethod that shall be moved invokedMethod = getMethodInvocation(compUnit, lineNumber, invokedMethod); IEditorPart editor = openEditor(iCompilationUnit); ASTNode loopNode = getLoopNode(invokedMethod); //Retrieve block parent for the loop statement. Block targetBlock = (Block) loopNode.getParent(); List<Statement> statements = targetBlock.statements(); int i = getLoopStatementIndex(loopNode, statements); //Add the node before the loop. compUnit.recordModifications(); ASTNode invokedMethodStatement = getInvokedStatement(invokedMethod); final VariableDeclarationStatement varDeclarationStatement[] = new VariableDeclarationStatement[1]; //Verify if the invoke statement contains a variable attribution if (invokedMethodStatement instanceof ExpressionStatement) { ExpressionStatement expressionStatement = (ExpressionStatement) invokedMethodStatement; Expression expression = expressionStatement.getExpression(); if (expression instanceof Assignment) { Expression leftHandSide = ((Assignment) expression).getLeftHandSide(); if (leftHandSide instanceof SimpleName) //Search for the variable declaration { SimpleName simpleName = (SimpleName) leftHandSide; final String varName = simpleName.getIdentifier(); loopNode.accept(new ASTVisitor() { @Override public boolean visit(VariableDeclarationStatement node) //Visit all variable declarations inside the loop looking for the variable which receives the findViewById result { List<VariableDeclarationFragment> fragments = node.fragments(); for (VariableDeclarationFragment fragment : fragments) { if (fragment.getName().getIdentifier().equals(varName)) { varDeclarationStatement[0] = node; break; } } return super.visit(node); } }); } } } //Variable is declared inside the loop, now let's move the variable declaration if needed if (varDeclarationStatement[0] != null) { ASTNode varDeclarationSubTree = ASTNode.copySubtree(targetBlock.getAST(), varDeclarationStatement[0]); statements.add(i, (Statement) varDeclarationSubTree.getRoot()); //Delete the node inside loop. varDeclarationStatement[0].delete(); i++; } ASTNode copySubtree = ASTNode.copySubtree(targetBlock.getAST(), invokedMethodStatement); statements.add(i, (Statement) copySubtree.getRoot()); //Delete the node inside loop. invokedMethodStatement.delete(); // apply changes to file final Map<?, ?> mapOptions = JavaCore.create(resource.getProject()).getOptions(true); final IDocument document = ((AbstractTextEditor) editor).getDocumentProvider() .getDocument(editor.getEditorInput()); PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { try { TextEdit edit = compUnit.rewrite(document, mapOptions); iCompilationUnit.applyTextEdit(edit, new NullProgressMonitor()); } catch (JavaModelException e) { EclipseUtils.showErrorDialog(MessagesNLS.FindViewByIdMarkerResolution_Error_Msg_Title, MessagesNLS.FindViewByIdMarkerResolution_Error_Aplying_Changes + e.getMessage()); } } }); marker.delete(); } catch (Exception e) { EclipseUtils.showErrorDialog(MessagesNLS.FindViewByIdMarkerResolution_Error_Msg_Title, MessagesNLS.FindViewByIdMarkerResolution_Error_Could_Not_Fix_Code); } }
From source file:net.sf.jasperreports.eclipse.builder.jdt.JDTUtils.java
License:Open Source License
/** * Formats the specified compilation unit. * //from w ww. j a v a2 s .c om * @param unit the compilation unit to format * @param monitor the monitor for the operation * @throws JavaModelException */ public static void formatUnitSourceCode(ICompilationUnit unit, IProgressMonitor monitor) throws JavaModelException { CodeFormatter formatter = ToolFactory.createCodeFormatter(null); ISourceRange range = unit.getSourceRange(); TextEdit formatEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, unit.getSource(), range.getOffset(), range.getLength(), 0, null); if (formatEdit != null && formatEdit.hasChildren()) { unit.applyTextEdit(formatEdit, monitor); } else { monitor.done(); } }
From source file:org.eclipse.andmore.android.generatecode.JavaCodeModifier.java
License:Apache License
/** * Insert code into the class (activity / fragment) and adds imports if * necessary.//from w ww . java 2s. c o m * * @throws JavaModelException * Thrown if there were problems parsing the java file. */ public void insertCode(IProgressMonitor monitor, IEditorPart editor) throws JavaModelException { final SubMonitor theMonitor = SubMonitor.convert(monitor); IResource resource = codeGeneratorData.getResource(); if (resource instanceof IFile) { IFile java = (IFile) resource; AndmoreLogger.info("Trying to insert code for class: " + java.getFullPath() + " based on resource " //$NON-NLS-1$ + getDataResource()); IDocument document = null; try { document = ((AbstractTextEditor) editor).getDocumentProvider().getDocument(editor.getEditorInput()); final ICompilationUnit compUnit = getCodeGeneratorData().getICompilationUnit(); CompilationUnit cpU = getCodeGeneratorData().getCompilationUnit(); try { cpU.recordModifications(); initVariables(); codeGenerators.clear(); codeGenerators = populateListOfCodeGenerators(getCodeGeneratorData()); theMonitor.beginTask(CodeUtilsNLS.JavaViewBasedOnLayoutModifier_InsertingCode, 1000 * getNumberOfTasks()); callCodeGenerators(theMonitor, java); addImportsIfRequired(theMonitor, cpU); Map<?, ?> mapOptions = JavaCore.create(java.getProject()).getOptions(true); final TextEdit edit = cpU.rewrite(document, mapOptions); PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { try { compUnit.applyTextEdit(edit, theMonitor); } catch (JavaModelException e) { AndmoreLogger.error(this.getClass(), "Error applying changes: " + e.getMessage(), //$NON-NLS-1$ e); } } }); } catch (CoreException e) { AndmoreLogger.error(this.getClass(), "Error changing AST activity/fragment: " + e.getMessage()); //$NON-NLS-1$ throw new JavaModelException(e); } catch (RuntimeException rte) { AndmoreLogger.error(this.getClass(), "Error changing AST activity/fragment: " + rte.getMessage()); //$NON-NLS-1$ throw new JavaModelException(rte, IJavaModelStatusConstants.CORE_EXCEPTION); } } catch (CoreException e) { AndmoreLogger.error(this.getClass(), "Error creating IDocument from java file: " + java + " message: " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ throw new JavaModelException(e, IJavaModelStatusConstants.CORE_EXCEPTION); } finally { theMonitor.done(); } } }