List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getPackageFragment
IPackageFragment getPackageFragment(String packageName);
From source file:org.eclipse.ajdt.internal.ui.wizards.NewTypeWizardPage.java
License:Open Source License
/** * Creates the new type using the entered field values. * /*from ww w.ja v a 2s . com*/ * @param monitor a progress monitor to report progress. * @throws CoreException Thrown when the creation failed. * @throws InterruptedException Thrown when the operation was canceled. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor = new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8); IPackageFragmentRoot root = getPackageFragmentRoot(); IPackageFragment pack = getPackageFragment(); if (pack == null) { pack = root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName = pack.getElementName(); pack = root.createPackageFragment(packName, true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } boolean needsSave; ICompilationUnit connectedCU = null; try { String typeName = getTypeNameWithoutParameters(); boolean isInnerClass = isEnclosingTypeSelected(); IType createdType; ImportsManager imports; int indent = 0; Set /* String (import names) */ existingImports; String lineDelimiter = null; if (!isInnerClass) { lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject()); String cuName = getCompilationUnitName(typeName); ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, //$NON-NLS-1$ new SubProgressMonitor(monitor, 2)); // create a working copy with a new owner needsSave = true; parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now a (primary) working copy connectedCU = parentCU; IBuffer buffer = parentCU.getBuffer(); String simpleTypeStub = constructSimpleTypeStub(); String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter); buffer.setContents(cuContent); CompilationUnit astRoot = createASTForImports(parentCU); existingImports = getExistingImports(astRoot); imports = new ImportsManager(astRoot); // add an import that will be removed again. Having this import solves 14661 imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName)); String typeContent = constructTypeStub(parentCU, imports, lineDelimiter); int index = cuContent.lastIndexOf(simpleTypeStub); if (index == -1) { AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0); int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition(); int end = typeNode.getStartPosition() + typeNode.getLength(); buffer.replace(start, end - start, typeContent); } else { buffer.replace(index, simpleTypeStub.length(), typeContent); } createdType = parentCU.getType(typeName); } else { IType enclosingType = getEnclosingType(); ICompilationUnit parentCU = enclosingType.getCompilationUnit(); needsSave = !parentCU.isWorkingCopy(); parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now for sure (primary) a working copy connectedCU = parentCU; CompilationUnit astRoot = createASTForImports(parentCU); imports = new ImportsManager(astRoot); existingImports = getExistingImports(astRoot); // add imports that will be removed again. Having the imports solves 14661 IType[] topLevelTypes = parentCU.getTypes(); for (int i = 0; i < topLevelTypes.length; i++) { imports.addImport(topLevelTypes[i].getFullyQualifiedName('.')); } lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType); StringBuffer content = new StringBuffer(); String comment = getTypeComment(parentCU, lineDelimiter); if (comment != null) { content.append(comment); content.append(lineDelimiter); } content.append(constructTypeStub(parentCU, imports, lineDelimiter)); IJavaElement sibling = null; if (enclosingType.isEnum()) { IField[] fields = enclosingType.getFields(); if (fields.length > 0) { for (int i = 0, max = fields.length; i < max; i++) { if (!fields[i].isEnumConstant()) { sibling = fields[i]; break; } } } } else { IJavaElement[] elems = enclosingType.getChildren(); sibling = elems.length > 0 ? elems[0] : null; } createdType = enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 2)); indent = StubUtility.getIndentUsed(enclosingType) + 1; } if (monitor.isCanceled()) { throw new InterruptedException(); } // add imports for superclass/interfaces, so types can be resolved correctly ICompilationUnit cu = createdType.getCompilationUnit(); imports.create(false, new SubProgressMonitor(monitor, 1)); JavaModelUtil.reconcile(cu); if (monitor.isCanceled()) { throw new InterruptedException(); } // set up again CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit()); imports = new ImportsManager(astRoot); createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1)); // add imports imports.create(false, new SubProgressMonitor(monitor, 1)); removeUnusedImports(cu, existingImports, false); JavaModelUtil.reconcile(cu); ISourceRange range = createdType.getSourceRange(); IBuffer buf = cu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, lineDelimiter, pack.getJavaProject()); formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { String fileComment = getFileComment(cu); if (fileComment != null && fileComment.length() > 0) { buf.replace(0, 0, fileComment + lineDelimiter); } } fCreatedType = createdType; if (needsSave) { cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } } finally { if (connectedCU != null) { connectedCU.discardWorkingCopy(); } monitor.done(); } }
From source file:org.eclipse.ajdt.ui.tests.refactoring.RenamePackageTest.java
License:Open Source License
public void testRenamePackage() throws Exception { IProject proj = createPredefinedProject("Bug 254431"); //$NON-NLS-1$ IJavaProject jProj = JavaCore.create(proj); IPackageFragmentRoot packRoot = jProj.getPackageFragmentRoot(proj.getFolder("src")); //$NON-NLS-1$ IPackageFragment frag = packRoot.getPackageFragment("ajdt.renamepackagebug1"); //$NON-NLS-1$ assertTrue("Package fragment " + frag.getElementName() + " should exist", frag.exists()); //$NON-NLS-1$ //$NON-NLS-2$ RenamePackageProcessor processor = new RenamePackageProcessor(frag); processor.setNewElementName("ajdt.renamed"); //$NON-NLS-1$ IProgressMonitor pm = new NullProgressMonitor(); CheckConditionsContext context = new CheckConditionsContext(); context.add(new ValidateEditChecker(context)); context.add(new ResourceChangeChecker()); processor.checkInitialConditions(pm); processor.checkFinalConditions(pm, context); Change change = processor.createChange(pm); change.perform(pm);//ww w . j a v a 2 s. c o m waitForJobsToComplete(); IPackageFragment newFrag = packRoot.getPackageFragment("ajdt.renamed"); //$NON-NLS-1$ assertTrue("Package fragment " + newFrag.getElementName() + " should exist after a rename", //$NON-NLS-1$//$NON-NLS-2$ newFrag.exists()); IFile ajFile = proj.getFile("src/ajdt/renamed/A.aj"); //$NON-NLS-1$ assertTrue("A.aj should exist after its package has been renamed", ajFile.exists()); //$NON-NLS-1$ IMarker[] markers = ajFile.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE); if (markers.length > 0) { StringBuffer sb = new StringBuffer(); sb.append("No markers should have been found, but the following markers were found on A.aj:\n"); //$NON-NLS-1$ for (int i = 0; i < markers.length; i++) { sb.append("\t" + markers[i].getAttribute(IMarker.MESSAGE) + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } assertEquals(sb.toString(), 0, markers.length); } IFile javaFile = proj.getFile("src/ajdt/renamepackagebug2/B.aj"); //$NON-NLS-1$ assertTrue("B.aj should exist", javaFile.exists()); //$NON-NLS-1$ markers = javaFile.findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE); if (markers.length > 0) { StringBuffer sb = new StringBuffer(); sb.append("No markers should have been found, but the following markers were found on B.aj:\n"); //$NON-NLS-1$ for (int i = 0; i < markers.length; i++) { sb.append("\t" + markers[i].getAttribute(IMarker.MESSAGE) + "\n"); //$NON-NLS-1$//$NON-NLS-2$ } assertEquals(sb.toString(), 0, markers.length); } }
From source file:org.eclipse.andmore.internal.editors.manifest.ManifestInfo.java
License:Open Source License
/** * Returns the {@link IPackageFragment} for the package registered in the manifest * * @return the {@link IPackageFragment} for the package registered in the manifest *///from w w w. j ava2s . co m @Nullable public IPackageFragment getPackageFragment() { sync(); try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject); if (javaProject != null) { IPackageFragmentRoot root = ManifestInfo.getSourcePackageRoot(javaProject); if (root != null) { return root.getPackageFragment(mPackage); } } } catch (CoreException e) { AndmoreAndroidPlugin.log(e, null); } return null; }
From source file:org.eclipse.andmore.internal.editors.manifest.model.UiPackageAttributeNode.java
License:Open Source License
/** * Handles response to the Label hyper link being activated. *//*from w w w. j av a 2s.c o m*/ private void doLabelClick() { // get the current package name String package_name = getTextWidget().getText().trim(); if (package_name.length() == 0) { createNewPackage(); } else { // Try to select the package in the Package Explorer for the current // project and the current editor's site. IProject project = getProject(); if (project == null) { AndmoreAndroidPlugin.log(IStatus.ERROR, "Failed to get project for UiPackageAttribute"); //$NON-NLS-1$ return; } IWorkbenchPartSite site = getUiParent().getEditor().getSite(); if (site == null) { AndmoreAndroidPlugin.log(IStatus.ERROR, "Failed to get editor site for UiPackageAttribute"); //$NON-NLS-1$ return; } for (IPackageFragmentRoot root : getPackageFragmentRoots(project)) { IPackageFragment fragment = root.getPackageFragment(package_name); if (fragment != null && fragment.exists()) { ShowInPackageViewAction action = new ShowInPackageViewAction(site); action.run(fragment); // This action's run() doesn't provide the status (although internally it could) // so we just assume it worked. return; } } } }
From source file:org.eclipse.andmore.wizards.buildingblocks.NewBuildingBlocksWizardPage.java
License:Apache License
/** * Checks for cross package/class collision among source folders * // ww w . ja v a 2 s. co m * @return true if there is any collision or false otherwise */ private boolean packageAndClassExist() { boolean exists = false; try { if ((getJavaProject() != null) && getJavaProject().isOpen()) { IPackageFragmentRoot[] roots = getJavaProject().getPackageFragmentRoots(); if (roots != null) { for (IPackageFragmentRoot root : roots) { if ((root.getKind() & IPackageFragmentRoot.K_SOURCE) == IPackageFragmentRoot.K_SOURCE) { IPackageFragment pack = root.getPackageFragment(getPackageText()); if ((pack != null) && pack.exists()) { IJavaElement classes[] = pack.getChildren(); if (classes != null) { for (IJavaElement clazz : classes) { if (clazz.getElementName().equals(getTypeName() + JAVA_EXTENSION)) { exists = true; break; } } } } } if (exists) { break; } } } } } catch (JavaModelException e) { // Do nothing AndmoreLogger.error(NewBuildingBlocksWizardPage.class, e.getLocalizedMessage(), e); } return exists; }
From source file:org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundle.java
License:Open Source License
protected void runAction() { // First see if this is a "new wizard". IWizardDescriptor descriptor = PlatformUI.getWorkbench().getNewWizardRegistry().findWizard(newBunldeWizard); // If not check if it is an "import wizard". if (descriptor == null) { descriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(newBunldeWizard); }/*from ww w .j av a2 s.c o m*/ // Or maybe an export wizard if (descriptor == null) { descriptor = PlatformUI.getWorkbench().getExportWizardRegistry().findWizard(newBunldeWizard); } try { // Then if we have a wizard, open it. if (descriptor != null) { IWizard wizard = descriptor.createWizard(); if (!(wizard instanceof IResourceBundleWizard)) { return; } IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; String[] keySilbings = key.split("\\."); String rbName = keySilbings[keySilbings.length - 1]; String packageName = ""; rbw.setBundleId(rbName); // Set the default path according to the specified package name String pathName = ""; if (keySilbings.length > 1) { try { IJavaProject jp = JavaCore.create(resource.getProject()); packageName = key.substring(0, key.lastIndexOf(".")); for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) { IPackageFragment pf = fr.getPackageFragment(packageName); if (pf.exists()) { pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString(); break; } } } catch (Exception e) { pathName = ""; } } try { IJavaProject jp = JavaCore.create(resource.getProject()); if (pathName.trim().equals("")) { for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) { if (!fr.isReadOnly()) { pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString(); break; } } } } catch (Exception e) { pathName = ""; } rbw.setDefaultPath(pathName); WizardDialog wd = new WizardDialog(Display.getDefault().getActiveShell(), wizard); wd.setTitle(wizard.getWindowTitle()); if (wd.open() == WizardDialog.OK) { try { resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD, I18nBuilder.BUILDER_ID, null, null); } catch (CoreException e) { Logger.logError(e); } ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); IPath path = resource.getRawLocation(); try { bufferManager.connect(path, null); ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path); IDocument document = textFileBuffer.getDocument(); if (document.get().charAt(start - 1) == '"' && document.get().charAt(start) != '"') { start--; end++; } if (document.get().charAt(end + 1) == '"' && document.get().charAt(end) != '"') { end++; } document.replace(start, end - start, "\"" + (packageName.equals("") ? "" : packageName + ".") + rbName + "\""); textFileBuffer.commit(null, false); } catch (Exception e) { Logger.logError(e); } finally { try { bufferManager.disconnect(path, null); } catch (CoreException e) { Logger.logError(e); } } } } } catch (CoreException e) { Logger.logError(e); } }
From source file:org.eclipse.babel.tapiji.tools.java.ui.autocompletion.CreateResourceBundleProposal.java
License:Open Source License
@SuppressWarnings("deprecation") protected void runAction() { // First see if this is a "new wizard". IWizardDescriptor descriptor = PlatformUI.getWorkbench().getNewWizardRegistry().findWizard(newBunldeWizard); // If not check if it is an "import wizard". if (descriptor == null) { descriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(newBunldeWizard); }/*from w w w . ja v a2 s . c o m*/ // Or maybe an export wizard if (descriptor == null) { descriptor = PlatformUI.getWorkbench().getExportWizardRegistry().findWizard(newBunldeWizard); } try { // Then if we have a wizard, open it. if (descriptor != null) { IWizard wizard = descriptor.createWizard(); if (!(wizard instanceof IResourceBundleWizard)) { return; } IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; String[] keySilbings = key.split("\\."); String rbName = keySilbings[keySilbings.length - 1]; String packageName = ""; rbw.setBundleId(rbName); // Set the default path according to the specified package name String pathName = ""; if (keySilbings.length > 1) { try { IJavaProject jp = JavaCore.create(resource.getProject()); packageName = key.substring(0, key.lastIndexOf(".")); for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) { IPackageFragment pf = fr.getPackageFragment(packageName); if (pf.exists()) { pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString(); break; } } } catch (Exception e) { pathName = ""; } } try { IJavaProject jp = JavaCore.create(resource.getProject()); if (pathName.trim().equals("")) { for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) { if (!fr.isReadOnly()) { pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString(); break; } } } } catch (Exception e) { pathName = ""; } rbw.setDefaultPath(pathName); WizardDialog wd = new WizardDialog(Display.getDefault().getActiveShell(), wizard); wd.setTitle(wizard.getWindowTitle()); if (wd.open() == WizardDialog.OK) { try { resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD, I18nBuilder.BUILDER_ID, null, null); } catch (CoreException e) { Logger.logError(e); } ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); IPath path = resource.getRawLocation(); try { bufferManager.connect(path, LocationKind.NORMALIZE, null); ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE); IDocument document = textFileBuffer.getDocument(); if (document.get().charAt(start - 1) == '"' && document.get().charAt(start) != '"') { start--; end++; } if (document.get().charAt(end + 1) == '"' && document.get().charAt(end) != '"') { end++; } document.replace(start, end - start, "\"" + (packageName.equals("") ? "" : packageName + ".") + rbName + "\""); textFileBuffer.commit(null, false); } catch (Exception e) { } finally { try { bufferManager.disconnect(path, null); } catch (CoreException e) { } } } } } catch (CoreException e) { } }
From source file:org.eclipse.che.jdt.core.ImportOrganizeTest.java
License:Open Source License
@Test public void testClearImportsNoPackage() throws Exception { IPackageFragmentRoot sourceFolder = JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1 = sourceFolder.getPackageFragment(""); StringBuffer buf = new StringBuffer(); buf.append("import java.util.Vector;\n"); buf.append("public class C {\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order = new String[0]; IChooseImportQuery query = createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op = createOperation(cu, order, 99, false, true, true, query); op.run(null);//from ww w . ja v a 2s .c om buf = new StringBuffer(); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); }
From source file:org.eclipse.che.jdt.core.ImportOrganizeTest.java
License:Open Source License
@Test public void testNewImportsNoPackage() throws Exception { IPackageFragmentRoot sourceFolder = JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1 = sourceFolder.getPackageFragment(""); StringBuffer buf = new StringBuffer(); buf.append("public class C extends Vector {\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order = new String[0]; IChooseImportQuery query = createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op = createOperation(cu, order, 99, false, true, true, query); op.run(null);//from w w w . j av a 2 s . c o m buf = new StringBuffer(); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); }
From source file:org.eclipse.che.jdt.core.ImportOrganizeTest.java
License:Open Source License
@Test public void testReplaceImportsNoPackage() throws Exception { IPackageFragmentRoot sourceFolder = JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1 = sourceFolder.getPackageFragment(""); StringBuffer buf = new StringBuffer(); buf.append("import java.util.Set;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order = new String[0]; IChooseImportQuery query = createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op = createOperation(cu, order, 99, false, true, true, query); op.run(null);/*from w ww . ja v a2 s . c o m*/ buf = new StringBuffer(); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); }