org.eclipse.jdt.internal.core.JavaModelManager Java Examples

The following examples show how to use org.eclipse.jdt.internal.core.JavaModelManager. 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: ProjectAwareUniqueClassNameValidator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private SourceTraversal doCheckUniqueInProjectSource(String packageName, String typeName, JvmDeclaredType type,
		List<IPackageFragmentRoot> sourceFolders) throws JavaModelException {
	IndexManager indexManager = JavaModelManager.getIndexManager();
	for (IPackageFragmentRoot sourceFolder : sourceFolders) {
		if (indexManager.awaitingJobsCount() > 0) {
			if (!isDerived(sourceFolder.getResource())) {
				IPackageFragment packageFragment = sourceFolder.getPackageFragment(packageName);
				if (packageFragment.exists()) {
					for (ICompilationUnit unit : packageFragment.getCompilationUnits()) {
						if (!isDerived(unit.getResource())) {
							IType javaType = unit.getType(typeName);
							if (javaType.exists()) {
								addIssue(type, unit.getElementName());
								return SourceTraversal.DUPLICATE;
							}
						}
					}
				}
			}
		} else {
			return SourceTraversal.INTERRUPT;
		}
	}
	return SourceTraversal.UNIQUE;
}
 
Example #2
Source File: PatternSearchJob.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public Index[] getIndexes(IProgressMonitor progressMonitor) {
	// acquire the in-memory indexes on the fly
	IndexLocation[] indexLocations;
	int length;
	if (this.participant instanceof JavaSearchParticipant) {
		indexLocations = ((JavaSearchParticipant)this.participant).selectIndexURLs(this.pattern, this.scope);
		length = indexLocations.length;
	} else {
		IPath[] paths = this.participant.selectIndexes(this.pattern, this.scope);
		length = paths.length;
		indexLocations = new IndexLocation[paths.length];
		for (int i = 0, len = paths.length; i < len; i++) {
			indexLocations[i] = new FileIndexLocation(paths[i].toFile(), true);
		}
	}
	Index[] indexes = JavaModelManager.getIndexManager().getIndexes(indexLocations, progressMonitor);
	this.areIndexesReady = indexes.length == length;
	return indexes;
}
 
Example #3
Source File: Util.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static String getSourceAttachmentProperty(IPath path) throws JavaModelException {
	Map rootPathToAttachments = JavaModelManager.getJavaModelManager().rootPathToAttachments;
	String property = (String) rootPathToAttachments.get(path);
	if (property == null) {
		try {
			property = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(getSourceAttachmentPropertyName(path));
			if (property == null) {
				rootPathToAttachments.put(path, PackageFragmentRoot.NO_SOURCE_ATTACHMENT);
				return null;
			}
			rootPathToAttachments.put(path, property);
			return property;
		} catch (CoreException e)  {
			throw new JavaModelException(e);
		}
	} else if (property.equals(PackageFragmentRoot.NO_SOURCE_ATTACHMENT)) {
		return null;
	} else
		return property;
}
 
Example #4
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public static IFolder createExternalFolder(String folderName) throws CoreException {
		final Wrapper<IFolder> wrapper = Wrapper.forType(IFolder.class);
		ResourcesPlugin.getWorkspace().run((monitor)->{
			IPath externalFolderPath = new Path(folderName);
			IProject externalFoldersProject = JavaModelManager.getExternalManager().getExternalFoldersProject();
			if (!externalFoldersProject.isAccessible()) {
				if (!externalFoldersProject.exists())
					externalFoldersProject.create(monitor());
				externalFoldersProject.open(monitor());
			}
			IFolder result = externalFoldersProject.getFolder(externalFolderPath);
			result.create(true, false, null);
//				JavaModelManager.getExternalManager().addFolder(result.getFullPath());
			wrapper.set(result);
		}, monitor());
		return wrapper.get();
	}
 
