Java Code Examples for org.eclipse.jdt.core.IPackageFragment#getCompilationUnit()

The following examples show how to use org.eclipse.jdt.core.IPackageFragment#getCompilationUnit() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean packageDocumentationAlreadyExists(IPackageFragment pack) throws JavaModelException {
	ICompilationUnit packageInfoJava= pack.getCompilationUnit(PACKAGE_INFO_JAVA_FILENAME);
	if (packageInfoJava.exists()) {
		return true;
	}
	Object[] nonJavaResources= pack.getNonJavaResources();
	for (int i= 0; i < nonJavaResources.length; i++) {
		Object resource= nonJavaResources[i];
		if (resource instanceof IFile) {
			IFile file= (IFile) resource;
			String fileName= file.getName();
			if (PACKAGE_HTML_FILENAME.equals(fileName)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 2
Source File: CompilationUnitRenamedReferenceUpdater.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ICompilationUnit getUpdatedCompilationUnit(
    ICompilationUnit compilationUnit) {
  if (!compilationUnit.getElementName().equals(oldCuName)) {
    return compilationUnit;
  }

  // Sanity check
  if (!(compilationUnit.getParent() instanceof IPackageFragment)) {
    GWTPluginLog.logWarning(String.format(
        "The parent of %s is not a package fragment (it is %s of type %s).",
        compilationUnit.getElementName(),
        compilationUnit.getParent().getElementName(),
        compilationUnit.getParent().getClass().getSimpleName()));
    return compilationUnit;
  }

  IPackageFragment pkgFragment = (IPackageFragment) compilationUnit.getParent();
  ICompilationUnit newCu = pkgFragment.getCompilationUnit(newCuName);
  return newCu;
}
 
Example 3
Source File: JavadocContentAccess.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets a reader for an package fragment's Javadoc comment content from the source attachment.
 * The content does contain only the text from the comment without the Javadoc leading star characters.
 * Returns <code>null</code> if the package fragment does not contain a Javadoc comment or if no source is available.
 * @param fragment The package fragment to get the Javadoc of.
 * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
 * does not contain a Javadoc comment or if no source is available
 * @throws JavaModelException is thrown when the package fragment's javadoc can not be accessed
 * @since 3.4
 */
private static Reader internalGetContentReader(IPackageFragment fragment) throws JavaModelException {
	IPackageFragmentRoot root= (IPackageFragmentRoot) fragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

	//1==> Handle the case when the documentation is present in package-info.java or package-info.class file
	boolean isBinary= root.getKind() == IPackageFragmentRoot.K_BINARY;
	ITypeRoot packageInfo;
	if (isBinary) {
		packageInfo= fragment.getClassFile(PACKAGE_INFO_CLASS);
	} else {
		packageInfo= fragment.getCompilationUnit(PACKAGE_INFO_JAVA);
	}
	if (packageInfo != null && packageInfo.exists()) {
		String source = packageInfo.getSource();
		//the source can be null for some of the class files
		if (source != null) {
			Javadoc javadocNode = getPackageJavadocNode(fragment, source);
			if (javadocNode != null) {
				int start = javadocNode.getStartPosition();
				int length = javadocNode.getLength();
				return new JavaDocCommentReader(source, start, start + length - 1);
			}
		}
	}
	return null;
}
 
Example 4
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private ICompilationUnit getNewCompilationUnit() {
	ICompilationUnit cu = fType.getCompilationUnit();
	if (isPrimaryType()) {
		IPackageFragment parent = fType.getPackageFragment();
		String renamedCUName = JavaModelUtil.getRenamedCUName(cu, getNewElementName());
		return parent.getCompilationUnit(renamedCUName);
	} else {
		return cu;
	}
}
 
Example 5
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IEditorPart openDeclaration(IJavaElement element) throws PartInitException, JavaModelException {
	if (!(element instanceof IPackageFragment)) {
		return JavaUI.openInEditor(element);
	}
	
	IPackageFragment packageFragment= (IPackageFragment) element;
	ITypeRoot typeRoot;
	IPackageFragmentRoot root= (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
		typeRoot= packageFragment.getClassFile(JavaModelUtil.PACKAGE_INFO_CLASS);
	} else {
		typeRoot= packageFragment.getCompilationUnit(JavaModelUtil.PACKAGE_INFO_JAVA);
	}

	// open the package-info file in editor if one exists
	if (typeRoot.exists())
		return JavaUI.openInEditor(typeRoot);

	// open the package.html file in editor if one exists
	Object[] nonJavaResources= packageFragment.getNonJavaResources();
	for (Object nonJavaResource : nonJavaResources) {
		if (nonJavaResource instanceof IFile) {
			IFile file= (IFile) nonJavaResource;
			if (file.exists() && JavaModelUtil.PACKAGE_HTML.equals(file.getName())) {
				return EditorUtility.openInEditor(file, true);
			}
		}
	}

	// select the package in the Package Explorer if there is no associated package Javadoc file
	PackageExplorerPart view= (PackageExplorerPart) JavaPlugin.getActivePage().showView(JavaUI.ID_PACKAGES);
	view.tryToReveal(packageFragment);
	return null;
}
 
Example 6
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void getWrongPackageDeclNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked= cu.getResource().isLinked();

	// correct package declaration
	int relevance= cu.getPackageDeclarations().length == 0 ? IProposalRelevance.MISSING_PACKAGE_DECLARATION : IProposalRelevance.CORRECT_PACKAGE_DECLARATION; // bug 38357
	proposals.add(new CorrectPackageDeclarationProposal(cu, problem, relevance));

	// move to package
	IPackageDeclaration[] packDecls= cu.getPackageDeclarations();
	String newPackName= packDecls.length > 0 ? packDecls[0].getElementName() : ""; //$NON-NLS-1$

	IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(cu);
	IPackageFragment newPack= root.getPackageFragment(newPackName);

	ICompilationUnit newCU= newPack.getCompilationUnit(cu.getElementName());
	if (!newCU.exists() && !isLinked) {
		String label;
		if (newPack.isDefaultPackage()) {
			label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_movecu_default_description, BasicElementLabels.getFileName(cu));
		} else {
			String packageLabel= JavaElementLabels.getElementLabel(newPack, JavaElementLabels.ALL_DEFAULT);
			label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_movecu_description, new Object[] { BasicElementLabels.getFileName(cu), packageLabel });
		}
		CompositeChange composite= new CompositeChange(label);
		composite.add(new CreatePackageChange(newPack));
		composite.add(new MoveCompilationUnitChange(cu, newPack));

		proposals.add(new ChangeCorrectionProposal(label, composite, IProposalRelevance.MOVE_CU_TO_PACKAGE, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_MOVE)));
	}
}
 
