List of usage examples for org.eclipse.jdt.core IBuffer replace
public void replace(int position, int length, String text);
From source file:org.eclipse.wb.internal.rcp.wizards.jface.wizard.WizardWizardPage.java
License:Open Source License
private void addPageInvocations(IType newType, ImportsManager imports) throws JavaModelException { IBuffer buffer = newType.getCompilationUnit().getBuffer(); // prepare addPage() invocations String addPagesSource = ""; for (IType page : getSelectedPages()) { String simpleName = imports.addImport(page.getFullyQualifiedName()); addPagesSource += "addPage(new " + simpleName + "());"; }/*w w w . j a v a 2 s. c o m*/ // prepare position for addPage() invocations int pagesOffset; { IMethod pagesMethod = newType.getMethod("addPages", new String[0]); pagesOffset = pagesMethod.getSourceRange().getOffset(); pagesOffset = buffer.getContents().indexOf('{', pagesOffset) + 1; } // insert addPage() invocations, don't care about formatting buffer.replace(pagesOffset, 0, addPagesSource); }
From source file:org.eclipse.wb.internal.rcp.wizards.rcp.editor.MultiPageEditorPartWizardPage.java
License:Open Source License
private void addPageInvocations(IType newType, ImportsManager imports) throws JavaModelException { IBuffer buffer = newType.getCompilationUnit().getBuffer(); // prepare addPage() invocations String addPagesSource = ""; for (IType page : getSelectedPages()) { String simpleName = imports.addImport(page.getFullyQualifiedName()); addPagesSource += "addPage(new " + simpleName + "(), (org.eclipse.ui.IEditorInput) null);"; }/* w w w . j a va 2 s. c o m*/ // insert addPage() invocations, don't care about formatting String pattern = "int pages;"; int pagesOffset = buffer.getContents().indexOf(pattern); buffer.replace(pagesOffset, pattern.length(), addPagesSource); // if no pages, remove "try" block if (addPagesSource.length() == 0) { String contents = buffer.getContents(); int tryBegin = contents.indexOf("try {"); int tryEnd = contents.indexOf("}", tryBegin + 1); tryEnd = contents.indexOf("}", tryEnd + 1); buffer.replace(tryBegin, tryEnd - tryBegin + 1, ""); } }
From source file:org.eclipse.wb.tests.designer.editor.SplitModeTest.java
License:Open Source License
public void test_reparse_afterDelay() throws Exception { IPreferenceStore preferences = DesignerPlugin.getPreferences(); preferences.setValue(IPreferenceConstants.P_EDITOR_LAYOUT, IPreferenceConstants.V_EDITOR_LAYOUT_SPLIT_VERTICAL_DESIGN); preferences.setValue(IPreferenceConstants.P_EDITOR_LAYOUT_SYNC_DELAY, 100); openContainer("// filler filler filler", "public class Test extends JPanel {", " public Test() {", " } // marker", "}"); openSourcePage();// ww w.ja v a2 s .c om // initially no setEnabled(false) invocation check_isEnabled(true); // set focus to Source, as if user does this { MultiMode multiMode = (MultiMode) m_designerEditor.getMultiMode(); multiMode.getSourcePage().setFocus(); } // insert setEnabled(false) into buffer { IBuffer buffer = m_lastEditor.getModelUnit().getBuffer(); int position = buffer.getContents().indexOf("} // marker"); buffer.replace(position, 0, "setEnabled(false);"); } // still not re-parsed check_isEnabled(true); // wait for re-parse waitEventLoop(1000); fetchContentFields(); check_isEnabled(false); }
From source file:org.eclipse.wb.tests.designer.editor.SplitModeTest.java
License:Open Source License
public void test_reparse_afterSave() throws Exception { IPreferenceStore preferences = DesignerPlugin.getPreferences(); preferences.setValue(IPreferenceConstants.P_EDITOR_LAYOUT, IPreferenceConstants.V_EDITOR_LAYOUT_SPLIT_VERTICAL_DESIGN); preferences.setValue(IPreferenceConstants.P_EDITOR_LAYOUT_SYNC_DELAY, -1); openContainer("// filler filler filler", "public class Test extends JPanel {", " public Test() {", " } // marker", "}"); openSourcePage();// ww w. j a va 2s. co m // initially no setEnabled(false) invocation check_isEnabled(true); // insert setEnabled(false) into buffer { IBuffer buffer = m_lastEditor.getModelUnit().getBuffer(); int position = buffer.getContents().indexOf("} // marker"); buffer.replace(position, 0, "setEnabled(false);"); } // still not re-parsed check_isEnabled(true); // wait, but still not re-parsed waitEventLoop(300); check_isEnabled(true); // do save m_designerEditor.doSave(null); check_isEnabled(false); }
From source file:org.eclipseguru.gwt.core.internal.codegen.JdtTypeGenerator.java
License:Open Source License
/** * Creates the type into the specified compilation unit. * <p>//w w w . j a v a2 s. c o m * Note, the content in the compilation unit will be completely replaced. * </p> * * @param parentCU * the parent compilation unit (must be a working copy) * @param needsSave * indicates if the compilation unit should be saved * @param monitor * a progress monitor to report progress (must not be * <code>null</code> and needs 10 progress steps) * @throws CoreException * Thrown when the creation failed. */ @SuppressWarnings("unchecked") public void createType(final ICompilationUnit parentCU, IProgressMonitor monitor) throws CoreException { if (!parentCU.isWorkingCopy()) { throw new CoreException(GwtCore .newErrorStatus("compilation unit '" + parentCU.getElementName() + "' must be a working copy")); } monitor = ProgressUtil.monitor(monitor); try { final String lineDelimiter = GwtUtil.getLineSeparator(parentCU.getJavaProject().getProject()); monitor.beginTask(NLS.bind("''{0}''...", getTypeName()), 10); currentType = parentCU.getType(getTypeNameWithoutParameters()); final IBuffer buffer = parentCU.getBuffer(); final String cuContent = constructCUContent(parentCU, constructSimpleTypeStub(), lineDelimiter); buffer.setContents(cuContent); CompilationUnit astRoot = ImportsManager.createASTForImports(parentCU); final Set<String> existingImports = ImportsManager.getExistingImports(astRoot); ProgressUtil.checkCanceled(monitor); ImportsManager imports = new ImportsManager(astRoot); // add an import that will be removed again. Having this import solves 14661 (Eclipse Bugzilla) imports.addImport(JavaModelUtil.concatenateName(parentCU.getParent().getElementName(), getTypeNameWithoutParameters())); final String typeContent = constructTypeStub(parentCU, imports, lineDelimiter); // check that we have the types final List types = astRoot.types(); if (types.isEmpty()) { throw new CoreException(GwtCore.newErrorStatus("compilation unit '" + parentCU.getElementName() + "' AST has no types; content follows: " + cuContent)); } final AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) types.get(0); final int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition(); final int end = typeNode.getStartPosition() + typeNode.getLength(); buffer.replace(start, end - start, typeContent); final IType createdType = parentCU.getType(getTypeName()); ProgressUtil.checkCanceled(monitor); // add imports for superclass/interfaces, so types can be resolved // correctly imports.create(new SubProgressMonitor(monitor, 1)); JavaModelUtil.reconcile(parentCU); ProgressUtil.checkCanceled(monitor); // set up again astRoot = ImportsManager.createASTForImports(parentCU); imports = new ImportsManager(astRoot); createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1)); // add imports imports.create(ProgressUtil.subProgressMonitor(monitor, 1)); ImportsManager.removeUnusedImports(parentCU, existingImports); JavaModelUtil.reconcile(parentCU); // format the compilation unit final TextEdit edit = CodeFormatterUtil.format2(CodeFormatter.K_COMPILATION_UNIT, parentCU.getBuffer().getContents(), 0, lineDelimiter, new HashMap(parentCU.getJavaProject().getOptions(true))); if (edit != null) { JavaModelUtil.applyEdit(parentCU, edit, false, ProgressUtil.subProgressMonitor(monitor, 1)); } monitor.worked(1); } finally { monitor.done(); } }
From source file:org.gw4e.eclipse.fwk.source.SourceHelper.java
License:Open Source License
public static void updatePathGenerator(IFile ifile, String oldPathGenerator, String newPathGenerator) throws CoreException { ICompilationUnit cu = JavaCore.createCompilationUnitFrom(ifile); ICompilationUnit workingCopy = cu.getWorkingCopy(new NullProgressMonitor()); IBuffer buffer = ((IOpenable) workingCopy).getBuffer(); String source = buffer.getContents(); int start = source.indexOf(oldPathGenerator); buffer.replace(start, oldPathGenerator.length(), newPathGenerator); workingCopy.reconcile(ICompilationUnit.NO_AST, false, workingCopy.getOwner(), new NullProgressMonitor()); workingCopy.commitWorkingCopy(true, null); workingCopy.discardWorkingCopy();/*from w w w. j a va 2 s . c om*/ ifile.touch(new NullProgressMonitor()); }
From source file:org.j2eespider.util.AnnotationUtil.java
License:Open Source License
/** * Replace annotations in method./*w w w. j a v a2 s .c om*/ */ public static void replaceAnnotationsInMethod(IMethod imethod, List<ValidatorType> annotations, String textNewAnnotations) { try { //monta o scanner do metodo IBuffer methodBuffer = imethod.getOpenable().getBuffer(); ISourceRange sourceRange = imethod.getSourceRange(); ISourceRange javadocRange = null;//imethod.getJavadocRange(); ISourceRange nameRange = imethod.getNameRange(); IScanner scanner = null; // delay initialization if (sourceRange != null && nameRange != null) { if (scanner == null) { scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(methodBuffer.getCharacters()); } scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); } //apaga todas as annotations que esto em annotationsType e adiciona textNewAnnotations StringBuffer sourceMethod = new StringBuffer(); int tok = scanner.getNextToken(); while (tok != ITerminalSymbols.TokenNameprivate && tok != ITerminalSymbols.TokenNameprotected && tok != ITerminalSymbols.TokenNamepublic) { //loop nas annotations if (tok == ITerminalSymbols.TokenNameAT) { //encontrou o inicio de uma annotation StringBuffer thisAnnotation = new StringBuffer("@"); tok = scanner.getNextToken(); //trabalha todo o contedo da annotation while (tok != ITerminalSymbols.TokenNameAT && tok != ITerminalSymbols.TokenNameprivate && tok != ITerminalSymbols.TokenNameprotected && tok != ITerminalSymbols.TokenNamepublic) { //pega todo o conteudo desta annotation thisAnnotation.append(scanner.getCurrentTokenSource()); //pega o nome dessa annotation tok = scanner.getNextToken(); } //verifica se para apagar essa annotation (s joga no novo sourceMethod se ela no tiver na lista que para apagar) if (!ValidatorUtil.containsValidator(annotations, thisAnnotation.toString())) { sourceMethod.append(thisAnnotation); } } } //grava o resto do metodo int posStartMethod = scanner.getCurrentTokenStartPosition(); int lengthRemoved = posStartMethod - sourceRange.getOffset(); //conta quantos caracteres foram removidos desse metodo (as annotations) String codeRemain = String.valueOf(scanner.getSource()).substring(posStartMethod, posStartMethod + sourceRange.getLength() - lengthRemoved); if (!sourceMethod.toString().equals("") && sourceMethod.toString().lastIndexOf("\n") != sourceMethod.toString().length() - 1) { //se j tem alguma annotation, ve se precisa de quebra de linha sourceMethod.append("\n\t"); } sourceMethod.append(textNewAnnotations); //adiciona as novas annotations antes do resto do mtodo sourceMethod.append(codeRemain); if (javadocRange != null) { //se tiver javadoc, no altera ele... methodBuffer.replace(sourceRange.getOffset() + javadocRange.getLength(), sourceRange.getLength() - javadocRange.getLength(), "\t" + sourceMethod.toString()); //altera o cdigo do mtodo } else { methodBuffer.replace(sourceRange.getOffset(), sourceRange.getLength(), sourceMethod.toString()); //altera o cdigo do mtodo } imethod.getOpenable().save(null, true); } catch (JavaModelException e) { } catch (InvalidInputException e) { } }
From source file:org.jboss.reddeer.eclipse.ui.wizards.NewRedDeerTestWizardPageOne.java
License:Open Source License
private void addAnnotation(IType type) throws JavaModelException { ISourceRange range = type.getSourceRange(); IBuffer buf = type.getCompilationUnit().getBuffer(); char[] source = buf.getCharacters(); IScanner scanner = ToolFactory.createScanner(false, false, false, JavaCore.VERSION_1_5); scanner.setSource(source);/*from w ww . j av a 2 s . c om*/ int offset = range.getOffset(); try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (token == ITerminalSymbols.TokenNamepublic) { offset = scanner.getCurrentTokenStartPosition(); break; } token = scanner.getNextToken(); } } catch (InvalidInputException e) { Activator.log(e); } StringBuffer sb = new StringBuffer(); sb.append("@RunWith(RedDeerSuite.class)").append(getPackageFragment().findRecommendedLineSeparator()); buf.replace(offset, 0, sb.toString()); }
From source file:org.jboss.tools.arquillian.ui.internal.utils.ArquillianUIUtil.java
License:Open Source License
/** * Creates a deployment method/*from ww w . jav a 2 s . co m*/ * * @param icu * @param type * @param imports * @param isAddComments * @param delimiter * @param deploymentDescriptor * @param sibling * @param force * @throws CoreException */ public static void createDeploymentMethod(ICompilationUnit icu, IType type, ImportsManager imports, boolean isAddComments, String delimiter, IDeploymentDescriptor deploymentDescriptor, IJavaElement sibling, boolean force) throws CoreException { String content = null; ImportRewrite importsRewrite = null; if (icu != null) { importsRewrite = StubUtility.createImportRewrite(icu, true); } String annotation = '@' + addImport(imports, importsRewrite, ArquillianUtility.ORG_JBOSS_ARQUILLIAN_CONTAINER_TEST_API_DEPLOYMENT); String methodName = CREATE_DEPLOYMENT; addImport(imports, importsRewrite, ORG_JBOSS_SHRINKWRAP_API_SHRINK_WRAP); addImport(imports, importsRewrite, ORG_JBOSS_SHRINKWRAP_API_ARCHIVE); GenStubSettings settings = JUnitStubUtility.getCodeGenerationSettings(type.getJavaProject()); settings.createComments = isAddComments; StringBuffer buffer = new StringBuffer(); if (settings.createComments) { String retTypeSig = Signature.createTypeSignature(ORG_JBOSS_SHRINKWRAP_API_ARCHIVE, true); String comment = CodeGeneration.getMethodComment(type.getCompilationUnit(), type.getElementName(), methodName, new String[0], new String[0], retTypeSig, null, delimiter); if (comment != null) { buffer.append(comment); } } String archiveType = ArquillianConstants.JAR; String archiveName = ""; //$NON-NLS-1$ String deploymentName = null; String deploymentOrder = null; boolean addBeansXml = true; IType[] types = null; List<String> resources = new ArrayList<String>(); List<String> webInfResources = new ArrayList<String>(); if (deploymentDescriptor != null) { methodName = deploymentDescriptor.getMethodName(); archiveType = deploymentDescriptor.getArchiveType(); archiveName = deploymentDescriptor.getArchiveName(); addBeansXml = deploymentDescriptor.addBeansXml(); deploymentName = deploymentDescriptor.getDeploymentName(); deploymentOrder = deploymentDescriptor.getDeploymentOrder(); types = deploymentDescriptor.getTypes(); ProjectResource[] allResources = deploymentDescriptor.getResources(); for (ProjectResource resource : allResources) { if (ArquillianConstants.WAR.equals(archiveType) && resource.isDeployAsWebInfResource()) { webInfResources.add(resource.getPath().toString()); } else { resources.add(resource.getPath().toString()); } } } buffer.append(annotation); if ((deploymentName != null && !deploymentName.isEmpty()) || (deploymentOrder != null && !deploymentOrder.isEmpty())) { buffer.append("("); //$NON-NLS-1$ if ((deploymentName != null && !deploymentName.isEmpty())) { buffer.append("name = \""); //$NON-NLS-1$ buffer.append(deploymentName); buffer.append("\""); //$NON-NLS-1$ if (deploymentOrder != null && !deploymentOrder.isEmpty()) { buffer.append(" , "); //$NON-NLS-1$ } } if (deploymentOrder != null && !deploymentOrder.isEmpty()) { buffer.append("order = "); //$NON-NLS-1$ buffer.append(deploymentOrder); } buffer.append(")"); //$NON-NLS-1$ } buffer.append(delimiter); buffer.append("public static Archive<?> "); //$NON-NLS-1$ buffer.append(methodName); buffer.append("()"); //$NON-NLS-1$ buffer.append(" {").append(delimiter); //$NON-NLS-1$ if (ArquillianConstants.JAR.equals(archiveType)) { addImport(imports, importsRewrite, ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_JAVA_ARCHIVE); buffer.append("JavaArchive archive = ShrinkWrap.create(JavaArchive.class"); //$NON-NLS-1$ } if (ArquillianConstants.WAR.equals(archiveType)) { addImport(imports, importsRewrite, ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_WEB_ARCHIVE); buffer.append("WebArchive archive = ShrinkWrap.create(WebArchive.class"); //$NON-NLS-1$ } if (ArquillianConstants.EAR.equals(archiveType)) { addImport(imports, importsRewrite, "org.jboss.shrinkwrap.api.spec.EnterpriseArchive"); //$NON-NLS-1$ buffer.append("EnterpriseArchive archive = ShrinkWrap.create(EnterpriseArchive.class"); //$NON-NLS-1$ } if (ArquillianConstants.RAR.equals(archiveType)) { addImport(imports, importsRewrite, "org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive"); //$NON-NLS-1$ buffer.append("ResourceAdapterArchive archive = ShrinkWrap.create(ResourceAdapterArchive.class"); //$NON-NLS-1$ } if (archiveName != null && !archiveName.isEmpty()) { if (archiveName.indexOf(PERIOD) == -1) { archiveName = archiveName + PERIOD + archiveType; } buffer.append(", "); //$NON-NLS-1$ buffer.append("\""); //$NON-NLS-1$ buffer.append(archiveName); buffer.append("\""); //$NON-NLS-1$ } buffer.append(")"); //$NON-NLS-1$ if (types != null && types.length > 0) { buffer.append(delimiter); buffer.append(".addClasses( "); //$NON-NLS-1$ boolean first = true; for (IType t : types) { if (!first) { buffer.append(" , "); //$NON-NLS-1$ } else { first = false; } String typeName = t.getFullyQualifiedName().replaceAll("\\$", "."); int lastPeriod = typeName.lastIndexOf(PERIOD); String className = typeName; if (lastPeriod >= 0 && lastPeriod < typeName.length()) { className = typeName.substring(lastPeriod + 1, typeName.length()); addImport(imports, importsRewrite, typeName); } buffer.append(className); buffer.append(".class"); //$NON-NLS-1$ } buffer.append(" )"); //$NON-NLS-1$ } for (String resource : resources) { buffer.append(delimiter); buffer.append(".addAsResource( "); //$NON-NLS-1$ buffer.append("\""); //$NON-NLS-1$ buffer.append(resource); buffer.append("\""); //$NON-NLS-1$ buffer.append(" )"); //$NON-NLS-1$ } for (String resource : webInfResources) { buffer.append(delimiter); buffer.append(".addAsWebInfResource( "); //$NON-NLS-1$ buffer.append("\""); //$NON-NLS-1$ buffer.append(resource); buffer.append("\""); //$NON-NLS-1$ buffer.append(" )"); //$NON-NLS-1$ } if (addBeansXml && !ArquillianConstants.EAR.equals(archiveType)) { addImport(imports, importsRewrite, "org.jboss.shrinkwrap.api.asset.EmptyAsset"); //$NON-NLS-1$ buffer.append(delimiter); if (ArquillianConstants.WAR.equals(archiveType)) { buffer.append(".addAsWebInfResource(EmptyAsset.INSTANCE, \"beans.xml\")"); //$NON-NLS-1$ } else { buffer.append(".addAsManifestResource(EmptyAsset.INSTANCE, \"beans.xml\")"); //$NON-NLS-1$ } } buffer.append(";").append(delimiter); //$NON-NLS-1$ buffer.append("// System.out.println(archive.toString(true));").append( //$NON-NLS-1$ delimiter); buffer.append("return archive;").append(delimiter); //$NON-NLS-1$ buffer.append("}"); //$NON-NLS-1$ buffer.append(delimiter); content = buffer.toString(); if (icu == null) { type.createMethod(content, sibling, force, null); } else { TextEdit edit = importsRewrite.rewriteImports(null); JavaModelUtil.applyEdit(importsRewrite.getCompilationUnit(), edit, false, null); IMethod createdMethod = type.createMethod(content, sibling, force, null); ISourceRange range = createdMethod.getSourceRange(); IBuffer buf = icu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); int indent = StubUtility.getIndentUsed(type) + 1; String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, delimiter, type.getJavaProject()); //formattedContent = Strings // .trimLeadingTabsAndSpaces(formattedContent); while (formattedContent.length() > 0) { char ch = formattedContent.charAt(0); if (ScannerHelper.isWhitespace(ch)) { formattedContent = formattedContent.substring(1); } else { break; } } buf.replace(range.getOffset(), range.getLength(), formattedContent); icu.reconcile(ICompilationUnit.NO_AST, false, null, null); icu.commitWorkingCopy(false, null); } }
From source file:org.jboss.tools.arquillian.ui.internal.wizards.NewArquillianJUnitTestCasePageOne.java
License:Open Source License
@Override protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException { if (fMethodStubsButtons.isSelected(IDX_DEPLOYMENT)) { String delimiter = getLineDelimiter(); NewArquillianJUnitTestCaseDeploymentPage deploymentPage = (NewArquillianJUnitTestCaseDeploymentPage) getWizard() .getPage(//from ww w. ja v a 2 s .com NewArquillianJUnitTestCaseDeploymentPage.ORG_JBOSS_TOOLS_ARQUILLIAN_UI_DEPLOYMENT_PAGE); ArquillianUIUtil.createDeploymentMethod(null, type, imports, isAddComments(), delimiter, deploymentPage, null, false); } if (fMethodStubsButtons.isSelected(IDX_SETUP_CLASS)) { createSetUpClass(type, imports); } if (fMethodStubsButtons.isSelected(IDX_TEARDOWN_CLASS)) { createTearDownClass(type, imports); } if (fMethodStubsButtons.isSelected(IDX_SETUP)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(IDX_TEARDOWN)) { createTearDown(type, imports); } createTestMethodStubs(type, imports); imports.addStaticImport("org.junit.Assert", "*", false); //$NON-NLS-1$ //$NON-NLS-2$ imports.addImport(ORG_JUNIT_RUNNER_RUNWITH); imports.addImport("org.jboss.arquillian.junit.Arquillian"); ISourceRange range = type.getSourceRange(); IBuffer buf = type.getCompilationUnit().getBuffer(); char[] source = buf.getCharacters(); IScanner scanner = ToolFactory.createScanner(false, false, false, JavaCore.VERSION_1_5); scanner.setSource(source); int offset = range.getOffset(); try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (token == ITerminalSymbols.TokenNamepublic) { offset = scanner.getCurrentTokenStartPosition(); break; } token = scanner.getNextToken(); } } catch (InvalidInputException e) { ArquillianUIActivator.log(e); } StringBuffer sb = new StringBuffer(); sb.append("@RunWith(Arquillian.class)").append(getPackageFragment().findRecommendedLineSeparator()); buf.replace(offset, 0, sb.toString()); }