org.eclipse.jdt.internal.core.util.Util Java Examples

The following examples show how to use org.eclipse.jdt.internal.core.util.Util. 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: ClassFile.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 7 votes vote down vote up
private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg, boolean fullyInitialize) throws CoreException, IOException, ClassFormatException {
	JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent();
	ZipFile zip = null;
	try {
		zip = root.getJar();
		String entryName = Util.concatWith(pkg.names, getElementName(), '/');
		ZipEntry ze = zip.getEntry(entryName);
		if (ze != null) {
			byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
			String fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName;
			return new ClassFileReader(contents, fileName.toCharArray(), fullyInitialize);
		}
	} finally {
		JavaModelManager.getJavaModelManager().closeZipFile(zip);
	}
	return null;
}
 
Example #2
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
void verbose_missbehaving_container(IJavaProject project, IPath containerPath, IClasspathEntry[] classpathEntries) {
	Util.verbose(
		"CPContainer GET - missbehaving container (returning null classpath entry)\n" + //$NON-NLS-1$
		"	project: " + project.getElementName() + '\n' + //$NON-NLS-1$
		"	container path: " + containerPath + '\n' + //$NON-NLS-1$
		"	classpath entries: {\n" + //$NON-NLS-1$
		org.eclipse.jdt.internal.compiler.util.Util.toString(
			classpathEntries,
			new org.eclipse.jdt.internal.compiler.util.Util.Displayable(){
				public String displayString(Object o) {
					StringBuffer buffer = new StringBuffer("		"); //$NON-NLS-1$
					if (o == null) {
						buffer.append("<null>"); //$NON-NLS-1$
						return buffer.toString();
					}
					buffer.append(o);
					return buffer.toString();
				}
			}) +
		"\n	}" //$NON-NLS-1$
	);
}
 
Example #3
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void verbose_container_initialization_failed(IJavaProject project, IPath containerPath, IClasspathContainer container, ClasspathContainerInitializer initializer) {
	if (container == CONTAINER_INITIALIZATION_IN_PROGRESS) {
		Util.verbose(
			"CPContainer INIT - FAILED (initializer did not initialize container)\n" + //$NON-NLS-1$
			"	project: " + project.getElementName() + '\n' + //$NON-NLS-1$
			"	container path: " + containerPath + '\n' + //$NON-NLS-1$
			"	initializer: " + initializer); //$NON-NLS-1$

	} else {
		Util.verbose(
			"CPContainer INIT - FAILED (see exception above)\n" + //$NON-NLS-1$
			"	project: " + project.getElementName() + '\n' + //$NON-NLS-1$
			"	container path: " + containerPath + '\n' + //$NON-NLS-1$
			"	initializer: " + initializer); //$NON-NLS-1$
	}
}
 
Example #4
Source File: JobManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public synchronized void request(IJob job) {

		job.ensureReadyToRun();

		// append the job to the list of ones to process later on
		int size = this.awaitingJobs.length;
		if (++this.jobEnd == size) { // when growing, relocate jobs starting at position 0
			this.jobEnd -= this.jobStart; // jobEnd now equals the number of jobs
			if (this.jobEnd < 50 && this.jobEnd < this.jobStart) {
				// plenty of free space in the queue so shift the remaining jobs to the beginning instead of growing it
				System.arraycopy(this.awaitingJobs, this.jobStart, this.awaitingJobs, 0, this.jobEnd);
				for (int i = this.jobStart; i < size; i++)
					this.awaitingJobs[i] = null;
			} else {
				System.arraycopy(this.awaitingJobs, this.jobStart, this.awaitingJobs = new IJob[size * 2], 0, this.jobEnd);
			}
			this.jobStart = 0;
		}
		this.awaitingJobs[this.jobEnd] = job;
		if (VERBOSE) {
			Util.verbose("REQUEST   background job - " + job); //$NON-NLS-1$
			Util.verbose("AWAITING JOBS count: " + awaitingJobsCount()); //$NON-NLS-1$
		}
		notifyAll(); // wake up the background thread if it is waiting
	}
 
