Java Code Examples for org.eclipse.jdt.core.JavaCore#createCompilationUnitFrom()

The following examples show how to use org.eclipse.jdt.core.JavaCore#createCompilationUnitFrom() . 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: MethodFinder.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
public IMethod convertMethodDecl2IMethod(MethodDeclaration methodDecl){
	SimpleName methodName = methodDecl.getName();
	//cu.accept(visitor);
	
	try {
		ICompilationUnit iCompilationUnit = JavaCore.createCompilationUnitFrom((IFile) resource);
		
		int startPos = methodDecl.getStartPosition();
		IJavaElement element = iCompilationUnit.getElementAt(startPos);
		if(element instanceof IMethod) {
			return (IMethod) element;
		}
		return null;
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 2
Source File: ClassPathDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void visitCompilationUnit(IFile file) {
	ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
	if (cu != null) {
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		CompilationUnit root= (CompilationUnit)parser.createAST(null);
		PackageDeclaration packDecl= root.getPackage();
		
		IPath packPath= file.getParent().getFullPath();
		String cuName= file.getName();
		if (packDecl == null) {
			addToMap(fSourceFolders, packPath, new Path(cuName));
		} else {
			IPath relPath= new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			IPath folderPath= getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(fSourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
Example 3
Source File: SarlClassPathDetector.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Visit the given Java compilation unit.
 *
 * @param jfile the compilation unit.
 */
protected void visitJavaCompilationUnit(IFile jfile) {
	final ICompilationUnit cu = JavaCore.createCompilationUnitFrom(jfile);
	if (cu != null) {
		final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		final CompilationUnit root = (CompilationUnit) parser.createAST(null);
		final PackageDeclaration packDecl = root.getPackage();

		final IPath packPath = jfile.getParent().getFullPath();
		final String cuName = jfile.getName();
		if (packDecl == null) {
			addToMap(this.sourceFolders, packPath, new Path(cuName));
		} else {
			final IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			final IPath folderPath = getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(this.sourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
Example 4
Source File: CodeGenerator.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method organizes imports for all generated files and the file, in which the call code for the generated classes is inserted.
 *
 * @param editor
 *        Editor with the currently open file
 * @throws CoreException
 *         {@link DeveloperProject#refresh() refresh()} and {@link DeveloperProject#getPackagesOfProject(String) getPackagesOfProject()}
 */
protected void cleanUpProject(IEditorPart editor) throws CoreException {
	this.project.refresh();
	final ICompilationUnit[] generatedCUnits = this.project.getPackagesOfProject(Constants.PackageNameAsName).getCompilationUnits();
	boolean anyFileOpen = false;

	if (editor == null && generatedCUnits[0].getResource().getType() == IResource.FILE) {
		IFile genClass = (IFile) generatedCUnits[0].getResource();
		IDE.openEditor(UIUtils.getCurrentlyOpenPage(), genClass);
		editor = UIUtils.getCurrentlyOpenPage().getActiveEditor();
		anyFileOpen = true;
	}

	final OrganizeImportsAction organizeImportsActionForAllFilesTouchedDuringGeneration = new OrganizeImportsAction(editor.getSite());
	final FormatAllAction faa = new FormatAllAction(editor.getSite());
	faa.runOnMultiple(generatedCUnits);
	organizeImportsActionForAllFilesTouchedDuringGeneration.runOnMultiple(generatedCUnits);

	if (anyFileOpen) {
		UIUtils.closeEditor(editor);
	}

	final ICompilationUnit openClass = JavaCore.createCompilationUnitFrom(UIUtils.getCurrentlyOpenFile(editor));
	organizeImportsActionForAllFilesTouchedDuringGeneration.run(openClass);
	faa.runOnMultiple(new ICompilationUnit[] { openClass });
	editor.doSave(null);
}
 
Example 5
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static ICompilationUnit resolveCompilationUnit(IFile resource) {
	if(resource != null){
		if(!ProjectUtils.isJavaProject(resource.getProject())){
			return null;
		}
		if (resource.getFileExtension() != null) {
			String name = resource.getName();
			if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(name)) {
				return JavaCore.createCompilationUnitFrom(resource);
			}
		}
	}

	return null;
}
 
Example 6
Source File: WorkItem.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Add secondary types patterns (not nested in the type itself but contained
 * in the java file)
 *
 * @param fileName
 *            java file name (not path!) without .java suffix
 * @param classNamePattern
 *            non null pattern for all matching .class file names
 * @return modified classNamePattern, if there are more then one type
 *         defined in the java file
 */
private static String addSecondaryTypesToPattern(IFile file, String fileName, String classNamePattern) {
    ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
    if (cu == null) {
        FindbugsPlugin.getDefault().logError(
                "NULL compilation unit for " + file + ", FB analysis might  be incomplete for included types");
        return classNamePattern;
    }
    try {
        IType[] types = cu.getTypes();
        if (types.length > 1) {
            StringBuilder sb = new StringBuilder(classNamePattern);
            for (IType type : types) {
                if (fileName.equals(type.getElementName())) {
                    // "usual" type with the same name: we have it already
                    continue;
                }
                sb.append("|").append(type.getElementName());
                sb.append("\\.class|").append(type.getElementName());
                sb.append("\\$.*\\.class");
            }
            classNamePattern = sb.toString();
        }
    } catch (JavaModelException e) {
        FindbugsPlugin.getDefault().logException(e, "Cannot get types from compilation unit: " + cu);
    }
    return classNamePattern;
}
 
Example 7
Source File: LogContent.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes the address of a particular line in a Java source file, in the
 * format accepted by
 * {@link LogContent#buildJavaSourceHyperlink(String, String)}.
 */
private static String computeJavaSourceAddress(String filesystemPath,
    String lineNumber) {
  IPath path = new Path(filesystemPath);
  IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
      path);
  if (file != null && file.exists()) {
    ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
    if (cu != null) {
      IJavaElement cuParent = cu.getParent();
      if (cuParent instanceof IPackageFragment) {
        IPackageFragment pckgFragment = (IPackageFragment) cuParent;

        StringBuffer sb = new StringBuffer();
        sb.append(pckgFragment.getElementName());
        /*
         * We can use anything for the type and method, since
         * JavaStackTraceHyperlink will strip it out anyway (it only uses the
         * package name, the compilation unit name, and the line number).
         */
        sb.append(".DummyType.dummyMethod");
        sb.append('(');
        sb.append(cu.getElementName());
        sb.append(':');
        sb.append(lineNumber);
        sb.append(')');
        return sb.toString();
      }
    }
  }
  return null;
}
 
Example 8
Source File: GroovyFileStore.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
public ICompilationUnit getCompilationUnit() {
    return JavaCore.createCompilationUnitFrom(getResource());
}