Example #5
Source File: SearchParticipant.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Schedules the indexing of the given document.
 * Once the document is ready to be indexed,
 * {@link #indexDocument(SearchDocument, IPath) indexDocument(document, indexPath)}
 * will be called in a different thread than the caller's thread.
 * <p>
 * The given index location must represent a path in the file system to a file that
 * either already exists or is going to be created. If it exists, it must be an index file,
 * otherwise its data might be overwritten.
 * </p><p>
 * When the index is no longer needed, clients should use {@link #removeIndex(IPath) }
 * to discard it.
 * </p>
 *
 * @param document the document to index
 * @param indexPath the location on the file system of the index
 */
public final void scheduleDocumentIndexing(SearchDocument document, IPath indexPath) {
	IPath documentPath = new Path(document.getPath());
	Object file = JavaModel.getTarget(documentPath, true);
	IPath containerPath = documentPath;
	if (file instanceof IResource) {
		containerPath = ((IResource)file).getProject().getFullPath();
	} else if (file == null) {
		containerPath = documentPath.removeLastSegments(1);
	}
	IndexManager manager = JavaModelManager.getIndexManager();
	// TODO (frederic) should not have to create index manually, should expose API that recreates index instead
	IndexLocation indexLocation;
	indexLocation = new FileIndexLocation(indexPath.toFile(), true);
	manager.ensureIndexExists(indexLocation, containerPath);
	manager.scheduleDocumentIndexing(document, containerPath, indexLocation, this);
	if (!indexPath.equals(this.lastIndexLocation)) {
		manager.updateParticipant(indexPath, containerPath);
		this.lastIndexLocation = indexPath;
	}
}
 
Example #6
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private IBinding resolveBindings(IType jdtType, IJavaProject javaProject) {
	ThreadLocal<Boolean> abortOnMissingSource = JavaModelManager.getJavaModelManager().abortOnMissingSource;
	Boolean wasAbortOnMissingSource = abortOnMissingSource.get();
	try {
		abortOnMissingSource.set(Boolean.TRUE);
		resolveBinding.start();

		parser.setWorkingCopyOwner(workingCopyOwner);
		parser.setIgnoreMethodBodies(true);
		
		parser.setProject(javaProject);
		
		Map<String, String> options = javaProject.getOptions(true);
		
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.DISABLED);
		parser.setCompilerOptions(options);

		IBinding[] bindings = parser.createBindings(new IJavaElement[] { jdtType }, null);
		resolveBinding.stop();
		return bindings[0];
	} finally {
		abortOnMissingSource.set(wasAbortOnMissingSource);
	}
}
 
Example #7
Source File: WorkspaceEventsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private ICompilationUnit createCompilationUnit(ICompilationUnit unit) {
	try {
		unit.getResource().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
		if (unit.getResource().exists()) {
			IJavaElement parent = unit.getParent();
			if (parent instanceof PackageFragment) {
				PackageFragment pkg = (PackageFragment) parent;
				if (JavaModelManager.determineIfOnClasspath(unit.getResource(), unit.getJavaProject()) != null) {
					OpenableElementInfo elementInfo = (OpenableElementInfo) pkg.getElementInfo();
					elementInfo.addChild(unit);
				}
			}
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException(e.getMessage(), e);
	}
	return unit;
}
 
Example #8
Source File: FileEventHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static ICompilationUnit createCompilationUnit(ICompilationUnit unit) {
	try {
		unit.getResource().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
		if (unit.getResource().exists()) {
			IJavaElement parent = unit.getParent();
			if (parent instanceof IPackageFragment) {
				IPackageFragment pkg = (IPackageFragment) parent;
				if (JavaModelManager.determineIfOnClasspath(unit.getResource(), unit.getJavaProject()) != null) {
					unit = pkg.createCompilationUnit(unit.getElementName(), unit.getSource(), true, new NullProgressMonitor());
				}
			}
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException(e.getMessage(), e);
	}
	return unit;
}
 
Example #9
Source File: SourceIndexer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void resolveDocument() {
	try {
		IPath path = new Path(this.document.getPath());
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
		JavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
		JavaProject javaProject = (JavaProject) model.getJavaProject(project);

		this.options = new CompilerOptions(javaProject.getOptions(true));
		ProblemReporter problemReporter =
				new ProblemReporter(
						DefaultErrorHandlingPolicies.proceedWithAllProblems(),
						this.options,
						new DefaultProblemFactory());

		// Re-parse using normal parser, IndexingParser swallows several nodes, see comment above class.
		this.basicParser = new Parser(problemReporter, false);
		this.basicParser.reportOnlyOneSyntaxError = true;
		this.basicParser.scanner.taskTags = null;
		this.cud = this.basicParser.parse(this.compilationUnit, new CompilationResult(this.compilationUnit, 0, 0, this.options.maxProblemsPerUnit));

		// Use a non model name environment to avoid locks, monitors and such.
		INameEnvironment nameEnvironment = new JavaSearchNameEnvironment(javaProject, JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, true/*add primary WCs*/));
		this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, nameEnvironment);
		reduceParseTree(this.cud);
		this.lookupEnvironment.buildTypeBindings(this.cud, null);
		this.lookupEnvironment.completeTypeBindings();
		this.cud.scope.faultInTypes();
		this.cud.resolve();
	} catch (Exception e) {
		if (JobManager.VERBOSE) {
			e.printStackTrace();
		}
	}
}
 
Example #10
Source File: AbstractIndexer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void addTypeDeclaration(int modifiers, char[] packageName, char[] name, char[][] enclosingTypeNames, boolean secondary) {
	char[] indexKey = TypeDeclarationPattern.createIndexKey(modifiers, name, packageName, enclosingTypeNames, secondary);
	if (secondary)
		JavaModelManager.getJavaModelManager().secondaryTypeAdding(
			this.document.getPath(),
			name == null ? CharOperation.NO_CHAR : name,
			packageName == null ? CharOperation.NO_CHAR : packageName);

	addIndexEntry(TYPE_DECL, indexKey);
}
 
Example #11
Source File: JavaSearchScope.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see AbstractJavaSearchScope#packageFragmentRoot(String, int, String)
 */
public IPackageFragmentRoot packageFragmentRoot(String resourcePathString, int jarSeparatorIndex, String jarPath) {
	int index = -1;
	boolean isJarFile = jarSeparatorIndex != -1;
	if (isJarFile) {
		// internal or external jar (case 3, 4, or 5)
		String relativePath = resourcePathString.substring(jarSeparatorIndex+1);
		index = indexOf(jarPath, relativePath);
	} else {
		// resource in workspace (case 1 or 2)
		index = indexOf(resourcePathString);
	}
	if (index >= 0) {
		int idx = this.projectIndexes[index];
		String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx);
		if (projectPath != null) {
			IJavaProject project =JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath));
			if (isJarFile) {
				IResource resource = JavaModel.getWorkspaceTarget(new Path(jarPath));
				if (resource != null)
					return project.getPackageFragmentRoot(resource);
				return project.getPackageFragmentRoot(jarPath);
			}
			Object target = JavaModel.getWorkspaceTarget(new Path(this.containerPaths[index]+'/'+this.relativePaths[index]));
			if (target != null) {
				if (target instanceof IProject) {
					return project.getPackageFragmentRoot((IProject) target);
				}
				IJavaElement element = JavaModelManager.create((IResource) target, project);
				return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
			}
		}
	}
	return null;
}
 