Example 7
Source File: ChangeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static ICompilationUnit getNewCompilationUnit(IType type, String newName) {
	ICompilationUnit cu = type.getCompilationUnit();
	if (isPrimaryType(type)) {
		IPackageFragment parent = type.getPackageFragment();
		String renamedCUName = JavaModelUtil.getRenamedCUName(cu, newName);
		return parent.getCompilationUnit(renamedCUName);
	} else {
		return cu;
	}
}
 
Example 8
Source File: ReorgCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void getWrongPackageDeclNameProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	ICompilationUnit cu= context.getCompilationUnit();

	// correct package declaration
	int relevance= cu.getPackageDeclarations().length == 0 ? IProposalRelevance.MISSING_PACKAGE_DECLARATION : IProposalRelevance.CORRECT_PACKAGE_DECLARATION; // bug 38357
	proposals.add(new CorrectPackageDeclarationProposal(cu, problem, relevance));

	// move to package
	IPackageDeclaration[] packDecls= cu.getPackageDeclarations();
	String newPackName= packDecls.length > 0 ? packDecls[0].getElementName() : ""; //$NON-NLS-1$

	IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(cu);
	IPackageFragment newPack= root.getPackageFragment(newPackName);

	ICompilationUnit newCU= newPack.getCompilationUnit(cu.getElementName());
	boolean isLinked= cu.getResource().isLinked();
	if (!newCU.exists() && !isLinked) {
		String label;
		if (newPack.isDefaultPackage()) {
			label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_movecu_default_description, BasicElementLabels.getFileName(cu));
		} else {
			String packageLabel= JavaElementLabels.getElementLabel(newPack, JavaElementLabels.ALL_DEFAULT);
			label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_movecu_description, new Object[] { BasicElementLabels.getFileName(cu), packageLabel });
		}

		proposals.add(new ChangeCorrectionProposal(label, CodeActionKind.QuickFix, new MoveCompilationUnitChange(cu, newPack), IProposalRelevance.MOVE_CU_TO_PACKAGE));
	}
}
 