Example #5
Source File: PatternSearchJob.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean execute(IProgressMonitor progressMonitor) {
	if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();

	boolean isComplete = COMPLETE;
	this.executionTime = 0;
	Index[] indexes = getIndexes(progressMonitor);
	try {
		int max = indexes.length;
		if (progressMonitor != null)
			progressMonitor.beginTask("", max); //$NON-NLS-1$
		for (int i = 0; i < max; i++) {
			isComplete &= search(indexes[i], progressMonitor);
			if (progressMonitor != null) {
				if (progressMonitor.isCanceled()) throw new OperationCanceledException();
				progressMonitor.worked(1);
			}
		}
		if (JobManager.VERBOSE)
			Util.verbose("-> execution time: " + this.executionTime + "ms - " + this);//$NON-NLS-1$//$NON-NLS-2$
		return isComplete;
	} finally {
		if (progressMonitor != null)
			progressMonitor.done();
	}
}
 
Example #6
Source File: IndexManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void saveIndex(Index index) throws IOException {
	// must have permission to write from the write monitor
	if (index.hasChanged()) {
		if (VERBOSE)
			Util.verbose("-> saving index " + index.getIndexLocation()); //$NON-NLS-1$
		index.save();
	}
	synchronized (this) {
		IPath containerPath = new Path(index.containerPath);
		if (this.jobEnd > this.jobStart) {
			for (int i = this.jobEnd; i > this.jobStart; i--) { // skip the current job
				IJob job = this.awaitingJobs[i];
				if (job instanceof IndexRequest)
					if (((IndexRequest) job).containerPath.equals(containerPath)) return;
			}
		}
		IndexLocation indexLocation = computeIndexLocation(containerPath);
		updateIndexState(indexLocation, SAVED_STATE);
	}
}
 
Example #7
Source File: PackageFragmentRoot.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compute the package fragment children of this package fragment root.
 *
 * @exception JavaModelException  The resource associated with this package fragment root does not exist
 */
protected boolean computeChildren(OpenableElementInfo info, IResource underlyingResource) throws JavaModelException {
	// Note the children are not opened (so not added to newElements) for a regular package fragment root
	// However they are opened for a Jar package fragment root (see JarPackageFragmentRoot#computeChildren)
	try {
		// the underlying resource may be a folder or a project (in the case that the project folder
		// is actually the package fragment root)
		if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) {
			ArrayList vChildren = new ArrayList(5);
			IContainer rootFolder = (IContainer) underlyingResource;
			char[][] inclusionPatterns = fullInclusionPatternChars();
			char[][] exclusionPatterns = fullExclusionPatternChars();
			computeFolderChildren(rootFolder, !Util.isExcluded(rootFolder, inclusionPatterns, exclusionPatterns), CharOperation.NO_STRINGS, vChildren, inclusionPatterns, exclusionPatterns);
			IJavaElement[] children = new IJavaElement[vChildren.size()];
			vChildren.toArray(children);
			info.setChildren(children);
		}
	} catch (JavaModelException e) {
		//problem resolving children; structure remains unknown
		info.setChildren(new IJavaElement[]{});
		throw e;
	}
	return true;
}
 
Example #8
Source File: IndexManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private char[][] readIndexState(String dirOSString) {
	try {
		char[] savedIndexNames = org.eclipse.jdt.internal.compiler.util.Util.getFileCharContent(this.savedIndexNamesFile, null);
		if (savedIndexNames.length > 0) {
			char[][] names = CharOperation.splitOn('\n', savedIndexNames);
			if (names.length > 1) {
				// First line is DiskIndex signature + saved plugin working location (see writeSavedIndexNamesFile())
				String savedSignature = DiskIndex.SIGNATURE + "+" + dirOSString; //$NON-NLS-1$
				if (savedSignature.equals(new String(names[0])))
					return names;
			}
		}
	} catch (IOException ignored) {
		if (VERBOSE)
			Util.verbose("Failed to read saved index file names"); //$NON-NLS-1$
	}
	return null;
}
 
