1 /*******************************************************************************
2 * Copyright (c) 2000, 2003 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.internal.core;
13 import java.io.BufferedInputStream;
14 import java.io.BufferedOutputStream;
15 import java.io.DataInputStream;
16 import java.io.DataOutputStream;
18 import java.io.FileInputStream;
19 import java.io.FileOutputStream;
20 import java.io.IOException;
21 import java.text.NumberFormat;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
28 import java.util.WeakHashMap;
29 import java.util.zip.ZipFile;
31 import net.sourceforge.phpdt.core.ElementChangedEvent;
32 import net.sourceforge.phpdt.core.IClasspathEntry;
33 import net.sourceforge.phpdt.core.ICompilationUnit;
34 import net.sourceforge.phpdt.core.IElementChangedListener;
35 import net.sourceforge.phpdt.core.IJavaElement;
36 import net.sourceforge.phpdt.core.IJavaElementDelta;
37 import net.sourceforge.phpdt.core.IJavaModel;
38 import net.sourceforge.phpdt.core.IJavaProject;
39 import net.sourceforge.phpdt.core.IPackageFragment;
40 import net.sourceforge.phpdt.core.IPackageFragmentRoot;
41 import net.sourceforge.phpdt.core.IWorkingCopy;
42 import net.sourceforge.phpdt.core.JavaModelException;
43 import net.sourceforge.phpdt.core.JavaCore;
44 import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
45 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
46 import net.sourceforge.phpdt.internal.core.builder.PHPBuilder;
47 import net.sourceforge.phpdt.internal.core.util.Util;
49 import org.eclipse.core.resources.IFile;
50 import org.eclipse.core.resources.IFolder;
51 import org.eclipse.core.resources.IProject;
52 import org.eclipse.core.resources.IResource;
53 import org.eclipse.core.resources.IResourceDelta;
54 import org.eclipse.core.resources.ISaveContext;
55 import org.eclipse.core.resources.ISaveParticipant;
56 import org.eclipse.core.resources.IWorkspace;
57 import org.eclipse.core.resources.IWorkspaceDescription;
58 import org.eclipse.core.resources.IWorkspaceRoot;
59 import org.eclipse.core.resources.ResourcesPlugin;
60 import org.eclipse.core.runtime.CoreException;
61 import org.eclipse.core.runtime.IPath;
62 import org.eclipse.core.runtime.IProgressMonitor;
63 import org.eclipse.core.runtime.ISafeRunnable;
64 import org.eclipse.core.runtime.IStatus;
65 import org.eclipse.core.runtime.MultiStatus;
66 import org.eclipse.core.runtime.Path;
67 import org.eclipse.core.runtime.Platform;
68 import org.eclipse.core.runtime.Plugin;
69 import org.eclipse.core.runtime.Preferences;
70 import org.eclipse.core.runtime.Status;
72 import net.sourceforge.phpdt.internal.core.DefaultWorkingCopyOwner;
74 import net.sourceforge.phpdt.internal.core.DeltaProcessingState;
76 import net.sourceforge.phpdt.internal.core.DeltaProcessor;
78 import net.sourceforge.phpdt.core.IParent;
79 import net.sourceforge.phpdt.internal.core.JavaElementInfo;
81 import net.sourceforge.phpdt.core.IProblemRequestor;
82 import net.sourceforge.phpdt.core.WorkingCopyOwner;
83 import net.sourceforge.phpdt.core.compiler.IProblem;
84 import net.sourceforge.phpdt.internal.core.CompilationUnit;
85 import net.sourceforge.phpdt.internal.core.JavaElement;
86 import net.sourceforge.phpdt.internal.core.JavaElementDeltaBuilder;
87 import net.sourceforge.phpdt.internal.core.JavaModelManager.PerWorkingCopyInfo;
90 * The <code>JavaModelManager</code> manages instances of <code>IJavaModel</code>.
91 * <code>IElementChangedListener</code>s register with the <code>JavaModelManager</code>,
92 * and receive <code>ElementChangedEvent</code>s for all <code>IJavaModel</code>s.
94 * The single instance of <code>JavaModelManager</code> is available from
95 * the static method <code>JavaModelManager.getJavaModelManager()</code>.
97 public class JavaModelManager implements ISaveParticipant {
100 * Unique handle onto the JavaModel
102 final JavaModel javaModel = new JavaModel();
105 * Classpath variables pool
107 public static HashMap Variables = new HashMap(5);
108 public static HashMap PreviousSessionVariables = new HashMap(5);
109 public static HashSet OptionNames = new HashSet(20);
110 public final static String CP_VARIABLE_PREFERENCES_PREFIX = PHPeclipsePlugin.PLUGIN_ID+".classpathVariable."; //$NON-NLS-1$
111 // public final static String CP_CONTAINER_PREFERENCES_PREFIX = PHPCore.PLUGIN_ID+".classpathContainer."; //$NON-NLS-1$
112 public final static String CP_ENTRY_IGNORE = "##<cp entry ignore>##"; //$NON-NLS-1$
115 * Classpath containers pool
117 public static HashMap Containers = new HashMap(5);
118 public static HashMap PreviousSessionContainers = new HashMap(5);
121 * Name of the extension point for contributing classpath variable initializers
123 // public static final String CPVARIABLE_INITIALIZER_EXTPOINT_ID = "classpathVariableInitializer" ; //$NON-NLS-1$
126 * Name of the extension point for contributing classpath container initializers
128 // public static final String CPCONTAINER_INITIALIZER_EXTPOINT_ID = "classpathContainerInitializer" ; //$NON-NLS-1$
131 * Name of the extension point for contributing a source code formatter
133 public static final String FORMATTER_EXTPOINT_ID = "codeFormatter" ; //$NON-NLS-1$
136 * Special value used for recognizing ongoing initialization and breaking initialization cycles
138 public final static IPath VariableInitializationInProgress = new Path("Variable Initialization In Progress"); //$NON-NLS-1$
139 // public final static IClasspathContainer ContainerInitializationInProgress = new IClasspathContainer() {
140 // public IClasspathEntry[] getClasspathEntries() { return null; }
141 // public String getDescription() { return "Container Initialization In Progress"; } //$NON-NLS-1$
142 // public int getKind() { return 0; }
143 // public IPath getPath() { return null; }
144 // public String toString() { return getDescription(); }
147 private static final String INDEX_MANAGER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/indexmanager" ; //$NON-NLS-1$
148 private static final String COMPILER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/compiler" ; //$NON-NLS-1$
149 private static final String JAVAMODEL_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/javamodel" ; //$NON-NLS-1$
150 private static final String CP_RESOLVE_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/cpresolution" ; //$NON-NLS-1$
151 private static final String ZIP_ACCESS_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/zipaccess" ; //$NON-NLS-1$
152 private static final String DELTA_DEBUG =PHPeclipsePlugin.PLUGIN_ID + "/debug/javadelta" ; //$NON-NLS-1$
153 private static final String HIERARCHY_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/hierarchy" ; //$NON-NLS-1$
154 private static final String POST_ACTION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/postaction" ; //$NON-NLS-1$
155 private static final String BUILDER_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/builder" ; //$NON-NLS-1$
156 private static final String COMPLETION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/completion" ; //$NON-NLS-1$
157 private static final String SELECTION_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/selection" ; //$NON-NLS-1$
158 private static final String SHARED_WC_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/sharedworkingcopy" ; //$NON-NLS-1$
159 private static final String SEARCH_DEBUG = PHPeclipsePlugin.PLUGIN_ID + "/debug/search" ; //$NON-NLS-1$
161 public final static IWorkingCopy[] NoWorkingCopy = new IWorkingCopy[0];
164 * Table from WorkingCopyOwner to a table of ICompilationUnit (working copy handle) to PerWorkingCopyInfo.
165 * NOTE: this object itself is used as a lock to synchronize creation/removal of per working copy infos
167 protected Map perWorkingCopyInfos = new HashMap(5);
169 * Returns whether the given full path (for a package) conflicts with the output location
170 * of the given project.
172 public static boolean conflictsWithOutputLocation(IPath folderPath, JavaProject project) {
174 IPath outputLocation = project.getOutputLocation();
175 if (outputLocation == null) {
176 // in doubt, there is a conflict
179 if (outputLocation.isPrefixOf(folderPath)) {
180 // only allow nesting in project's output if there is a corresponding source folder
181 // or if the project's output is not used (in other words, if all source folders have their custom output)
182 IClasspathEntry[] classpath = project.getResolvedClasspath(true);
183 boolean isOutputUsed = false;
184 for (int i = 0, length = classpath.length; i < length; i++) {
185 IClasspathEntry entry = classpath[i];
186 if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
187 if (entry.getPath().equals(outputLocation)) {
190 if (entry.getOutputLocation() == null) {
198 } catch (JavaModelException e) {
199 // in doubt, there is a conflict
204 // public static IClasspathContainer containerGet(IJavaProject project, IPath containerPath) {
205 // Map projectContainers = (Map)Containers.get(project);
206 // if (projectContainers == null){
209 // IClasspathContainer container = (IClasspathContainer)projectContainers.get(containerPath);
213 // public static void containerPut(IJavaProject project, IPath containerPath, IClasspathContainer container){
215 // Map projectContainers = (Map)Containers.get(project);
216 // if (projectContainers == null){
217 // projectContainers = new HashMap(1);
218 // Containers.put(project, projectContainers);
221 // if (container == null) {
222 // projectContainers.remove(containerPath);
223 // Map previousContainers = (Map)PreviousSessionContainers.get(project);
224 // if (previousContainers != null){
225 // previousContainers.remove(containerPath);
228 // projectContainers.put(containerPath, container);
231 // // do not write out intermediate initialization value
232 // if (container == JavaModelManager.ContainerInitializationInProgress) {
235 // Preferences preferences = PHPeclipsePlugin.getPlugin().getPluginPreferences();
236 // String containerKey = CP_CONTAINER_PREFERENCES_PREFIX+project.getElementName() +"|"+containerPath;//$NON-NLS-1$
237 // String containerString = CP_ENTRY_IGNORE;
239 // if (container != null) {
240 // containerString = ((JavaProject)project).encodeClasspath(container.getClasspathEntries(), null, false);
242 // } catch(JavaModelException e){
244 // preferences.setDefault(containerKey, CP_ENTRY_IGNORE); // use this default to get rid of removed ones
245 // preferences.setValue(containerKey, containerString);
246 // PHPeclipsePlugin.getPlugin().savePluginPreferences();
250 * Returns the Java element corresponding to the given resource, or
251 * <code>null</code> if unable to associate the given resource
252 * with a Java element.
254 * The resource must be one of:<ul>
255 * <li>a project - the element returned is the corresponding <code>IJavaProject</code></li>
256 * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
257 * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
258 * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
259 * <li>a folder - the element returned is the corresponding <code>IPackageFragmentRoot</code>
260 * or <code>IPackageFragment</code></li>
261 * <li>the workspace root resource - the element returned is the <code>IJavaModel</code></li>
264 * Creating a Java element has the side effect of creating and opening all of the
265 * element's parents if they are not yet open.
267 public static IJavaElement create(IResource resource, IJavaProject project) {
268 if (resource == null) {
271 int type = resource.getType();
273 case IResource.PROJECT :
274 return JavaCore.create((IProject) resource);
275 case IResource.FILE :
276 return create((IFile) resource, project);
277 case IResource.FOLDER :
278 return create((IFolder) resource, project);
279 case IResource.ROOT :
280 return JavaCore.create((IWorkspaceRoot) resource);
287 * Returns the Java element corresponding to the given file, its project being the given
289 * Returns <code>null</code> if unable to associate the given file
290 * with a Java element.
292 * <p>The file must be one of:<ul>
293 * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
294 * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
295 * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
298 * Creating a Java element has the side effect of creating and opening all of the
299 * element's parents if they are not yet open.
301 public static IJavaElement create(IFile file, IJavaProject project) {
305 if (project == null) {
306 project = JavaCore.create(file.getProject());
309 if (file.getFileExtension() != null) {
310 String name = file.getName();
311 if (PHPFileUtil.isValidPHPUnitName(name))
312 //if (PHPFileUtil.isPHPFile(file))
313 return createCompilationUnitFrom(file, project);
314 // if (Util.isValidClassFileName(name))
315 // return createClassFileFrom(file, project);
316 // if (Util.isArchiveFileName(name))
317 // return createJarPackageFragmentRootFrom(file, project);
323 * Returns the package fragment or package fragment root corresponding to the given folder,
324 * its parent or great parent being the given project.
325 * or <code>null</code> if unable to associate the given folder with a Java element.
327 * Note that a package fragment root is returned rather than a default package.
329 * Creating a Java element has the side effect of creating and opening all of the
330 * element's parents if they are not yet open.
332 public static IJavaElement create(IFolder folder, IJavaProject project) {
333 if (folder == null) {
336 if (project == null) {
337 project = JavaCore.create(folder.getProject());
339 IJavaElement element = determineIfOnClasspath(folder, project);
340 if (conflictsWithOutputLocation(folder.getFullPath(), (JavaProject)project)
341 || (folder.getName().indexOf('.') >= 0
342 && !(element instanceof IPackageFragmentRoot))) {
343 return null; // only package fragment roots are allowed with dot names
350 * Creates and returns a class file element for the given <code>.class</code> file,
351 * its project being the given project. Returns <code>null</code> if unable
352 * to recognize the class file.
354 // public static IClassFile createClassFileFrom(IFile file, IJavaProject project ) {
355 // if (file == null) {
358 // if (project == null) {
359 // project = PHPCore.create(file.getProject());
361 // IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
362 // if (pkg == null) {
363 // // fix for 1FVS7WE
364 // // not on classpath - make the root its folder, and a default package
365 // IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent());
366 // pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
368 // return pkg.getClassFile(file.getName());
372 * Creates and returns a compilation unit element for the given <code>.java</code>
373 * file, its project being the given project. Returns <code>null</code> if unable
374 * to recognize the compilation unit.
376 public static ICompilationUnit createCompilationUnitFrom(IFile file, IJavaProject project) {
378 if (file == null) return null;
380 if (project == null) {
381 project = JavaCore.create(file.getProject());
383 IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
385 // not on classpath - make the root its folder, and a default package
386 IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent());
387 pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
390 System.out.println("WARNING : creating unit element outside classpath ("+ Thread.currentThread()+"): " + file.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$
393 return pkg.getCompilationUnit(file.getName());
396 * Creates and returns a handle for the given JAR file, its project being the given project.
397 * The Java model associated with the JAR's project may be
398 * created as a side effect.
399 * Returns <code>null</code> if unable to create a JAR package fragment root.
400 * (for example, if the JAR file represents a non-Java resource)
402 // public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file, IJavaProject project) {
403 // if (file == null) {
406 // if (project == null) {
407 // project = PHPCore.create(file.getProject());
410 // // Create a jar package fragment root only if on the classpath
411 // IPath resourcePath = file.getFullPath();
413 // IClasspathEntry[] entries = ((JavaProject)project).getResolvedClasspath(true);
414 // for (int i = 0, length = entries.length; i < length; i++) {
415 // IClasspathEntry entry = entries[i];
416 // IPath rootPath = entry.getPath();
417 // if (rootPath.equals(resourcePath)) {
418 // return project.getPackageFragmentRoot(file);
421 // } catch (JavaModelException e) {
427 * Returns the package fragment root represented by the resource, or
428 * the package fragment the given resource is located in, or <code>null</code>
429 * if the given resource is not on the classpath of the given project.
431 public static IJavaElement determineIfOnClasspath(
433 IJavaProject project) {
435 IPath resourcePath = resource.getFullPath();
437 IClasspathEntry[] entries =
438 net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(resourcePath.lastSegment())
439 ? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path)
440 : ((JavaProject)project).getResolvedClasspath(true);
442 for (int i = 0; i < entries.length; i++) {
443 IClasspathEntry entry = entries[i];
444 if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue;
445 IPath rootPath = entry.getPath();
446 if (rootPath.equals(resourcePath)) {
447 return project.getPackageFragmentRoot(resource);
448 } else if (rootPath.isPrefixOf(resourcePath) && !Util.isExcluded(resource, ((ClasspathEntry)entry).fullExclusionPatternChars())) {
449 // given we have a resource child of the root, it cannot be a JAR pkg root
450 IPackageFragmentRoot root = ((JavaProject) project).getFolderPackageFragmentRoot(rootPath);
451 if (root == null) return null;
452 IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());
453 if (resource.getType() == IResource.FILE) {
454 // if the resource is a file, then remove the last segment which
455 // is the file name in the package
456 pkgPath = pkgPath.removeLastSegments(1);
458 // don't check validity of package name (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=26706)
459 // String pkgName = pkgPath.toString().replace('/', '.');
460 String pkgName = pkgPath.toString();
461 return root.getPackageFragment(pkgName);
463 String pkgName = Util.packageName(pkgPath);
464 if (pkgName == null){// || JavaConventions.validatePackageName(pkgName).getSeverity() == IStatus.ERROR) {
467 return root.getPackageFragment(pkgName);
471 } catch (JavaModelException npe) {
478 * The singleton manager
480 private final static JavaModelManager Manager= new JavaModelManager();
485 protected JavaModelCache cache = new JavaModelCache();
488 * Temporary cache of newly opened elements
490 private ThreadLocal temporaryCache = new ThreadLocal();
492 * Set of elements which are out of sync with their buffers.
494 protected Map elementsOutOfSynchWithBuffers = new HashMap(11);
496 * Holds the state used for delta processing.
498 public DeltaProcessingState deltaState = new DeltaProcessingState();
500 * Turns delta firing on/off. By default it is on.
502 private boolean isFiring= true;
505 * Queue of deltas created explicily by the Java Model that
506 * have yet to be fired.
508 ArrayList javaModelDeltas= new ArrayList();
510 * Queue of reconcile deltas on working copies that have yet to be fired.
511 * This is a table form IWorkingCopy to IJavaElementDelta
513 HashMap reconcileDeltas = new HashMap();
517 * Collection of listeners for Java element deltas
519 private IElementChangedListener[] elementChangedListeners = new IElementChangedListener[5];
520 private int[] elementChangedListenerMasks = new int[5];
521 private int elementChangedListenerCount = 0;
522 public int currentChangeEventType = ElementChangedEvent.PRE_AUTO_BUILD;
523 public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with ElementChangedEvent event masks
528 * Used to convert <code>IResourceDelta</code>s into <code>IJavaElementDelta</code>s.
530 // public final DeltaProcessor deltaProcessor = new DeltaProcessor(this);
532 * Used to update the JavaModel for <code>IJavaElementDelta</code>s.
534 // private final ModelUpdater modelUpdater =new ModelUpdater();
536 * Workaround for bug 15168 circular errors not reported
537 * This is a cache of the projects before any project addition/deletion has started.
539 public IJavaProject[] javaProjectsCache;
542 * Table from IProject to PerProjectInfo.
543 * NOTE: this object itself is used as a lock to synchronize creation/removal of per project infos
545 protected Map perProjectInfo = new HashMap(5);
548 * A map from ICompilationUnit to IWorkingCopy
549 * of the shared working copies.
551 public Map sharedWorkingCopies = new HashMap();
554 * A weak set of the known scopes.
556 protected WeakHashMap scopes = new WeakHashMap();
558 public static class PerProjectInfo {
559 public IProject project;
560 public Object savedState;
561 public boolean triedRead;
562 public IClasspathEntry[] classpath;
563 public IClasspathEntry[] lastResolvedClasspath;
564 public Map resolvedPathToRawEntries; // reverse map from resolved path to raw entries
565 public IPath outputLocation;
566 public Preferences preferences;
567 public PerProjectInfo(IProject project) {
569 this.triedRead = false;
570 this.savedState = null;
571 this.project = project;
574 public static class PerWorkingCopyInfo implements IProblemRequestor {
576 IProblemRequestor problemRequestor;
577 ICompilationUnit workingCopy;
578 public PerWorkingCopyInfo(ICompilationUnit workingCopy, IProblemRequestor problemRequestor) {
579 this.workingCopy = workingCopy;
580 this.problemRequestor = problemRequestor;
582 public void acceptProblem(IProblem problem) {
583 if (this.problemRequestor == null) return;
584 this.problemRequestor.acceptProblem(problem);
586 public void beginReporting() {
587 if (this.problemRequestor == null) return;
588 this.problemRequestor.beginReporting();
590 public void endReporting() {
591 if (this.problemRequestor == null) return;
592 this.problemRequestor.endReporting();
594 public ICompilationUnit getWorkingCopy() {
595 return this.workingCopy;
597 public boolean isActive() {
598 return this.problemRequestor != null && this.problemRequestor.isActive();
600 public String toString() {
601 StringBuffer buffer = new StringBuffer();
602 buffer.append("Info for "); //$NON-NLS-1$
603 buffer.append(((JavaElement)workingCopy).toStringWithAncestors());
604 buffer.append("\nUse count = "); //$NON-NLS-1$
605 buffer.append(this.useCount);
606 buffer.append("\nProblem requestor:\n "); //$NON-NLS-1$
607 buffer.append(this.problemRequestor);
608 return buffer.toString();
611 public static boolean VERBOSE = false;
612 public static boolean CP_RESOLVE_VERBOSE = false;
613 public static boolean ZIP_ACCESS_VERBOSE = false;
616 * A cache of opened zip files per thread.
617 * (map from Thread to map of IPath to java.io.ZipFile)
618 * NOTE: this object itself is used as a lock to synchronize creation/removal of entries
620 private HashMap zipFiles = new HashMap();
624 * Update the classpath variable cache
626 public static class PluginPreferencesListener implements Preferences.IPropertyChangeListener {
628 * @see org.eclipse.core.runtime.Preferences.IPropertyChangeListener#propertyChange(PropertyChangeEvent)
630 public void propertyChange(Preferences.PropertyChangeEvent event) {
631 // TODO : jsurfer temp-del
632 // String propertyName = event.getProperty();
633 // if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)) {
634 // String varName = propertyName.substring(CP_VARIABLE_PREFERENCES_PREFIX.length());
635 // String newValue = (String)event.getNewValue();
636 // if (newValue != null && !(newValue = newValue.trim()).equals(CP_ENTRY_IGNORE)) {
637 // Variables.put(varName, new Path(newValue));
639 // Variables.remove(varName);
642 // if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)) {
643 // recreatePersistedContainer(propertyName, (String)event.getNewValue(), false);
649 * Line separator to use throughout the JavaModel for any source edit operation
651 public static String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
653 * Constructs a new JavaModelManager
655 private JavaModelManager() {
659 * @deprecated - discard once debug has converted to not using it
661 public void addElementChangedListener(IElementChangedListener listener) {
662 this.addElementChangedListener(listener, ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE);
665 * addElementChangedListener method comment.
666 * Need to clone defensively the listener information, in case some listener is reacting to some notification iteration by adding/changing/removing
667 * any of the other (for example, if it deregisters itself).
669 public void addElementChangedListener(IElementChangedListener listener, int eventMask) {
670 for (int i = 0; i < this.elementChangedListenerCount; i++){
671 if (this.elementChangedListeners[i].equals(listener)){
673 // only clone the masks, since we could be in the middle of notifications and one listener decide to change
674 // any event mask of another listeners (yet not notified).
675 int cloneLength = this.elementChangedListenerMasks.length;
676 System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[cloneLength], 0, cloneLength);
677 this.elementChangedListenerMasks[i] = eventMask; // could be different
681 // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end.
683 if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount){
684 System.arraycopy(this.elementChangedListeners, 0, this.elementChangedListeners = new IElementChangedListener[length*2], 0, length);
685 System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[length*2], 0, length);
687 this.elementChangedListeners[this.elementChangedListenerCount] = listener;
688 this.elementChangedListenerMasks[this.elementChangedListenerCount] = eventMask;
689 this.elementChangedListenerCount++;
693 * Starts caching ZipFiles.
694 * Ignores if there are already clients.
696 public void cacheZipFiles() {
697 synchronized(this.zipFiles) {
698 Thread currentThread = Thread.currentThread();
699 if (this.zipFiles.get(currentThread) != null) return;
700 this.zipFiles.put(currentThread, new HashMap());
703 public void closeZipFile(ZipFile zipFile) {
704 if (zipFile == null) return;
705 synchronized(this.zipFiles) {
706 if (this.zipFiles.get(Thread.currentThread()) != null) {
707 return; // zip file will be closed by call to flushZipFiles
710 if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
711 System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.closeZipFile(ZipFile)] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$
714 } catch (IOException e) {
722 * Configure the plugin with respect to option settings defined in ".options" file
724 public void configurePluginDebugOptions(){
725 if(JavaCore.getPlugin().isDebugging()){
726 // TODO jsurfer temp-del
728 String option = Platform.getDebugOption(BUILDER_DEBUG);
729 // if(option != null) JavaBuilder.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
731 // option = Platform.getDebugOption(COMPILER_DEBUG);
732 // if(option != null) Compiler.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
734 // option = Platform.getDebugOption(COMPLETION_DEBUG);
735 // if(option != null) CompletionEngine.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
737 option = Platform.getDebugOption(CP_RESOLVE_DEBUG);
738 if(option != null) JavaModelManager.CP_RESOLVE_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
740 option = Platform.getDebugOption(DELTA_DEBUG);
741 if(option != null) DeltaProcessor.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
743 // option = Platform.getDebugOption(HIERARCHY_DEBUG);
744 // if(option != null) TypeHierarchy.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
746 // option = Platform.getDebugOption(INDEX_MANAGER_DEBUG);
747 // if(option != null) IndexManager.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
749 option = Platform.getDebugOption(JAVAMODEL_DEBUG);
750 if(option != null) JavaModelManager.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
752 option = Platform.getDebugOption(POST_ACTION_DEBUG);
753 if(option != null) JavaModelOperation.POST_ACTION_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
755 // option = Platform.getDebugOption(SEARCH_DEBUG);
756 // if(option != null) SearchEngine.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
758 // option = Platform.getDebugOption(SELECTION_DEBUG);
759 // if(option != null) SelectionEngine.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
761 option = Platform.getDebugOption(ZIP_ACCESS_DEBUG);
762 if(option != null) JavaModelManager.ZIP_ACCESS_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
768 * Discards the per working copy info for the given working copy (making it a compilation unit)
769 * if its use count was 1. Otherwise, just decrement the use count.
770 * If the working copy is primary, computes the delta between its state and the original compilation unit
772 * Close the working copy, its buffer and remove it from the shared working copy table.
773 * Ignore if no per-working copy info existed.
774 * NOTE: it must be synchronized as it may interact with the element info cache (if useCount is decremented to 0), see bug 50667.
775 * Returns the new use count (or -1 if it didn't exist).
777 public synchronized int discardPerWorkingCopyInfo(CompilationUnit workingCopy) throws JavaModelException {
778 synchronized(perWorkingCopyInfos) {
779 WorkingCopyOwner owner = workingCopy.owner;
780 Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
781 if (workingCopyToInfos == null) return -1;
783 PerWorkingCopyInfo info = (PerWorkingCopyInfo)workingCopyToInfos.get(workingCopy);
784 if (info == null) return -1;
786 if (--info.useCount == 0) {
787 // create the delta builder (this remembers the current content of the working copy)
788 JavaElementDeltaBuilder deltaBuilder = null;
789 if (workingCopy.isPrimary()) {
790 deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
793 // remove per working copy info
794 workingCopyToInfos.remove(workingCopy);
795 if (workingCopyToInfos.isEmpty()) {
796 this.perWorkingCopyInfos.remove(owner);
799 // remove infos + close buffer (since no longer working copy)
800 removeInfoAndChildren(workingCopy);
801 workingCopy.closeBuffer();
803 // compute the delta if needed and register it if there are changes
804 if (deltaBuilder != null) {
805 deltaBuilder.buildDeltas();
806 if ((deltaBuilder.delta != null) && (deltaBuilder.delta.getAffectedChildren().length > 0)) {
807 getDeltaProcessor().registerJavaModelDelta(deltaBuilder.delta);
812 return info.useCount;
817 * @see ISaveParticipant
819 public void doneSaving(ISaveContext context){
823 * Fire Java Model delta, flushing them after the fact after post_change notification.
824 * If the firing mode has been turned off, this has no effect.
826 public void fire(IJavaElementDelta customDelta, int eventType) {
828 if (!this.isFiring) return;
830 if (DeltaProcessor.VERBOSE && (eventType == DEFAULT_CHANGE_EVENT || eventType == ElementChangedEvent.PRE_AUTO_BUILD)) {
831 System.out.println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$
834 IJavaElementDelta deltaToNotify;
835 if (customDelta == null){
836 deltaToNotify = this.mergeDeltas(this.javaModelDeltas);
838 deltaToNotify = customDelta;
841 // Refresh internal scopes
842 if (deltaToNotify != null) {
843 // TODO khartlage temp-del
844 // Iterator scopes = this.scopes.keySet().iterator();
845 // while (scopes.hasNext()) {
846 // AbstractSearchScope scope = (AbstractSearchScope)scopes.next();
847 // scope.processDelta(deltaToNotify);
853 // Important: if any listener reacts to notification by updating the listeners list or mask, these lists will
854 // be duplicated, so it is necessary to remember original lists in a variable (since field values may change under us)
855 IElementChangedListener[] listeners = this.elementChangedListeners;
856 int[] listenerMask = this.elementChangedListenerMasks;
857 int listenerCount = this.elementChangedListenerCount;
860 case DEFAULT_CHANGE_EVENT:
861 firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, listenerCount);
862 firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
863 fireReconcileDelta(listeners, listenerMask, listenerCount);
865 case ElementChangedEvent.PRE_AUTO_BUILD:
866 firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, listenerCount);
868 case ElementChangedEvent.POST_CHANGE:
869 firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
870 fireReconcileDelta(listeners, listenerMask, listenerCount);
876 private void firePreAutoBuildDelta(
877 IJavaElementDelta deltaToNotify,
878 IElementChangedListener[] listeners,
882 if (DeltaProcessor.VERBOSE){
883 System.out.println("FIRING PRE_AUTO_BUILD Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
884 System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
886 if (deltaToNotify != null) {
887 notifyListeners(deltaToNotify, ElementChangedEvent.PRE_AUTO_BUILD, listeners, listenerMask, listenerCount);
891 private void firePostChangeDelta(
892 IJavaElementDelta deltaToNotify,
893 IElementChangedListener[] listeners,
897 // post change deltas
898 if (DeltaProcessor.VERBOSE){
899 System.out.println("FIRING POST_CHANGE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
900 System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
902 if (deltaToNotify != null) {
903 // flush now so as to keep listener reactions to post their own deltas for subsequent iteration
906 notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, listeners, listenerMask, listenerCount);
909 private void fireReconcileDelta(
910 IElementChangedListener[] listeners,
915 IJavaElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas.values());
916 if (DeltaProcessor.VERBOSE){
917 System.out.println("FIRING POST_RECONCILE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
918 System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
920 if (deltaToNotify != null) {
921 // flush now so as to keep listener reactions to post their own deltas for subsequent iteration
922 this.reconcileDeltas = new HashMap();
924 notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, listeners, listenerMask, listenerCount);
928 public void notifyListeners(IJavaElementDelta deltaToNotify, int eventType, IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {
929 final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType);
930 for (int i= 0; i < listenerCount; i++) {
931 if ((listenerMask[i] & eventType) != 0){
932 final IElementChangedListener listener = listeners[i];
934 if (DeltaProcessor.VERBOSE) {
935 System.out.print("Listener #" + (i+1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$
936 start = System.currentTimeMillis();
938 // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
939 Platform.run(new ISafeRunnable() {
940 public void handleException(Throwable exception) {
941 Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$
943 public void run() throws Exception {
944 listener.elementChanged(extraEvent);
947 if (DeltaProcessor.VERBOSE) {
948 System.out.println(" -> " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
955 * Flushes all deltas without firing them.
957 protected void flush() {
958 this.javaModelDeltas = new ArrayList();
962 * Flushes ZipFiles cache if there are no more clients.
964 public void flushZipFiles() {
965 synchronized(this.zipFiles) {
966 Thread currentThread = Thread.currentThread();
967 HashMap map = (HashMap)this.zipFiles.remove(currentThread);
968 if (map == null) return;
969 Iterator iterator = map.values().iterator();
970 while (iterator.hasNext()) {
972 ZipFile zipFile = (ZipFile)iterator.next();
973 if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
974 System.out.println("(" + currentThread + ") [JavaModelManager.flushZipFiles()] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$//$NON-NLS-2$
977 } catch (IOException e) {
984 public DeltaProcessor getDeltaProcessor() {
985 return this.deltaState.getDeltaProcessor();
988 * Returns the set of elements which are out of synch with their buffers.
990 protected Map getElementsOutOfSynchWithBuffers() {
991 return this.elementsOutOfSynchWithBuffers;
995 * Returns the <code>IJavaElement</code> represented by the
996 * <code>String</code> memento.
998 public IJavaElement getHandleFromMemento(String memento) throws JavaModelException {
999 if (memento == null) {
1002 JavaModel model= (JavaModel) getJavaModel();
1003 if (memento.equals("")){ // workspace memento //$NON-NLS-1$
1006 int modelEnd= memento.indexOf(JavaElement.JEM_JAVAPROJECT);
1007 if (modelEnd == -1) {
1010 boolean returnProject= false;
1011 int projectEnd= memento.indexOf(JavaElement.JEM_PACKAGEFRAGMENTROOT, modelEnd);
1012 if (projectEnd == -1) {
1013 projectEnd= memento.length();
1014 returnProject= true;
1016 String projectName= memento.substring(modelEnd + 1, projectEnd);
1017 JavaProject proj= (JavaProject) model.getJavaProject(projectName);
1018 if (returnProject) {
1021 int rootEnd= memento.indexOf(JavaElement.JEM_PACKAGEFRAGMENT, projectEnd + 1);
1022 // TODO khartlage temp-del
1023 // if (rootEnd == -1) {
1024 // return model.getHandleFromMementoForRoot(memento, proj, projectEnd, memento.length());
1026 // IPackageFragmentRoot root = model.getHandleFromMementoForRoot(memento, proj, projectEnd, rootEnd);
1027 // if (root == null)
1030 // int end= memento.indexOf(JavaElement.JEM_COMPILATIONUNIT, rootEnd);
1032 // end= memento.indexOf(JavaElement.JEM_CLASSFILE, rootEnd);
1034 // if (rootEnd + 1 == memento.length()) {
1035 // return root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
1037 // return root.getPackageFragment(memento.substring(rootEnd + 1));
1040 // //deal with class file and binary members
1041 // return model.getHandleFromMementoForBinaryMembers(memento, root, rootEnd, end);
1044 // //deal with compilation units and source members
1045 // return model.getHandleFromMementoForSourceMembers(memento, root, rootEnd, end);
1048 // public IndexManager getIndexManager() {
1049 // return this.deltaProcessor.indexManager;
1053 * Returns the info for the element.
1055 public Object getInfo(IJavaElement element) {
1056 return this.cache.getInfo(element);
1060 * Returns the handle to the active Java Model.
1062 public final JavaModel getJavaModel() {
1067 * Returns the singleton JavaModelManager
1069 public final static JavaModelManager getJavaModelManager() {
1074 * Returns the last built state for the given project, or null if there is none.
1075 * Deserializes the state if necessary.
1077 * For use by image builder and evaluation support only
1079 public Object getLastBuiltState(IProject project, IProgressMonitor monitor) {
1080 if (!JavaProject.hasJavaNature(project)) return null; // should never be requested on non-Java projects
1081 PerProjectInfo info = getPerProjectInfo(project, true/*create if missing*/);
1082 if (!info.triedRead) {
1083 info.triedRead = true;
1085 if (monitor != null)
1086 monitor.subTask(Util.bind("build.readStateProgress", project.getName())); //$NON-NLS-1$
1087 info.savedState = readState(project);
1088 } catch (CoreException e) {
1089 e.printStackTrace();
1092 return info.savedState;
1096 * Returns the per-project info for the given project. If specified, create the info if the info doesn't exist.
1098 public PerProjectInfo getPerProjectInfo(IProject project, boolean create) {
1099 synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock
1100 PerProjectInfo info= (PerProjectInfo) perProjectInfo.get(project);
1101 if (info == null && create) {
1102 info= new PerProjectInfo(project);
1103 perProjectInfo.put(project, info);
1110 * Returns the per-project info for the given project.
1111 * If the info doesn't exist, check for the project existence and create the info.
1112 * @throws JavaModelException if the project doesn't exist.
1114 public PerProjectInfo getPerProjectInfoCheckExistence(IProject project) throws JavaModelException {
1115 JavaModelManager.PerProjectInfo info = getPerProjectInfo(project, false /* don't create info */);
1117 if (!JavaProject.hasJavaNature(project)) {
1118 throw ((JavaProject)JavaCore.create(project)).newNotPresentException();
1120 info = getPerProjectInfo(project, true /* create info */);
1125 * Returns the per-working copy info for the given working copy at the given path.
1126 * If it doesn't exist and if create, add a new per-working copy info with the given problem requestor.
1127 * If recordUsage, increment the per-working copy info's use count.
1128 * Returns null if it doesn't exist and not create.
1130 public PerWorkingCopyInfo getPerWorkingCopyInfo(CompilationUnit workingCopy,boolean create, boolean recordUsage, IProblemRequestor problemRequestor) {
1131 synchronized(perWorkingCopyInfos) { // use the perWorkingCopyInfo collection as its own lock
1132 WorkingCopyOwner owner = workingCopy.owner;
1133 Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
1134 if (workingCopyToInfos == null && create) {
1135 workingCopyToInfos = new HashMap();
1136 this.perWorkingCopyInfos.put(owner, workingCopyToInfos);
1139 PerWorkingCopyInfo info = workingCopyToInfos == null ? null : (PerWorkingCopyInfo) workingCopyToInfos.get(workingCopy);
1140 if (info == null && create) {
1141 info= new PerWorkingCopyInfo(workingCopy, problemRequestor);
1142 workingCopyToInfos.put(workingCopy, info);
1144 if (info != null && recordUsage) info.useCount++;
1149 * Returns the name of the variables for which an CP variable initializer is registered through an extension point
1151 public static String[] getRegisteredVariableNames(){
1153 Plugin jdtCorePlugin = JavaCore.getPlugin();
1154 if (jdtCorePlugin == null) return null;
1156 ArrayList variableList = new ArrayList(5);
1157 // IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID);
1158 // if (extension != null) {
1159 // IExtension[] extensions = extension.getExtensions();
1160 // for(int i = 0; i < extensions.length; i++){
1161 // IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
1162 // for(int j = 0; j < configElements.length; j++){
1163 // String varAttribute = configElements[j].getAttribute("variable"); //$NON-NLS-1$
1164 // if (varAttribute != null) variableList.add(varAttribute);
1168 String[] variableNames = new String[variableList.size()];
1169 variableList.toArray(variableNames);
1170 return variableNames;
1174 * Returns the name of the container IDs for which an CP container initializer is registered through an extension point
1176 // public static String[] getRegisteredContainerIDs(){
1178 // Plugin jdtCorePlugin = PHPCore.getPlugin();
1179 // if (jdtCorePlugin == null) return null;
1181 // ArrayList containerIDList = new ArrayList(5);
1182 // IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID);
1183 // if (extension != null) {
1184 // IExtension[] extensions = extension.getExtensions();
1185 // for(int i = 0; i < extensions.length; i++){
1186 // IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
1187 // for(int j = 0; j < configElements.length; j++){
1188 // String idAttribute = configElements[j].getAttribute("id"); //$NON-NLS-1$
1189 // if (idAttribute != null) containerIDList.add(idAttribute);
1193 // String[] containerIDs = new String[containerIDList.size()];
1194 // containerIDList.toArray(containerIDs);
1195 // return containerIDs;
1199 * Returns the File to use for saving and restoring the last built state for the given project.
1201 private File getSerializationFile(IProject project) {
1202 if (!project.exists()) return null;
1203 IPath workingLocation = project.getWorkingLocation(JavaCore.PLUGIN_ID);
1204 return workingLocation.append("state.dat").toFile(); //$NON-NLS-1$
1207 * Returns the temporary cache for newly opened elements for the current thread.
1208 * Creates it if not already created.
1210 public HashMap getTemporaryCache() {
1211 HashMap result = (HashMap)this.temporaryCache.get();
1212 if (result == null) {
1213 result = new HashMap();
1214 this.temporaryCache.set(result);
1219 * Returns the open ZipFile at the given location. If the ZipFile
1220 * does not yet exist, it is created, opened, and added to the cache
1221 * of open ZipFiles. The location must be a absolute path.
1223 * @exception CoreException If unable to create/open the ZipFile
1225 public ZipFile getZipFile(IPath path) throws CoreException {
1227 synchronized(this.zipFiles) { // TODO: use PeThreadObject which does synchronization
1228 Thread currentThread = Thread.currentThread();
1231 if ((map = (HashMap)this.zipFiles.get(currentThread)) != null
1232 && (zipFile = (ZipFile)map.get(path)) != null) {
1236 String fileSystemPath= null;
1237 IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
1238 IResource file = root.findMember(path);
1239 if (path.isAbsolute() && file != null) {
1240 if (file == null) { // external file
1241 fileSystemPath= path.toOSString();
1242 } else { // internal resource (not an IFile or not existing)
1244 if (file.getType() != IResource.FILE || (location = file.getLocation()) == null) {
1245 throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
1247 fileSystemPath= location.toOSString();
1249 } else if (!path.isAbsolute()) {
1250 file= root.getFile(path);
1251 if (file == null || file.getType() != IResource.FILE) {
1252 throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
1254 IPath location = file.getLocation();
1255 if (location == null) {
1256 throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
1258 fileSystemPath= location.toOSString();
1260 fileSystemPath= path.toOSString();
1264 if (ZIP_ACCESS_VERBOSE) {
1265 System.out.println("(" + currentThread + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + fileSystemPath ); //$NON-NLS-1$ //$NON-NLS-2$
1267 zipFile = new ZipFile(fileSystemPath);
1269 map.put(path, zipFile);
1272 } catch (IOException e) {
1273 throw new CoreException(new Status(Status.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("status.IOException"), e)); //$NON-NLS-1$
1278 * Returns whether there is a temporary cache for the current thread.
1280 public boolean hasTemporaryCache() {
1281 return this.temporaryCache.get() != null;
1283 // public void loadVariablesAndContainers() throws CoreException {
1285 // // backward compatibility, consider persistent property
1286 // QualifiedName qName = new QualifiedName(PHPCore.PLUGIN_ID, "variables"); //$NON-NLS-1$
1287 // String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName);
1290 // if (xmlString != null){
1291 // StringReader reader = new StringReader(xmlString);
1292 // Element cpElement;
1294 // DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
1295 // cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
1296 // } catch(SAXException e) {
1298 // } catch(ParserConfigurationException e){
1303 // if (cpElement == null) return;
1304 // if (!cpElement.getNodeName().equalsIgnoreCase("variables")) { //$NON-NLS-1$
1308 // NodeList list= cpElement.getChildNodes();
1309 // int length= list.getLength();
1310 // for (int i= 0; i < length; ++i) {
1311 // Node node= list.item(i);
1312 // short type= node.getNodeType();
1313 // if (type == Node.ELEMENT_NODE) {
1314 // Element element= (Element) node;
1315 // if (element.getNodeName().equalsIgnoreCase("variable")) { //$NON-NLS-1$
1317 // element.getAttribute("name"), //$NON-NLS-1$
1318 // new Path(element.getAttribute("path"))); //$NON-NLS-1$
1323 // } catch(IOException e){
1325 // if (xmlString != null){
1326 // ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one
1331 // // load variables and containers from preferences into cache
1332 // Preferences preferences = PHPCore.getPlugin().getPluginPreferences();
1334 // // only get variable from preferences not set to their default
1335 // String[] propertyNames = preferences.propertyNames();
1336 // int variablePrefixLength = CP_VARIABLE_PREFERENCES_PREFIX.length();
1337 // for (int i = 0; i < propertyNames.length; i++){
1338 // String propertyName = propertyNames[i];
1339 // if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)){
1340 // String varName = propertyName.substring(variablePrefixLength);
1341 // IPath varPath = new Path(preferences.getString(propertyName).trim());
1343 // Variables.put(varName, varPath);
1344 // PreviousSessionVariables.put(varName, varPath);
1346 // if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)){
1347 // recreatePersistedContainer(propertyName, preferences.getString(propertyName), true/*add to container values*/);
1350 // // override persisted values for variables which have a registered initializer
1351 // String[] registeredVariables = getRegisteredVariableNames();
1352 // for (int i = 0; i < registeredVariables.length; i++) {
1353 // String varName = registeredVariables[i];
1354 // Variables.put(varName, null); // reset variable, but leave its entry in the Map, so it will be part of variable names.
1356 // // override persisted values for containers which have a registered initializer
1357 // String[] registeredContainerIDs = getRegisteredContainerIDs();
1358 // for (int i = 0; i < registeredContainerIDs.length; i++) {
1359 // String containerID = registeredContainerIDs[i];
1360 // Iterator projectIterator = Containers.keySet().iterator();
1361 // while (projectIterator.hasNext()){
1362 // IJavaProject project = (IJavaProject)projectIterator.next();
1363 // Map projectContainers = (Map)Containers.get(project);
1364 // if (projectContainers != null){
1365 // Iterator containerIterator = projectContainers.keySet().iterator();
1366 // while (containerIterator.hasNext()){
1367 // IPath containerPath = (IPath)containerIterator.next();
1368 // if (containerPath.segment(0).equals(containerID)) { // registered container
1369 // projectContainers.put(containerPath, null); // reset container value, but leave entry in Map
1378 * Merged all awaiting deltas.
1380 public IJavaElementDelta mergeDeltas(Collection deltas) {
1381 if (deltas.size() == 0) return null;
1382 if (deltas.size() == 1) return (IJavaElementDelta)deltas.iterator().next();
1384 if (DeltaProcessor.VERBOSE) {
1385 System.out.println("MERGING " + deltas.size() + " DELTAS ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1388 Iterator iterator = deltas.iterator();
1389 IJavaElement javaModel = this.getJavaModel();
1390 JavaElementDelta rootDelta = new JavaElementDelta(javaModel);
1391 boolean insertedTree = false;
1392 while (iterator.hasNext()) {
1393 JavaElementDelta delta = (JavaElementDelta)iterator.next();
1394 if (DeltaProcessor.VERBOSE) {
1395 System.out.println(delta.toString());
1397 IJavaElement element = delta.getElement();
1398 if (javaModel.equals(element)) {
1399 IJavaElementDelta[] children = delta.getAffectedChildren();
1400 for (int j = 0; j < children.length; j++) {
1401 JavaElementDelta projectDelta = (JavaElementDelta) children[j];
1402 rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta);
1403 insertedTree = true;
1405 IResourceDelta[] resourceDeltas = delta.getResourceDeltas();
1406 if (resourceDeltas != null) {
1407 for (int i = 0, length = resourceDeltas.length; i < length; i++) {
1408 rootDelta.addResourceDelta(resourceDeltas[i]);
1409 insertedTree = true;
1413 rootDelta.insertDeltaTree(element, delta);
1414 insertedTree = true;
1426 * Returns the info for this element without
1427 * disturbing the cache ordering.
1428 */ // TODO: should be synchronized, could answer unitialized info or if cache is in middle of rehash, could even answer distinct element info
1429 protected Object peekAtInfo(IJavaElement element) {
1430 return this.cache.peekAtInfo(element);
1434 * @see ISaveParticipant
1436 public void prepareToSave(ISaveContext context) throws CoreException {
1439 protected void putInfo(IJavaElement element, Object info) {
1440 this.cache.putInfo(element, info);
1443 * Puts the infos in the given map (keys are IJavaElements and values are JavaElementInfos)
1444 * in the Java model cache in an atomic way.
1445 * First checks that the info for the opened element (or one of its ancestors) has not been
1446 * added to the cache. If it is the case, another thread has opened the element (or one of
1447 * its ancestors). So returns without updating the cache.
1449 protected synchronized void putInfos(IJavaElement openedElement, Map newElements) {
1451 Object existingInfo = this.cache.peekAtInfo(openedElement);
1452 if (openedElement instanceof IParent && existingInfo instanceof JavaElementInfo) {
1453 IJavaElement[] children = ((JavaElementInfo)existingInfo).getChildren();
1454 for (int i = 0, size = children.length; i < size; ++i) {
1455 JavaElement child = (JavaElement) children[i];
1458 } catch (JavaModelException e) {
1464 Iterator iterator = newElements.keySet().iterator();
1465 while (iterator.hasNext()) {
1466 IJavaElement element = (IJavaElement)iterator.next();
1467 Object info = newElements.get(element);
1468 this.cache.putInfo(element, info);
1472 * Reads the build state for the relevant project.
1474 protected Object readState(IProject project) throws CoreException {
1475 File file = getSerializationFile(project);
1476 if (file != null && file.exists()) {
1478 DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
1480 String pluginID= in.readUTF();
1481 if (!pluginID.equals(JavaCore.PLUGIN_ID))
1482 throw new IOException(Util.bind("build.wrongFileFormat")); //$NON-NLS-1$
1483 String kind= in.readUTF();
1484 if (!kind.equals("STATE")) //$NON-NLS-1$
1485 throw new IOException(Util.bind("build.wrongFileFormat")); //$NON-NLS-1$
1486 if (in.readBoolean())
1487 return PHPBuilder.readState(project, in);
1488 if (PHPBuilder.DEBUG)
1489 System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$
1493 } catch (Exception e) {
1494 e.printStackTrace();
1495 throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$
1501 // public static void recreatePersistedContainer(String propertyName, String containerString, boolean addToContainerValues) {
1502 // int containerPrefixLength = CP_CONTAINER_PREFERENCES_PREFIX.length();
1503 // int index = propertyName.indexOf('|', containerPrefixLength);
1504 // if (containerString != null) containerString = containerString.trim();
1506 // final String projectName = propertyName.substring(containerPrefixLength, index).trim();
1507 // JavaProject project = (JavaProject)getJavaModelManager().getJavaModel().getJavaProject(projectName);
1508 // final IPath containerPath = new Path(propertyName.substring(index+1).trim());
1510 // if (containerString == null || containerString.equals(CP_ENTRY_IGNORE)) {
1511 // containerPut(project, containerPath, null);
1513 // final IClasspathEntry[] containerEntries = project.decodeClasspath(containerString, false, false);
1514 // if (containerEntries != null && containerEntries != JavaProject.INVALID_CLASSPATH) {
1515 // IClasspathContainer container = new IClasspathContainer() {
1516 // public IClasspathEntry[] getClasspathEntries() {
1517 // return containerEntries;
1519 // public String getDescription() {
1520 // return "Persisted container ["+containerPath+" for project ["+ projectName+"]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
1522 // public int getKind() {
1525 // public IPath getPath() {
1526 // return containerPath;
1528 // public String toString() {
1529 // return getDescription();
1533 // if (addToContainerValues) {
1534 // containerPut(project, containerPath, container);
1536 // Map projectContainers = (Map)PreviousSessionContainers.get(project);
1537 // if (projectContainers == null){
1538 // projectContainers = new HashMap(1);
1539 // PreviousSessionContainers.put(project, projectContainers);
1541 // projectContainers.put(containerPath, container);
1548 * Registers the given delta with this manager.
1550 protected void registerJavaModelDelta(IJavaElementDelta delta) {
1551 this.javaModelDeltas.add(delta);
1555 * Remembers the given scope in a weak set
1556 * (so no need to remove it: it will be removed by the garbage collector)
1558 // public void rememberScope(AbstractSearchScope scope) {
1559 // // NB: The value has to be null so as to not create a strong reference on the scope
1560 // this.scopes.put(scope, null);
1564 * removeElementChangedListener method comment.
1566 public void removeElementChangedListener(IElementChangedListener listener) {
1568 for (int i = 0; i < this.elementChangedListenerCount; i++){
1570 if (this.elementChangedListeners[i].equals(listener)){
1572 // need to clone defensively since we might be in the middle of listener notifications (#fire)
1573 int length = this.elementChangedListeners.length;
1574 IElementChangedListener[] newListeners = new IElementChangedListener[length];
1575 System.arraycopy(this.elementChangedListeners, 0, newListeners, 0, i);
1576 int[] newMasks = new int[length];
1577 System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, 0, i);
1579 // copy trailing listeners
1580 int trailingLength = this.elementChangedListenerCount - i - 1;
1581 if (trailingLength > 0){
1582 System.arraycopy(this.elementChangedListeners, i+1, newListeners, i, trailingLength);
1583 System.arraycopy(this.elementChangedListenerMasks, i+1, newMasks, i, trailingLength);
1586 // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto
1587 // the original ones)
1588 this.elementChangedListeners = newListeners;
1589 this.elementChangedListenerMasks = newMasks;
1590 this.elementChangedListenerCount--;
1596 // PROTECTED VOID REMOVEINFO(IJAVAELEMENT ELEMENT) {
1597 // THIS.CACHE.REMOVEINFO(ELEMENT);
1600 * Removes all cached info for the given element (including all children)
1602 * Returns the info for the given element, or null if it was closed.
1604 public synchronized Object removeInfoAndChildren(JavaElement element) throws JavaModelException {
1605 Object info = this.cache.peekAtInfo(element);
1607 boolean wasVerbose = false;
1610 System.out.println("CLOSING Element ("+ Thread.currentThread()+"): " + element.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
1614 element.closing(info);
1615 if (element instanceof IParent && info instanceof JavaElementInfo) {
1616 IJavaElement[] children = ((JavaElementInfo)info).getChildren();
1617 for (int i = 0, size = children.length; i < size; ++i) {
1618 JavaElement child = (JavaElement) children[i];
1622 this.cache.removeInfo(element);
1624 System.out.println("-> Package cache size = " + this.cache.pkgSize()); //$NON-NLS-1$
1625 System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(this.cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
1628 JavaModelManager.VERBOSE = wasVerbose;
1634 public void removePerProjectInfo(JavaProject javaProject) {
1635 synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock
1636 IProject project = javaProject.getProject();
1637 PerProjectInfo info= (PerProjectInfo) perProjectInfo.get(project);
1639 perProjectInfo.remove(project);
1644 * Resets the temporary cache for newly created elements to null.
1646 public void resetTemporaryCache() {
1647 this.temporaryCache.set(null);
1650 * @see ISaveParticipant
1652 public void rollback(ISaveContext context){
1655 private void saveState(PerProjectInfo info, ISaveContext context) throws CoreException {
1657 // passed this point, save actions are non trivial
1658 if (context.getKind() == ISaveContext.SNAPSHOT) return;
1661 if (info.triedRead) saveBuiltState(info);
1665 * Saves the built state for the project.
1667 private void saveBuiltState(PerProjectInfo info) throws CoreException {
1668 if (PHPBuilder.DEBUG)
1669 System.out.println(Util.bind("build.saveStateProgress", info.project.getName())); //$NON-NLS-1$
1670 File file = getSerializationFile(info.project);
1671 if (file == null) return;
1672 long t = System.currentTimeMillis();
1674 DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
1676 out.writeUTF(JavaCore.PLUGIN_ID);
1677 out.writeUTF("STATE"); //$NON-NLS-1$
1678 if (info.savedState == null) {
1679 out.writeBoolean(false);
1681 out.writeBoolean(true);
1682 PHPBuilder.writeState(info.savedState, out);
1687 } catch (RuntimeException e) {
1688 try {file.delete();} catch(SecurityException se) {}
1689 throw new CoreException(
1690 new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
1691 Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$
1692 } catch (IOException e) {
1693 try {file.delete();} catch(SecurityException se) {}
1694 throw new CoreException(
1695 new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
1696 Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$
1698 if (PHPBuilder.DEBUG) {
1699 t = System.currentTimeMillis() - t;
1700 System.out.println(Util.bind("build.saveStateComplete", String.valueOf(t))); //$NON-NLS-1$
1705 * @see ISaveParticipant
1707 public void saving(ISaveContext context) throws CoreException {
1709 IProject savedProject = context.getProject();
1710 if (savedProject != null) {
1711 if (!JavaProject.hasJavaNature(savedProject)) return; // ignore
1712 PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */);
1713 saveState(info, context);
1717 ArrayList vStats= null; // lazy initialized
1718 for (Iterator iter = perProjectInfo.values().iterator(); iter.hasNext();) {
1720 PerProjectInfo info = (PerProjectInfo) iter.next();
1721 saveState(info, context);
1722 } catch (CoreException e) {
1724 vStats= new ArrayList();
1725 vStats.add(e.getStatus());
1728 if (vStats != null) {
1729 IStatus[] stats= new IStatus[vStats.size()];
1730 vStats.toArray(stats);
1731 throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Util.bind("build.cannotSaveStates"), null)); //$NON-NLS-1$
1736 * Record the order in which to build the java projects (batch build). This order is based
1737 * on the projects classpath settings.
1739 protected void setBuildOrder(String[] javaBuildOrder) throws JavaModelException {
1741 // optional behaviour
1742 // possible value of index 0 is Compute
1743 if (!JavaCore.COMPUTE.equals(JavaCore.getOption(JavaCore.CORE_JAVA_BUILD_ORDER))) return; // cannot be customized at project level
1745 if (javaBuildOrder == null || javaBuildOrder.length <= 1) return;
1747 IWorkspace workspace = ResourcesPlugin.getWorkspace();
1748 IWorkspaceDescription description = workspace.getDescription();
1749 String[] wksBuildOrder = description.getBuildOrder();
1752 if (wksBuildOrder == null){
1753 newOrder = javaBuildOrder;
1755 // remove projects which are already mentionned in java builder order
1756 int javaCount = javaBuildOrder.length;
1757 HashMap newSet = new HashMap(javaCount); // create a set for fast check
1758 for (int i = 0; i < javaCount; i++){
1759 newSet.put(javaBuildOrder[i], javaBuildOrder[i]);
1762 int oldCount = wksBuildOrder.length;
1763 for (int i = 0; i < oldCount; i++){
1764 if (newSet.containsKey(wksBuildOrder[i])){
1765 wksBuildOrder[i] = null;
1769 // add Java ones first
1770 newOrder = new String[oldCount - removed + javaCount];
1771 System.arraycopy(javaBuildOrder, 0, newOrder, 0, javaCount); // java projects are built first
1773 // copy previous items in their respective order
1774 int index = javaCount;
1775 for (int i = 0; i < oldCount; i++){
1776 if (wksBuildOrder[i] != null){
1777 newOrder[index++] = wksBuildOrder[i];
1781 // commit the new build order out
1782 description.setBuildOrder(newOrder);
1784 workspace.setDescription(description);
1785 } catch(CoreException e){
1786 throw new JavaModelException(e);
1791 * Sets the last built state for the given project, or null to reset it.
1793 public void setLastBuiltState(IProject project, Object state) {
1794 if (!JavaProject.hasJavaNature(project)) return; // should never be requested on non-Java projects
1795 PerProjectInfo info = getPerProjectInfo(project, true /*create if missing*/);
1796 info.triedRead = true; // no point trying to re-read once using setter
1797 info.savedState = state;
1798 if (state == null) { // delete state file to ensure a full build happens if the workspace crashes
1800 File file = getSerializationFile(project);
1801 if (file != null && file.exists())
1803 } catch(SecurityException se) {}
1807 public void shutdown () {
1808 // TODO khartlage temp-del
1809 // if (this.deltaProcessor.indexManager != null){ // no more indexing
1810 // this.deltaProcessor.indexManager.shutdown();
1813 IJavaModel model = this.getJavaModel();
1814 if (model != null) {
1818 } catch (JavaModelException e) {
1823 * Turns the firing mode to on. That is, deltas that are/have been
1824 * registered will be fired.
1826 public void startDeltas() {
1827 this.isFiring= true;
1831 * Turns the firing mode to off. That is, deltas that are/have been
1832 * registered will not be fired until deltas are started again.
1834 public void stopDeltas() {
1835 this.isFiring= false;
1839 * Update Java Model given some delta
1841 // public void updateJavaModel(IJavaElementDelta customDelta) {
1843 // if (customDelta == null){
1844 // for (int i = 0, length = this.javaModelDeltas.size(); i < length; i++){
1845 // IJavaElementDelta delta = (IJavaElementDelta)this.javaModelDeltas.get(i);
1846 // this.modelUpdater.processJavaDelta(delta);
1849 // this.modelUpdater.processJavaDelta(customDelta);
1855 public static IPath variableGet(String variableName){
1856 return (IPath)Variables.get(variableName);
1859 public static String[] variableNames(){
1860 int length = Variables.size();
1861 String[] result = new String[length];
1862 Iterator vars = Variables.keySet().iterator();
1864 while (vars.hasNext()) {
1865 result[index++] = (String) vars.next();
1870 public static void variablePut(String variableName, IPath variablePath){
1872 // update cache - do not only rely on listener refresh
1873 if (variablePath == null) {
1874 Variables.remove(variableName);
1875 PreviousSessionVariables.remove(variableName);
1877 Variables.put(variableName, variablePath);
1880 // do not write out intermediate initialization value
1881 if (variablePath == JavaModelManager.VariableInitializationInProgress){
1884 Preferences preferences = JavaCore.getPlugin().getPluginPreferences();
1885 String variableKey = CP_VARIABLE_PREFERENCES_PREFIX+variableName;
1886 String variableString = variablePath == null ? CP_ENTRY_IGNORE : variablePath.toString();
1887 preferences.setDefault(variableKey, CP_ENTRY_IGNORE); // use this default to get rid of removed ones
1888 preferences.setValue(variableKey, variableString);
1889 JavaCore.getPlugin().savePluginPreferences();
1892 * Returns all the working copies which have the given owner.
1893 * Adds the working copies of the primary owner if specified.
1894 * Returns null if it has none.
1896 public ICompilationUnit[] getWorkingCopies(WorkingCopyOwner owner, boolean addPrimary) {
1897 synchronized(perWorkingCopyInfos) {
1898 ICompilationUnit[] primaryWCs = addPrimary && owner != DefaultWorkingCopyOwner.PRIMARY
1899 ? getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false)
1901 Map workingCopyToInfos = (Map)perWorkingCopyInfos.get(owner);
1902 if (workingCopyToInfos == null) return primaryWCs;
1903 int primaryLength = primaryWCs == null ? 0 : primaryWCs.length;
1904 int size = workingCopyToInfos.size(); // note size is > 0 otherwise pathToPerWorkingCopyInfos would be null
1905 ICompilationUnit[] result = new ICompilationUnit[primaryLength + size];
1906 if (primaryWCs != null) {
1907 System.arraycopy(primaryWCs, 0, result, 0, primaryLength);
1909 Iterator iterator = workingCopyToInfos.values().iterator();
1910 int index = primaryLength;
1911 while(iterator.hasNext()) {
1912 result[index++] = ((JavaModelManager.PerWorkingCopyInfo)iterator.next()).getWorkingCopy();