Example 9
Source File: RenameCompilationUnitProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object getNewElement() {
	IPackageFragment pack= (IPackageFragment) fCu.getParent();
	if (JavaConventionsUtil.validateCompilationUnitName(getNewElementName(), pack).getSeverity() == IStatus.ERROR) {
		return null;
	}
	return pack.getCompilationUnit(getNewElementName());
}
 
Example 10
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test1() throws Exception {
	requireJUnitSources();
	ICompilationUnit cu= (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
	assertNotNull("BaseTestRunner.java", cu);
	IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
	IPackageFragment pack= root.createPackageFragment("mytest", true, null);
	ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
	colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
	String[] order= new String[0];
	IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		//@formatter:off
		assertImports(cu, new String[] {
			"java.io.BufferedReader",
			"java.io.File",
			"java.io.FileInputStream",
			"java.io.FileOutputStream",
			"java.io.IOException",
			"java.io.InputStream",
			"java.io.PrintWriter",
			"java.io.StringReader",
			"java.io.StringWriter",
			"java.lang.reflect.InvocationTargetException",
			"java.lang.reflect.Method",
			"java.lang.reflect.Modifier",
			"java.text.NumberFormat",
			"java.util.Properties",
			"junit.framework.AssertionFailedError",
			"junit.framework.Test",
			"junit.framework.TestListener",
			"junit.framework.TestSuite"
		});
		//@formatter:on
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 11
Source File: ImportOrganizeTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void test1WithOrder() throws Exception {
	requireJUnitSources();
	ICompilationUnit cu = (ICompilationUnit) javaProject.findElement(new Path("junit/runner/BaseTestRunner.java"));
	assertNotNull("BaseTestRunner.java is missing", cu);
	IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent();
	IPackageFragment pack= root.createPackageFragment("mytest", true, null);
	ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java");
	colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null);
	String[] order= new String[] { "junit", "java.text", "java.io", "java" };
	IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 });
	OrganizeImportsOperation op = createOperation(cu, order, false, true, true, query);
	TextEdit edit = op.createTextEdit(new NullProgressMonitor());
	IDocument document = new Document(cu.getSource());
	edit.apply(document);
	try {
		cu.becomeWorkingCopy(new NullProgressMonitor());
		cu.getBuffer().setContents(document.get());
		cu.reconcile(ICompilationUnit.NO_AST, true, null, new NullProgressMonitor());
		//@formatter:off
		assertImports(cu, new String[] {
			"junit.framework.AssertionFailedError",
			"junit.framework.Test",
			"junit.framework.TestListener",
			"junit.framework.TestSuite",
			"java.text.NumberFormat",
			"java.io.BufferedReader",
			"java.io.File",
			"java.io.FileInputStream",
			"java.io.FileOutputStream",
			"java.io.IOException",
			"java.io.InputStream",
			"java.io.PrintWriter",
			"java.io.StringReader",
			"java.io.StringWriter",
			"java.lang.reflect.InvocationTargetException",
			"java.lang.reflect.Method",
			"java.lang.reflect.Modifier",
			"java.util.Properties"
		});
		//@formatter:on
	} finally {
		cu.discardWorkingCopy();
	}
}
 
Example 12
Source File: ClasspathResourceUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the given file or JAR entry if it is on the given package fragment. The file can be a Java file, class
 * file, or a non-Java resource.
 * <p>
 * This method returns null for .java files or .class files inside JARs.
 *
 * @param fileName
 *          the file name
 * @param pckgFragment
 *          the package fragment to search
 * @return the file as an IResource or IJarEntryResource, or null
 * @throws JavaModelException
 */