Example #9
Source File: IndexManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void readParticipantsIndexNamesFile() {
	SimpleLookupTable containers = new SimpleLookupTable(3);
	try {
		char[] participantIndexNames = org.eclipse.jdt.internal.compiler.util.Util.getFileCharContent(this.participantIndexNamesFile, null);
		if (participantIndexNames.length > 0) {
			char[][] names = CharOperation.splitOn('\n', participantIndexNames);
			if (names.length >= 3) {
				// First line is DiskIndex signature  (see writeParticipantsIndexNamesFile())
				if (DiskIndex.SIGNATURE.equals(new String(names[0]))) {					
					for (int i = 1, l = names.length-1 ; i < l ; i+=2) {
						IndexLocation indexLocation = new FileIndexLocation(new File(new String(names[i])), true);
						containers.put(indexLocation, new Path(new String(names[i+1])));
					}
				}				
			}
		}	
	} catch (IOException ignored) {
		if (VERBOSE)
			Util.verbose("Failed to read participant index file names"); //$NON-NLS-1$
	}
	this.participantsContainers = containers;
	return;
}
 
Example #10
Source File: IndexManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized void removeIndexesState(IndexLocation[] locations) {
	getIndexStates(); // ensure the states are initialized
	int length = locations.length;
	boolean changed = false;
	for (int i=0; i<length; i++) {
		if (locations[i] == null) continue;
		if ((this.indexStates.removeKey(locations[i]) != null)) {
			changed = true;
			if (VERBOSE) {
				Util.verbose("-> index state updated to: ? for: "+locations[i]); //$NON-NLS-1$
			}
		}
	}
	if (!changed) return;

	writeSavedIndexNamesFile();
	writeIndexMapFile();
}
 
Example #11
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void verbose_reentering_project_container_access(	IPath containerPath, IJavaProject project, IClasspathContainer previousContainer) {
	StringBuffer buffer = new StringBuffer();
	buffer.append("CPContainer INIT - reentering access to project container during its initialization, will see previous value\n"); //$NON-NLS-1$
	buffer.append("	project: " + project.getElementName() + '\n'); //$NON-NLS-1$
	buffer.append("	container path: " + containerPath + '\n'); //$NON-NLS-1$
	buffer.append("	previous value: "); //$NON-NLS-1$
	buffer.append(previousContainer.getDescription());
	buffer.append(" {\n"); //$NON-NLS-1$
	IClasspathEntry[] entries = previousContainer.getClasspathEntries();
	if (entries != null){
		for (int j = 0; j < entries.length; j++){
			buffer.append(" 		"); //$NON-NLS-1$
			buffer.append(entries[j]);
			buffer.append('\n');
		}
	}
	buffer.append(" 	}"); //$NON-NLS-1$
	Util.verbose(buffer.toString());
	new Exception("<Fake exception>").printStackTrace(System.out); //$NON-NLS-1$
}
 
Example #12
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Record a shared persistent property onto a project.
 * Note that it is orthogonal to IResource persistent properties, and client code has to decide
 * which form of storage to use appropriately. Shared properties produce real resource files which
 * can be shared through a VCM onto a server. Persistent properties are not shareable.
 * <p>
 * Shared properties end up in resource files, and thus cannot be modified during
 * delta notifications (a CoreException would then be thrown).
 *
 * @param key String
 * @param value String
 * @see JavaProject#getSharedProperty(String key)
 * @throws CoreException
 */