Example #12
Source File: CompletionUnitStructureRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected SourceMethod createMethodHandle(JavaElement parent, MethodInfo methodInfo) {
	String selector = JavaModelManager.getJavaModelManager().intern(new String(methodInfo.name));
	String[] parameterTypeSigs = convertTypeNamesToSigs(methodInfo.parameterTypes);
	AssistSourceMethod method = new AssistSourceMethod(parent, selector, parameterTypeSigs, this.bindingCache, this.newElements);
	if (methodInfo.node.binding != null) {
		this.bindingCache.put(method, methodInfo.node.binding);
		this.elementCache.put(methodInfo.node.binding, method);
	} else {
		this.elementWithProblemCache.put(methodInfo.node, method);
	}
	return method;
}
 
Example #13
Source File: CompletionUnitStructureRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected SourceField createField(JavaElement parent, FieldInfo fieldInfo) {
	String fieldName = JavaModelManager.getJavaModelManager().intern(new String(fieldInfo.name));
	AssistSourceField field = new AssistSourceField(parent, fieldName, this.bindingCache, this.newElements);
	if (fieldInfo.node.binding != null) {
		this.bindingCache.put(field, fieldInfo.node.binding);
		this.elementCache.put(fieldInfo.node.binding, field);
	} else {
		this.elementWithProblemCache.put(fieldInfo.node, field);
	}
	return field;
}
 