public static IStorage resolveFileOnPackageFragment(String fileName, IPackageFragment pckgFragment)
    throws JavaModelException {

  boolean isJavaFile = JavaCore.isJavaLikeFileName(fileName);
  boolean isClassFile = ResourceUtils.endsWith(fileName, ".class");

  // Check the non-Java resources first
  Object[] nonJavaResources = pckgFragment.getNonJavaResources();
  for (Object nonJavaResource : nonJavaResources) {
    if (nonJavaResource instanceof IFile) {
      IFile file = (IFile) nonJavaResource;
      String resFileName = file.getName();

      if (ResourceUtils.areFilenamesEqual(resFileName, fileName)) {
        // Java source files that have been excluded from the build path
        // show up as non-Java resources, but we'll ignore them since
        // they're not available on the classpath.
        if (!JavaCore.isJavaLikeFileName(resFileName)) {
          return file;
        } else {
          return null;
        }
      }
    }

    // JAR resources are not IResource's, so we need to handle them
    // differently
    if (nonJavaResource instanceof IJarEntryResource) {
      IJarEntryResource jarEntry = (IJarEntryResource) nonJavaResource;
      if (jarEntry.isFile() && ResourceUtils.areFilenamesEqual(jarEntry.getName(), fileName)) {
        return jarEntry;
      }
    }
  }

  // If we're looking for a .java or .class file, we can use the regular
  // Java Model methods.

  if (isJavaFile) {
    ICompilationUnit cu = pckgFragment.getCompilationUnit(fileName);
    if (cu.exists()) {
      return (IFile) cu.getCorrespondingResource();
    }
  }

  if (isClassFile) {
    IClassFile cf = pckgFragment.getClassFile(fileName);
    if (cf.exists()) {
      return (IFile) cf.getCorrespondingResource();
    }
  }

  return null;
}
 
Example 13
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Hook method that gets called when the type name has changed. The method validates the
 * type name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
	StatusInfo status= new StatusInfo();
	fCurrType= null;
	String typeNameWithParameters= getTypeName();
	// must not be empty
	if (typeNameWithParameters.length() == 0) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
		return status;
	}

	String typeName= getTypeNameWithoutParameters();
	if (typeName.indexOf('.') != -1) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
		return status;
	}

	IJavaProject project= getJavaProject();
	IStatus val= validateJavaTypeName(typeName, project);
	if (val.getSeverity() == IStatus.ERROR) {
		status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
		return status;
	} else if (val.getSeverity() == IStatus.WARNING) {
		status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
		// continue checking
	}

	// must not exist
	if (!isEnclosingTypeSelected()) {
		IPackageFragment pack= getPackageFragment();
		if (pack != null) {
			ICompilationUnit cu= pack.getCompilationUnit(getCompilationUnitName(typeName));
			fCurrType= cu.getType(typeName);
			IResource resource= cu.getResource();

			if (resource.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameFiltered);
				return status;
			}
			URI location= resource.getLocationURI();
			if (location != null) {
				try {
					IFileStore store= EFS.getStore(location);
					if (store.fetchInfo().exists()) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
						return status;
					}
				} catch (CoreException e) {
					status.setError(Messages.format(
						NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
						BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
				}
			}
		}
	} else {
		IType type= getEnclosingType();
		if (type != null) {
			fCurrType= type.getType(typeName);
			if (fCurrType.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
		}
	}

	if (!typeNameWithParameters.equals(typeName) && project != null) {
		if (!JavaModelUtil.is50OrHigher(project)) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
			return status;
		}
		String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(typeDeclaration.toCharArray());
		parser.setProject(project);
		CompilationUnit compilationUnit= (CompilationUnit) parser.createAST(null);
		IProblem[] problems= compilationUnit.getProblems();
		if (problems.length > 0) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
			return status;
		}
	}
	return status;
}
 
Example 14
Source File: MoveCompilationUnitChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
Change doPerformReorg(IProgressMonitor pm) throws CoreException, OperationCanceledException {
	String name;
	String newName= getNewName();
	if (newName == null) {
		name= getCu().getElementName();
	} else {
		name= newName;
	}

	// get current modification stamp
	long currentStamp= IResource.NULL_STAMP;
	IResource resource= getCu().getResource();
	if (resource != null) {
		currentStamp= resource.getModificationStamp();
	}

	IPackageFragment destination= getDestinationPackage();
	fUndoable= !destination.exists() || !destination.getCompilationUnit(name).exists();

	IPackageFragment[] createdPackages= null;
	if (!destination.exists()) {
		IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot) destination.getParent();
		createdPackages= createDestination(packageFragmentRoot, destination, pm);
	}

	// perform the move and restore modification stamp
	getCu().move(destination, null, newName, true, pm);
	if (fStampToRestore != IResource.NULL_STAMP) {
		ICompilationUnit moved= destination.getCompilationUnit(name);
		IResource movedResource= moved.getResource();
		if (movedResource != null) {
			movedResource.revertModificationStamp(fStampToRestore);
		}
	}

	if (fDeletePackages != null) {
		for (int i= fDeletePackages.length - 1; i >= 0; i--) {
			fDeletePackages[i].delete(true, pm);
		}
	}

	if (fUndoable) {
		return new MoveCompilationUnitChange(destination, getCu().getElementName(), getOldPackage(), currentStamp, createdPackages);
	} else {
		return null;
	}
}
 