public void setSharedProperty(String key, String value) throws CoreException {

	IFile rscFile = this.project.getFile(key);
	byte[] bytes = null;
	try {
		bytes = value.getBytes(org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
	} catch (UnsupportedEncodingException e) {
		Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$
		// fallback to default
		bytes = value.getBytes();
	}
	InputStream inputStream = new ByteArrayInputStream(bytes);
	// update the resource content
	if (rscFile.exists()) {
		if (rscFile.isReadOnly()) {
			// provide opportunity to checkout read-only .classpath file (23984)
			ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, IWorkspace.VALIDATE_PROMPT);
		}
		rscFile.setContents(inputStream, IResource.FORCE, null);
	} else {
		rscFile.create(inputStream, IResource.FORCE, null);
	}
}
 
Example #13
Source File: FieldPattern.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public FieldPattern(
	char[] name,
	char[] declaringQualification,
	char[] declaringSimpleName,
	char[] typeQualification,
	char[] typeSimpleName,
	String typeSignature,
	int limitTo,
	int matchRule) {

	this(name, declaringQualification, declaringSimpleName, typeQualification, typeSimpleName, limitTo, matchRule);

	// store type signatures and arguments
	if (typeSignature != null) {
		this.typeSignatures = Util.splitTypeLevelsSignature(typeSignature);
		setTypeArguments(Util.getAllTypeArguments(this.typeSignatures));
	}
}
 
Example #14
Source File: ExternalFoldersManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void refreshReferences(IProject source, IProgressMonitor monitor) {
	IProject externalProject = getExternalFoldersProject();
	if (source.equals(externalProject))
		return;
	if (!JavaProject.hasJavaNature(source))
		return;
	try {
		HashSet externalFolders = getExternalFolders(((JavaProject) JavaCore.create(source)).getResolvedClasspath());
		if (externalFolders == null)
			return;
		
		runRefreshJob(externalFolders);
	} catch (CoreException e) {
		Util.log(e, "Exception while refreshing external project"); //$NON-NLS-1$
	}
	return;
}
 
Example #15
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private int sortParticipants(ArrayList group, IConfigurationElement[] configElements, int index) {
	int size = group.size();
	if (size == 0) return index;
	Object[] elements = group.toArray();
	Util.sort(elements, new Util.Comparer() {
		public int compare(Object a, Object b) {
			if (a == b) return 0;
			String id = ((IConfigurationElement) a).getAttribute("id"); //$NON-NLS-1$
			if (id == null) return -1;
			IConfigurationElement[] requiredElements = ((IConfigurationElement) b).getChildren("requires"); //$NON-NLS-1$
			for (int i = 0, length = requiredElements.length; i < length; i++) {
				IConfigurationElement required = requiredElements[i];
				if (id.equals(required.getAttribute("id"))) //$NON-NLS-1$
					return 1;
			}
			return -1;
		}
	});
	for (int i = 0; i < size; i++)
		configElements[index+i] = (IConfigurationElement) elements[i];
	return index + size;
}
 
Example #16
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isOnClasspathEntry(IPath elementPath, boolean isFolderPath, boolean isPackageFragmentRoot, IClasspathEntry entry) {
	IPath entryPath = entry.getPath();
	if (isPackageFragmentRoot) {
		// package fragment roots must match exactly entry pathes (no exclusion there)
		if (entryPath.equals(elementPath))
			return true;
	} else {
		if (entryPath.isPrefixOf(elementPath)
				&& !Util.isExcluded(elementPath, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), isFolderPath))
			return true;
	}
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=276373
	if (entryPath.isAbsolute()
			&& entryPath.equals(ResourcesPlugin.getWorkspace().getRoot().getLocation().append(elementPath))) {
		return true;
	}
	return false;
}
 
Example #17
Source File: DeltaProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void notifyTypeHierarchies(IElementChangedListener[] listeners, int listenerCount) {
	for (int i= 0; i < listenerCount; i++) {
		final IElementChangedListener listener = listeners[i];
		if (!(listener instanceof TypeHierarchy)) continue;

		// wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
		SafeRunner.run(new ISafeRunnable() {
			public void handleException(Throwable exception) {
				Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$
			}
			public void run() throws Exception {
				TypeHierarchy typeHierarchy = (TypeHierarchy)listener;
				if (typeHierarchy.hasFineGrainChanges()) {
					// case of changes in primary working copies
					typeHierarchy.needsRefresh = true;
					typeHierarchy.fireChange();
				}
			}
		});
	}
}
 