Example #14
Source File: XtendUIValidationTests.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testJavaDocRefs_Delegation() throws Exception {
  final IJavaProject javaProject = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProject(this.testHelper.getProject());
  final String javaSeverity = javaProject.getOption(JavaCore.COMPILER_PB_INVALID_JAVADOC, true);
  try {
    boolean _notEquals = (!Objects.equal(javaSeverity, "ignore"));
    if (_notEquals) {
      Assert.fail((("Wrong expectation Java compiler option \'" + JavaCore.COMPILER_PB_INVALID_JAVADOC) + "\' should be \'ignore\' by default"));
    }
    String otherSeverity = "warning";
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("class ValidationClazz {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("/**");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("* {@link List}");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("*/");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def doStuff(){}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtendFile xtendFile = this.testHelper.xtendFile("ValidationClazz.xtend", _builder.toString());
    XtendTypeDeclaration _head = IterableExtensions.<XtendTypeDeclaration>head(xtendFile.getXtendTypes());
    final XtendClass clazz = ((XtendClass) _head);
    final XtendMember member = IterableExtensions.<XtendMember>head(clazz.getMembers());
    this.helper.assertNoIssues(member);
    this.cache.clear(xtendFile.eResource());
    javaProject.setOption(JavaCore.COMPILER_PB_INVALID_JAVADOC, otherSeverity);
    this.helper.assertWarning(member, XtendPackage.Literals.XTEND_FUNCTION, IssueCodes.JAVA_DOC_LINKING_DIAGNOSTIC, "javaDoc", "List", "cannot be resolved to a type");
  } finally {
    javaProject.setOption(JavaCore.COMPILER_PB_INVALID_JAVADOC, javaSeverity);
  }
}
 
Example #15
Source File: XtendUIValidationTests.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testIssueCodeDelegation() {
  try {
    final IJavaProject javaProject = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProject(this.testHelper.getProject());
    final String javaSeverity = javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true);
    try {
      boolean _notEquals = (!Objects.equal(javaSeverity, "error"));
      if (_notEquals) {
        Assert.fail((("Wrong expectation Java compiler option \'" + JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE) + "\' should be \'error\' by default"));
      }
      String otherSeverity = "warning";
      StringConcatenation _builder = new StringConcatenation();
      _builder.append("class ValidationClazz {");
      _builder.newLine();
      _builder.append("\t");
      _builder.append("def bar(org.eclipse.xtend.core.tests.restricted.RestrictedClass x) {}");
      _builder.newLine();
      _builder.append("}");
      _builder.newLine();
      final XtendFile xtendFile = this.testHelper.xtendFile("ValidationClazz.xtend", _builder.toString());
      XtendMember _head = IterableExtensions.<XtendMember>head(IterableExtensions.<XtendClass>head(Iterables.<XtendClass>filter(xtendFile.getXtendTypes(), XtendClass.class)).getMembers());
      final XtendFunction function = ((XtendFunction) _head);
      this.helper.assertError(function.getParameters().get(0), TypesPackage.Literals.JVM_TYPE_REFERENCE, org.eclipse.xtext.xbase.validation.IssueCodes.FORBIDDEN_REFERENCE);
      this.cache.clear(xtendFile.eResource());
      javaProject.setOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, otherSeverity);
      this.helper.assertWarning(function.getParameters().get(0), TypesPackage.Literals.JVM_TYPE_REFERENCE, org.eclipse.xtext.xbase.validation.IssueCodes.FORBIDDEN_REFERENCE);
    } finally {
      javaProject.setOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, javaSeverity);
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #16
Source File: JavaLanguageServerPlugin.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void disableServices() {
	try {
		ProjectsManager.setAutoBuilding(false);
	} catch (CoreException e1) {
		JavaLanguageServerPlugin.logException(e1);
	}

	IndexManager indexManager = JavaModelManager.getIndexManager();
	if (indexManager != null) {
		indexManager.shutdown();
	}
}
 
Example #17
Source File: JavaBuilderState.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static JavaBuilderState getLastBuiltState(IProject project) {
	final State state;
	Object lastBuiltState = JavaModelManager.getJavaModelManager().getLastBuiltState(project, null);
	if (lastBuiltState instanceof State) {
		state = (State) lastBuiltState;
	} else {
		state = null;
	}
	return new JavaBuilderState(project, state);
}
 
Example #18
Source File: RegionBasedHierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void build(boolean computeSubtypes) {

	JavaModelManager manager = JavaModelManager.getJavaModelManager();
	try {
		// optimize access to zip files while building hierarchy
		manager.cacheZipFiles(this);

		if (this.hierarchy.focusType == null || computeSubtypes) {
			IProgressMonitor typeInRegionMonitor =
				this.hierarchy.progressMonitor == null ?
					null :
					new SubProgressMonitor(this.hierarchy.progressMonitor, 30);
			HashMap allOpenablesInRegion = determineOpenablesInRegion(typeInRegionMonitor);
			this.hierarchy.initialize(allOpenablesInRegion.size());
			IProgressMonitor buildMonitor =
				this.hierarchy.progressMonitor == null ?
					null :
					new SubProgressMonitor(this.hierarchy.progressMonitor, 70);
			createTypeHierarchyBasedOnRegion(allOpenablesInRegion, buildMonitor);
			((RegionBasedTypeHierarchy)this.hierarchy).pruneDeadBranches();
		} else {
			this.hierarchy.initialize(1);
			buildSupertypes();
		}
	} finally {
		manager.flushZipFiles(this);
	}
}
 
Example #19
Source File: Util.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void setSourceAttachmentProperty(IPath path, String property) {
	if (property == null) {
		JavaModelManager.getJavaModelManager().rootPathToAttachments.put(path, PackageFragmentRoot.NO_SOURCE_ATTACHMENT);
	} else {
		JavaModelManager.getJavaModelManager().rootPathToAttachments.put(path, property);
	}
	try {
		ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(getSourceAttachmentPropertyName(path), property);
	} catch (CoreException e) {
		e.printStackTrace();
	}
}
 
Example #20
Source File: State.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static AccessRuleSet readRestriction(DataInputStream in) throws IOException {
	int length = in.readInt();
	if (length == 0) return null; // no restriction specified
	AccessRule[] accessRules = new AccessRule[length];
	for (int i = 0; i < length; i++) {
		char[] pattern = readName(in);
		int problemId = in.readInt();
		accessRules[i] = new ClasspathAccessRule(pattern, problemId);
	}
	JavaModelManager manager = JavaModelManager.getJavaModelManager();
	return new AccessRuleSet(accessRules, in.readByte(), manager.intern(in.readUTF()));
}
 
Example #21
Source File: AbstractImageBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void initializeAnnotationProcessorManager(Compiler newCompiler) {
	AbstractAnnotationProcessorManager annotationManager = JavaModelManager.getJavaModelManager().createAnnotationProcessorManager();
	if (annotationManager != null) {
		annotationManager.configureFromPlatform(newCompiler, this, this.javaBuilder.javaProject);
		annotationManager.setErr(new PrintWriter(System.err));
		annotationManager.setOut(new PrintWriter(System.out));
	}
	newCompiler.annotationProcessorManager = annotationManager;
}
 
Example #22
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IFolder createExternalFolder(String folderName) throws CoreException {
		IPath externalFolderPath = new Path(folderName);
		IProject externalFoldersProject = JavaModelManager.getExternalManager().getExternalFoldersProject();
		if (!externalFoldersProject.isAccessible()) {
			if (!externalFoldersProject.exists())
				externalFoldersProject.create(monitor());
			externalFoldersProject.open(monitor());
		}
		IFolder result = externalFoldersProject.getFolder(externalFolderPath);
		result.create(true, false, null);
//		JavaModelManager.getExternalManager().addFolder(result.getFullPath());
		return result;
	}
 
Example #23
Source File: ToolFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create an instance of a code formatter. A code formatter implementation can be contributed via the
 * extension point "org.eclipse.jdt.core.codeFormatter". If unable to find a registered extension, the factory
 * will default to using the default code formatter.
 *
 * @return an instance of a code formatter
 * @see ICodeFormatter
 * @see ToolFactory#createDefaultCodeFormatter(Map)
 * @deprecated The extension point has been deprecated, use {@link #createCodeFormatter(Map)} instead.
 */
public static ICodeFormatter createCodeFormatter(){

		Plugin jdtCorePlugin = JavaCore.getPlugin();
		if (jdtCorePlugin == null) return null;

		IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.FORMATTER_EXTPOINT_ID);
		if (extension != null) {
			IExtension[] extensions =  extension.getExtensions();
			for(int i = 0; i < extensions.length; i++){
				IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
				for(int j = 0; j < configElements.length; j++){
					try {
						Object execExt = configElements[j].createExecutableExtension("class"); //$NON-NLS-1$
						if (execExt instanceof ICodeFormatter){
							// use first contribution found
							return (ICodeFormatter)execExt;
						}
					} catch(CoreException e){
						// unable to instantiate extension, will answer default formatter instead
					}
				}
			}
		}
	// no proper contribution found, use default formatter
	return createDefaultCodeFormatter(null);
}
 
Example #24
Source File: ProjectClasspathFactory.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
protected JavaModel javaModel() {
    return JavaModelManager.getJavaModelManager().getJavaModel();
}
 
Example #25
Source File: JavaSearchNameEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void computeClasspathLocations(IWorkspaceRoot workspaceRoot, JavaProject javaProject) {

	IPackageFragmentRoot[] roots = null;
	try {
		roots = javaProject.getAllPackageFragmentRoots();
	} catch (JavaModelException e) {
		// project doesn't exist
		this.locations = new ClasspathLocation[0];
		return;
	}
	int length = roots.length;
	ClasspathLocation[] cpLocations = new ClasspathLocation[length];
	int index = 0;
	JavaModelManager manager = JavaModelManager.getJavaModelManager();
	for (int i = 0; i < length; i++) {
		PackageFragmentRoot root = (PackageFragmentRoot) roots[i];
		IPath path = root.getPath();
		try {
			if (root.isArchive()) {
				ZipFile zipFile = manager.getZipFile(path);
				cpLocations[index++] = new ClasspathJar(zipFile, ((ClasspathEntry) root.getRawClasspathEntry()).getAccessRuleSet());
			} else {
				Object target = JavaModel.getTarget(path, true);
				if (target == null) {
					// target doesn't exist any longer
					// just resize cpLocations
					System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index);
				} else if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
					cpLocations[index++] = new ClasspathSourceDirectory((IContainer)target, root.fullExclusionPatternChars(), root.fullInclusionPatternChars());
				} else {
					cpLocations[index++] = ClasspathLocation.forBinaryFolder((IContainer) target, false, ((ClasspathEntry) root.getRawClasspathEntry()).getAccessRuleSet());
				}
			}
		} catch (CoreException e1) {
			// problem opening zip file or getting root kind
			// consider root corrupt and ignore
			// just resize cpLocations
			System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index);
		}
	}
	this.locations = cpLocations;
}
 
Example #26
Source File: InternalCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private int getOpenedBinaryTypesThreshold() {
	return JavaModelManager.getJavaModelManager().getOpenableCacheSize() / 10;
}
 
Example #27
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
private ICompilationUnit[] getWorkingCopies() {
	if (ResourceSetContext.get(getResourceSet()).isBuilder()) {
		return new ICompilationUnit[0];
	}
	return JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false/*don't add primary WCs a second time*/);
}
 
Example #28
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public static void deleteExternalFolder(IFolder folder) throws CoreException {
	ResourcesPlugin.getWorkspace().run((monitor)->{
		JavaModelManager.getExternalManager().removeFolder(folder.getFullPath());
		folder.delete(true, null);
	}, monitor());
}
 
Example #29
Source File: InternalBuilderTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
private void clearJdtIndex() throws FileNotFoundException {
	JavaModelManager.getIndexManager().deleteIndexFiles();
	System.out.println("Cleaned up jdt's disk index.");
}
 
Example #30
Source File: InternalBuilderTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
private void dumpMemoryIndex(String message) {
	System.out.println(message + ":\n" + JavaModelManager.getIndexManager().toString());
}