Example 15
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public List<ResourceChange> createTopLevelParameterObject(IPackageFragmentRoot packageFragmentRoot, CreationListener listener) throws CoreException {
	List<ResourceChange> changes= new ArrayList<ResourceChange>();
	IPackageFragment packageFragment= packageFragmentRoot.getPackageFragment(getPackage());
	if (!packageFragment.exists()) {
		changes.add(new CreatePackageChange(packageFragment));
	}
	ICompilationUnit unit= packageFragment.getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX);
	Assert.isTrue(!unit.exists());
	IJavaProject javaProject= unit.getJavaProject();
	ICompilationUnit workingCopy= unit.getWorkingCopy(null);

	try {
		// create stub with comments and dummy type
		String lineDelimiter= StubUtility.getLineDelimiterUsed(javaProject);
		String fileComment= getFileComment(workingCopy, lineDelimiter);
		String typeComment= getTypeComment(workingCopy, lineDelimiter);
		String content= CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment, "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
		workingCopy.getBuffer().setContents(content);

		CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(workingCopy);
		ASTRewrite rewriter= cuRewrite.getASTRewrite();
		CompilationUnit root= cuRewrite.getRoot();
		AST ast= cuRewrite.getAST();
		ImportRewrite importRewrite= cuRewrite.getImportRewrite();

		// retrieve&replace dummy type with real class
		ListRewrite types= rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
		ASTNode dummyType= (ASTNode) types.getOriginalList().get(0);
		String newTypeName= JavaModelUtil.concatenateName(getPackage(), getClassName());
		TypeDeclaration classDeclaration= createClassDeclaration(newTypeName, cuRewrite, listener);
		classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		Javadoc javadoc= (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY);
		rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null);
		types.replace(dummyType, classDeclaration, null);

		// Apply rewrites and discard workingcopy
		// Using CompilationUnitRewrite.createChange() leads to strange
		// results
		String charset= ResourceUtil.getFile(unit).getCharset(false);
		Document document= new Document(content);
		try {
			rewriter.rewriteAST().apply(document);
			TextEdit rewriteImports= importRewrite.rewriteImports(null);
			rewriteImports.apply(document);
		} catch (BadLocationException e) {
			throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error, e));
		}
		String docContent= document.get();
		CreateCompilationUnitChange compilationUnitChange= new CreateCompilationUnitChange(unit, docContent, charset);
		changes.add(compilationUnitChange);
	} finally {
		workingCopy.discardWorkingCopy();
	}
	return changes;
}
 