Example #18
Source File: NameLookup.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ICompilationUnit findCompilationUnit(String[] pkgName, String cuName, PackageFragmentRoot root) {
		if (!root.isArchive()) {
			IPackageFragment pkg = root.getPackageFragment(pkgName);
			try {
				ICompilationUnit[] cus = pkg.getCompilationUnits();
				for (int j = 0, length = cus.length; j < length; j++) {
					ICompilationUnit cu = cus[j];
					if (Util.equalsIgnoreJavaLikeExtension(cu.getElementName(), cuName))
						return cu;
				}
			} catch (JavaModelException e) {
				// pkg does not exist
				// -> try next package
			}
		}
		return null;
}
 
Example #19
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void contentTypeChanged(ContentTypeChangeEvent event) {
	Util.resetJavaLikeExtensions();

	// Walk through projects to reset their secondary types cache
	IJavaProject[] projects;
	try {
		projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects();
	} catch (JavaModelException e) {
		return;
	}
	for (int i = 0, length = projects.length; i < length; i++) {
		IJavaProject project = projects[i];
		final PerProjectInfo projectInfo = getPerProjectInfo(project.getProject(), false /* don't create info */);
		if (projectInfo != null) {
			projectInfo.secondaryTypes = null;
		}
	}
}
 
Example #20
Source File: BasicSearchEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Searches for all declarations of the types referenced in the given element.
 * The element can be a compilation unit or a source type/method/field.
 * Reports the type declarations using the given requestor.
 *
 * @see SearchEngine#searchDeclarationsOfReferencedTypes(IJavaElement, SearchRequestor, IProgressMonitor)
 * 	for detailed comment
 */
public void searchDeclarationsOfReferencedTypes(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
	if (VERBOSE) {
		Util.verbose("BasicSearchEngine.searchDeclarationsOfReferencedTypes(IJavaElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$
	}
	// Do not accept other kind of element type than those specified in the spec
	switch (enclosingElement.getElementType()) {
		case IJavaElement.FIELD:
		case IJavaElement.METHOD:
		case IJavaElement.TYPE:
		case IJavaElement.COMPILATION_UNIT:
			// valid element type
			break;
		default:
			throw new IllegalArgumentException();
	}
	SearchPattern pattern = new DeclarationOfReferencedTypesPattern(enclosingElement);
	searchDeclarations(enclosingElement, requestor, pattern, monitor);
}
 
Example #21
Source File: CompilationUnit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected IStatus validateCompilationUnit(IResource resource) {
	IPackageFragmentRoot root = getPackageFragmentRoot();
	// root never null as validation is not done for working copies
	try {
		if (root.getKind() != IPackageFragmentRoot.K_SOURCE)
			return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, root);
	} catch (JavaModelException e) {
		return e.getJavaModelStatus();
	}
	if (resource != null) {
		char[][] inclusionPatterns = ((PackageFragmentRoot)root).fullInclusionPatternChars();
		char[][] exclusionPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars();
		if (Util.isExcluded(resource, inclusionPatterns, exclusionPatterns))
			return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this);
		if (!resource.isAccessible())
			return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this);
	}
	IJavaProject project = getJavaProject();
	return JavaConventions.validateCompilationUnitName(getElementName(),project.getOption(JavaCore.COMPILER_SOURCE, true), project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
}
 
Example #22
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void verbose_container_value_after_initialization(IJavaProject project, IPath containerPath, IClasspathContainer container) {
	StringBuffer buffer = new StringBuffer();
	buffer.append("CPContainer INIT - after resolution\n"); //$NON-NLS-1$
	buffer.append("	project: " + project.getElementName() + '\n'); //$NON-NLS-1$
	buffer.append("	container path: " + containerPath + '\n'); //$NON-NLS-1$
	if (container != null){
		buffer.append("	container: "+container.getDescription()+" {\n"); //$NON-NLS-2$//$NON-NLS-1$
		IClasspathEntry[] entries = container.getClasspathEntries();
		if (entries != null){
			for (int i = 0; i < entries.length; i++) {
				buffer.append("		" + entries[i] + '\n'); //$NON-NLS-1$
			}
		}
		buffer.append("	}");//$NON-NLS-1$
	} else {
		buffer.append("	container: {unbound}");//$NON-NLS-1$
	}
	Util.verbose(buffer.toString());
}
 
Example #23
Source File: CopyResourceElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void saveContent(PackageFragment dest, String destName, TextEdit edits, String sourceEncoding, IFile destFile) throws JavaModelException {
	try {
		// TODO (frederic) remove when bug 67606 will be fixed (bug 67823)
		// fix bug 66898
		if (sourceEncoding != null) destFile.setCharset(sourceEncoding, this.progressMonitor);
		// end todo
	}
	catch (CoreException ce) {
		// use no encoding
	}
	// when the file was copied, its read-only flag was preserved -> temporary set it to false
	// note this doesn't interfere with repository providers as this is a new resource that cannot be under
	// version control yet
	Util.setReadOnly(destFile, false);
	ICompilationUnit destCU = dest.getCompilationUnit(destName);
	applyTextEdit(destCU, edits);
	destCU.save(getSubProgressMonitor(1), this.force);
}
 
Example #24
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isOnClasspath(IResource resource) {
	IPath exactPath = resource.getFullPath();
	IPath path = exactPath;

	// ensure that folders are only excluded if all of their children are excluded
	int resourceType = resource.getType();
	boolean isFolderPath = resourceType == IResource.FOLDER || resourceType == IResource.PROJECT;

	IClasspathEntry[] classpath;
	try {
		classpath = this.getResolvedClasspath();
	} catch(JavaModelException e){
		return false; // not a Java project
	}
	for (int i = 0; i < classpath.length; i++) {
		IClasspathEntry entry = classpath[i];
		IPath entryPath = entry.getPath();
		if (entryPath.equals(exactPath)) { // package fragment roots must match exactly entry pathes (no exclusion there)
			return true;
		}
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=276373
		// When a classpath entry is absolute, convert the resource's relative path to a file system path and compare
		// e.g - /P/lib/variableLib.jar and /home/P/lib/variableLib.jar when compared should return true
		if (entryPath.isAbsolute()
				&& entryPath.equals(ResourcesPlugin.getWorkspace().getRoot().getLocation().append(exactPath))) {
			return true;
		}
		if (entryPath.isPrefixOf(path)
				&& !Util.isExcluded(path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), isFolderPath)) {
			return true;
		}
	}
	return false;
}
 
Example #25
Source File: IndexManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean hasJavaLikeNamesChanged() {
	char[][] currentNames = Util.getJavaLikeExtensions();
	int current = currentNames.length;
	char[][] prevNames = readJavaLikeNamesFile();
	if (prevNames == null) {
		if (VERBOSE && current != 1)
			Util.verbose("No Java like names found and there is atleast one non-default javaLikeName", System.err); //$NON-NLS-1$
		return (current != 1); //Ignore if only java
	}
	int prev = prevNames.length;
	if (current != prev) {
		if (VERBOSE)
			Util.verbose("Java like names have changed", System.err); //$NON-NLS-1$
		return true;
	}
	if (current > 1) {
		// Sort the current java like names. 
		// Copy the array to avoid modifying the Util static variable
		System.arraycopy(currentNames, 0, currentNames = new char[current][], 0, current);
		Util.sort(currentNames);
	}
	
	// The JavaLikeNames would have been sorted before getting stored in the file,
	// hence just do a direct compare.
	for (int i = 0; i < current; i++) {
		if (!CharOperation.equals(currentNames[i],prevNames[i])) {
			if (VERBOSE)
				Util.verbose("Java like names have changed", System.err); //$NON-NLS-1$
			return true;
		}
	}
	return false;
}
 