Example 16
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public final Change createChange(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 1); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
		final Map<String, String> arguments= new HashMap<String, String>();
		String project= null;
		final IJavaProject javaProject= fSubType.getJavaProject();
		if (javaProject != null)
			project= javaProject.getElementName();
		int flags= JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
		try {
			if (fSubType.isLocal() || fSubType.isAnonymous())
				flags|= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
		} catch (JavaModelException exception) {
			JavaPlugin.log(exception);
		}
		final IPackageFragment fragment= fSubType.getPackageFragment();
		final ICompilationUnit cu= fragment.getCompilationUnit(JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), fSuperName));
		final IType type= cu.getType(fSuperName);
		final String description= Messages.format(RefactoringCoreMessages.ExtractInterfaceProcessor_description_descriptor_short, BasicElementLabels.getJavaElementName(fSuperName));
		final String header= Messages.format(RefactoringCoreMessages.ExtractInterfaceProcessor_descriptor_description, new String[] { JavaElementLabels.getElementLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getElementLabel(fSubType, JavaElementLabels.ALL_FULLY_QUALIFIED) });
		final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
		comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractInterfaceProcessor_refactored_element_pattern, JavaElementLabels.getElementLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED)));
		final String[] settings= new String[fMembers.length];
		for (int index= 0; index < settings.length; index++)
			settings[index]= JavaElementLabels.getElementLabel(fMembers[index], JavaElementLabels.ALL_FULLY_QUALIFIED);
		comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ExtractInterfaceProcessor_extracted_members_pattern, settings));
		addSuperTypeSettings(comment, true);
		final ExtractInterfaceDescriptor descriptor= RefactoringSignatureDescriptorFactory.createExtractInterfaceDescriptor(project, description, comment.asString(), arguments, flags);
		arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fSubType));
		arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fSuperName);
		for (int index= 0; index < fMembers.length; index++)
			arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT + (index + 1), JavaRefactoringDescriptorUtil.elementToHandle(project, fMembers[index]));
		arguments.put(ATTRIBUTE_ABSTRACT, Boolean.valueOf(fAbstract).toString());
		arguments.put(ATTRIBUTE_COMMENTS, Boolean.valueOf(fComments).toString());
		arguments.put(ATTRIBUTE_PUBLIC, Boolean.valueOf(fPublic).toString());
		arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplace).toString());
		arguments.put(ATTRIBUTE_INSTANCEOF, Boolean.valueOf(fInstanceOf).toString());
		final DynamicValidationRefactoringChange change= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ExtractInterfaceRefactoring_name, fChangeManager.getAllChanges());
		final IFile file= ResourceUtil.getFile(fSubType.getCompilationUnit());
		if (fSuperSource != null && fSuperSource.length() > 0)
			change.add(new CreateCompilationUnitChange(fSubType.getPackageFragment().getCompilationUnit(JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), fSuperName)), fSuperSource, file.getCharset(false)));
		monitor.worked(1);
		return change;
	} finally {
		monitor.done();
	}
}
 
Example 17
Source File: RenameCompilationUnitProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public Object getNewElement() {
	IPackageFragment pack= (IPackageFragment) fCu.getParent();
	if (JavaConventionsUtil.validateCompilationUnitName(getNewElementName(), pack).getSeverity() == IStatus.ERROR)
		return null;
	return pack.getCompilationUnit(getNewElementName());
}
 
Example 18
Source File: GenericRefactoringHandleTransplanter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
protected ICompilationUnit transplantHandle(IPackageFragment parent, ICompilationUnit element) {
	return parent.getCompilationUnit(element.getElementName());
}
 
Example 19
Source File: GenericRefactoringHandleTransplanter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected ICompilationUnit transplantHandle(IPackageFragment parent, ICompilationUnit element) {
	return parent.getCompilationUnit(element.getElementName());
}
 
Example 20
Source File: MoveCompilationUnitChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
Change doPerformReorg(IProgressMonitor pm) throws CoreException, OperationCanceledException {
	String name;
	String newName= getNewName();
	if (newName == null)
		name= getCu().getElementName();
	else
		name= newName;

	// get current modification stamp
	long currentStamp= IResource.NULL_STAMP;
	IResource resource= getCu().getResource();
	if (resource != null) {
		currentStamp= resource.getModificationStamp();
	}

	IPackageFragment destination= getDestinationPackage();
	fUndoable= !destination.exists() || !destination.getCompilationUnit(name).exists();

	IPackageFragment[] createdPackages= null;
	if (!destination.exists()) {
		IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot) destination.getParent();
		createdPackages= createDestination(packageFragmentRoot, destination, pm);
	}

	// perform the move and restore modification stamp
	getCu().move(destination, null, newName, true, pm);
	if (fStampToRestore != IResource.NULL_STAMP) {
		ICompilationUnit moved= destination.getCompilationUnit(name);
		IResource movedResource= moved.getResource();
		if (movedResource != null) {
			movedResource.revertModificationStamp(fStampToRestore);
		}
	}

	if (fDeletePackages != null) {
		for (int i= fDeletePackages.length - 1; i >= 0; i--) {
			fDeletePackages[i].delete(true, pm);
		}
	}

	if (fUndoable) {
		return new MoveCompilationUnitChange(destination, getCu().getElementName(), getOldPackage(), currentStamp, createdPackages);
	} else {
		return null;
	}
}