Example #26
Source File: SourceMethod.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.eclipse.jdt.internal.core.JavaElement#hashCode()
 */
public int hashCode() {
   int hash = super.hashCode();
	for (int i = 0, length = this.parameterTypes.length; i < length; i++) {
	    hash = Util.combineHashCodes(hash, this.parameterTypes[i].hashCode());
	}
	return hash;
}
 
Example #27
Source File: JobManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Stop background processing, and wait until the current job is completed before returning
 */
public void shutdown() {

	if (VERBOSE)
		Util.verbose("Shutdown"); //$NON-NLS-1$

	disable();
	discardJobs(null); // will wait until current executing job has completed
	Thread thread = this.processingThread;
	try {
		if (thread != null) { // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=31858
			synchronized (this) {
				this.processingThread = null; // mark the job manager as shutting down so that the thread will stop by itself
				notifyAll(); // ensure its awake so it can be shutdown
			}
			// in case processing thread is handling a job
			thread.join();
		}
		Job job = this.progressJob;
		if (job != null) {
			job.cancel();
			job.join();
		}
	} catch (InterruptedException e) {
		// ignore
	}
}
 
Example #28
Source File: DOMImport.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
 */
protected void appendFragmentedContents(CharArrayBuffer buffer) {
	if (this.fNameRange[0] < 0) {
		buffer
			.append("import ") //$NON-NLS-1$
			.append(this.fName)
			.append(';')
			.append(Util.getLineSeparator(buffer.toString(), null));
	} else {
		buffer.append(this.fDocument, this.fSourceRange[0], this.fNameRange[0] - this.fSourceRange[0]);
		//buffer.append(fDocument, fNameRange[0], fNameRange[1] - fNameRange[0] + 1);
		buffer.append(this.fName);
		buffer.append(this.fDocument, this.fNameRange[1] + 1, this.fSourceRange[1] - this.fNameRange[1]);
	}
}
 
Example #29
Source File: BinaryTypeConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Convert a binary type into an AST type declaration and put it in the given compilation unit.
 */
public TypeDeclaration buildTypeDeclaration(IType type, CompilationUnitDeclaration compilationUnit)  throws JavaModelException {
	PackageFragment pkg = (PackageFragment) type.getPackageFragment();
	char[][] packageName = Util.toCharArrays(pkg.names);

	if (packageName.length > 0) {
		compilationUnit.currentPackage = new ImportReference(packageName, new long[]{0}, false, ClassFileConstants.AccDefault);
	}

	/* convert type */
	TypeDeclaration typeDeclaration = convert(type, null, null);

	IType alreadyComputedMember = type;
	IType parent = type.getDeclaringType();
	TypeDeclaration previousDeclaration = typeDeclaration;
	while(parent != null) {
		TypeDeclaration declaration = convert(parent, alreadyComputedMember, previousDeclaration);

		alreadyComputedMember = parent;
		previousDeclaration = declaration;
		parent = parent.getDeclaringType();
	}

	compilationUnit.types = new TypeDeclaration[]{previousDeclaration};

	return typeDeclaration;
}
 
Example #30
Source File: DOMCompilationUnit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see IDOMCompilationUnit#getName()
 */
public String getName() {
	IDOMType topLevelType= null;
	IDOMType firstType= null;
	IDOMNode child= this.fFirstChild;
	while (child != null) {
		if (child.getNodeType() == IDOMNode.TYPE) {
			IDOMType type= (IDOMType)child;
			if (firstType == null) {
				firstType= type;
			}
			if (Flags.isPublic(type.getFlags())) {
				topLevelType= type;
				break;
			}
		}
		child= child.getNextNode();
	}
	if (topLevelType == null) {
		topLevelType= firstType;
	}
	if (topLevelType != null) {
		return topLevelType.getName() + Util.defaultJavaExtension();
	} else {
		return null;
	}
}