RC2 compatibility
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpdt / internal / core / JavaModelManager.java
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
7  * 
8  * Contributors:
9  *     IBM Corporation - initial API and implementation
10  *******************************************************************************/
11 package net.sourceforge.phpdt.internal.core;
12
13 import java.io.BufferedInputStream;
14 import java.io.BufferedOutputStream;
15 import java.io.DataInputStream;
16 import java.io.DataOutputStream;
17 import java.io.File;
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;
27 import java.util.Map;
28 import java.util.WeakHashMap;
29 import java.util.zip.ZipFile;
30
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;
48
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;
71
72 import net.sourceforge.phpdt.internal.core.DefaultWorkingCopyOwner;
73
74 import net.sourceforge.phpdt.internal.core.DeltaProcessingState;
75
76 import net.sourceforge.phpdt.internal.core.DeltaProcessor;
77
78 import net.sourceforge.phpdt.core.IParent;
79 import net.sourceforge.phpdt.internal.core.JavaElementInfo;
80
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;
88
89 /**
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.
93  * <p>
94  * The single instance of <code>JavaModelManager</code> is available from
95  * the static method <code>JavaModelManager.getJavaModelManager()</code>.
96  */
97 public class JavaModelManager implements ISaveParticipant {     
98  
99         /**
100          * Unique handle onto the JavaModel
101          */
102         final JavaModel javaModel = new JavaModel();
103         
104         /**
105          * Classpath variables pool
106          */
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$
113                 
114         /**
115          * Classpath containers pool
116          */
117         public static HashMap Containers = new HashMap(5);
118         public static HashMap PreviousSessionContainers = new HashMap(5);
119
120         /**
121          * Name of the extension point for contributing classpath variable initializers
122          */
123 //      public static final String CPVARIABLE_INITIALIZER_EXTPOINT_ID = "classpathVariableInitializer" ; //$NON-NLS-1$
124
125         /**
126          * Name of the extension point for contributing classpath container initializers
127          */
128 //      public static final String CPCONTAINER_INITIALIZER_EXTPOINT_ID = "classpathContainerInitializer" ; //$NON-NLS-1$
129
130         /**
131          * Name of the extension point for contributing a source code formatter
132          */
133         public static final String FORMATTER_EXTPOINT_ID = "codeFormatter" ; //$NON-NLS-1$
134         
135         /**
136          * Special value used for recognizing ongoing initialization and breaking initialization cycles
137          */
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(); }
145 //      };
146         
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$
160
161         public final static IWorkingCopy[] NoWorkingCopy = new IWorkingCopy[0];
162         
163         /**
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
166          */
167         protected Map perWorkingCopyInfos = new HashMap(5);
168         /**
169          * Returns whether the given full path (for a package) conflicts with the output location
170          * of the given project.
171          */
172         public static boolean conflictsWithOutputLocation(IPath folderPath, JavaProject project) {
173                 try {
174                         IPath outputLocation = project.getOutputLocation();
175                         if (outputLocation == null) {
176                                 // in doubt, there is a conflict
177                                 return true;
178                         }
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)) {
188                                                         return false;
189                                                 }
190                                                 if (entry.getOutputLocation() == null) {
191                                                         isOutputUsed = true;
192                                                 }
193                                         }
194                                 }
195                                 return isOutputUsed;
196                         }
197                         return false;
198                 } catch (JavaModelException e) {
199                         // in doubt, there is a conflict
200                         return true;
201                 }
202         }
203
204 //      public static IClasspathContainer containerGet(IJavaProject project, IPath containerPath) {     
205 //              Map projectContainers = (Map)Containers.get(project);
206 //              if (projectContainers == null){
207 //                      return null;
208 //              }
209 //              IClasspathContainer container = (IClasspathContainer)projectContainers.get(containerPath);
210 //              return container;
211 //      }
212
213 //      public static void containerPut(IJavaProject project, IPath containerPath, IClasspathContainer container){
214 //
215 //              Map projectContainers = (Map)Containers.get(project);
216 //              if (projectContainers == null){
217 //                      projectContainers = new HashMap(1);
218 //                      Containers.put(project, projectContainers);
219 //              }
220 //
221 //              if (container == null) {
222 //                      projectContainers.remove(containerPath);
223 //                      Map previousContainers = (Map)PreviousSessionContainers.get(project);
224 //                      if (previousContainers != null){
225 //                              previousContainers.remove(containerPath);
226 //                      }
227 //              } else {
228 //                      projectContainers.put(containerPath, container);
229 //              }
230 //
231 //              // do not write out intermediate initialization value
232 //              if (container == JavaModelManager.ContainerInitializationInProgress) {
233 //                      return;
234 //              }
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;
238 //              try {
239 //                      if (container != null) {
240 //                              containerString = ((JavaProject)project).encodeClasspath(container.getClasspathEntries(), null, false);
241 //                      }
242 //              } catch(JavaModelException e){
243 //              }
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();
247 //      }
248
249         /**
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.
253          * <p>
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>
262          *      </ul>
263          * <p>
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.
266          */
267         public static IJavaElement create(IResource resource, IJavaProject project) {
268                 if (resource == null) {
269                         return null;
270                 }
271                 int type = resource.getType();
272                 switch (type) {
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);
281                         default :
282                                 return null;
283                 }
284         }
285
286         /**
287          * Returns the Java element corresponding to the given file, its project being the given
288          * project.
289          * Returns <code>null</code> if unable to associate the given file
290          * with a Java element.
291          *
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>
296          *      </ul>
297          * <p>
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.
300          */
301         public static IJavaElement create(IFile file, IJavaProject project) {
302                 if (file == null) {
303                         return null;
304                 }
305                 if (project == null) {
306                         project = JavaCore.create(file.getProject());
307                 }
308         
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);
318                 }
319                 return null;
320         }
321
322         /**
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.
326          * <p>
327          * Note that a package fragment root is returned rather than a default package.
328          * <p>
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.
331          */
332         public static IJavaElement create(IFolder folder, IJavaProject project) {
333                 if (folder == null) {
334                         return null;
335                 }
336                 if (project == null) {
337                         project = JavaCore.create(folder.getProject());
338                 }
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
344                 } else {
345                         return element;
346                 }
347         }
348
349         /**
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.
353          */
354 //      public static IClassFile createClassFileFrom(IFile file, IJavaProject project ) {
355 //              if (file == null) {
356 //                      return null;
357 //              }
358 //              if (project == null) {
359 //                      project = PHPCore.create(file.getProject());
360 //              }
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);
367 //              }
368 //              return pkg.getClassFile(file.getName());
369 //      }
370         
371         /**
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.
375          */
376         public static ICompilationUnit createCompilationUnitFrom(IFile file, IJavaProject project) {
377
378                 if (file == null) return null;
379
380                 if (project == null) {
381                         project = JavaCore.create(file.getProject());
382                 }
383                 IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
384                 if (pkg == null) {
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);
388                         
389                         if (VERBOSE){
390                                 System.out.println("WARNING : creating unit element outside classpath ("+ Thread.currentThread()+"): " + file.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$
391                         }
392                 }
393                 return pkg.getCompilationUnit(file.getName());
394         }
395         /**
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)
401          */
402 //      public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file, IJavaProject project) {
403 //              if (file == null) {
404 //                      return null;
405 //              }
406 //              if (project == null) {
407 //                      project = PHPCore.create(file.getProject());
408 //              }
409 //      
410 //              // Create a jar package fragment root only if on the classpath
411 //              IPath resourcePath = file.getFullPath();
412 //              try {
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);
419 //                              }
420 //                      }
421 //              } catch (JavaModelException e) {
422 //              }
423 //              return null;
424 //      }
425         
426         /**
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.
430          */
431         public static IJavaElement determineIfOnClasspath(
432                 IResource resource,
433                 IJavaProject project) {
434                         
435                 IPath resourcePath = resource.getFullPath();
436                 try {
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);
441                                 
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);
457                                                 
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                                                 return root.getPackageFragment(pkgName);
461                                         } else {
462                                                 String pkgName = Util.packageName(pkgPath);
463                                                 if (pkgName == null){// || JavaConventions.validatePackageName(pkgName).getSeverity() == IStatus.ERROR) {
464                                                         return null;
465                                                 }
466                                                 return root.getPackageFragment(pkgName);
467                                         }
468                                 }
469                         }
470                 } catch (JavaModelException npe) {
471                         return null;
472                 }
473                 return null;
474         }
475         
476         /**
477          * The singleton manager
478          */
479         private final static JavaModelManager Manager= new JavaModelManager();
480
481         /**
482          * Infos cache.
483          */
484         protected JavaModelCache cache = new JavaModelCache();
485
486         /*
487          * Temporary cache of newly opened elements
488          */
489         private ThreadLocal temporaryCache = new ThreadLocal();
490         /**
491          * Set of elements which are out of sync with their buffers.
492          */
493         protected Map elementsOutOfSynchWithBuffers = new HashMap(11);
494         /**
495          * Holds the state used for delta processing.
496          */
497         public DeltaProcessingState deltaState = new DeltaProcessingState();
498         /**
499          * Turns delta firing on/off. By default it is on.
500          */
501         private boolean isFiring= true;
502
503         /**
504          * Queue of deltas created explicily by the Java Model that
505          * have yet to be fired.
506          */
507         ArrayList javaModelDeltas= new ArrayList();
508         /**
509          * Queue of reconcile deltas on working copies that have yet to be fired.
510          * This is a table form IWorkingCopy to IJavaElementDelta
511          */
512         HashMap reconcileDeltas = new HashMap();
513
514
515         /**
516          * Collection of listeners for Java element deltas
517          */
518         private IElementChangedListener[] elementChangedListeners = new IElementChangedListener[5];
519         private int[] elementChangedListenerMasks = new int[5];
520         private int elementChangedListenerCount = 0;
521         public int currentChangeEventType = ElementChangedEvent.PRE_AUTO_BUILD;
522         public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with ElementChangedEvent event masks
523
524
525
526         /**
527          * Used to convert <code>IResourceDelta</code>s into <code>IJavaElementDelta</code>s.
528          */
529 //      public final DeltaProcessor deltaProcessor = new DeltaProcessor(this);
530         /**
531          * Used to update the JavaModel for <code>IJavaElementDelta</code>s.
532          */
533 //      private final ModelUpdater modelUpdater =new ModelUpdater();
534         /**
535          * Workaround for bug 15168 circular errors not reported  
536          * This is a cache of the projects before any project addition/deletion has started.
537          */
538         public IJavaProject[] javaProjectsCache;
539
540         /**
541          * Table from IProject to PerProjectInfo.
542          * NOTE: this object itself is used as a lock to synchronize creation/removal of per project infos
543          */
544         protected Map perProjectInfo = new HashMap(5);
545         
546         /**
547          * A map from ICompilationUnit to IWorkingCopy
548          * of the shared working copies.
549          */
550         public Map sharedWorkingCopies = new HashMap();
551         
552         /**
553          * A weak set of the known scopes.
554          */
555         protected WeakHashMap scopes = new WeakHashMap();
556
557         public static class PerProjectInfo {
558                 public IProject project;
559                 public Object savedState;
560                 public boolean triedRead;
561                 public IClasspathEntry[] classpath;
562                 public IClasspathEntry[] lastResolvedClasspath;
563                 public Map resolvedPathToRawEntries; // reverse map from resolved path to raw entries
564                 public IPath outputLocation;
565                 public Preferences preferences;
566                 public PerProjectInfo(IProject project) {
567
568                         this.triedRead = false;
569                         this.savedState = null;
570                         this.project = project;
571                 }
572         }
573         public static class PerWorkingCopyInfo implements IProblemRequestor {
574                 int useCount = 0;
575                 IProblemRequestor problemRequestor;
576                 ICompilationUnit workingCopy;
577                 public PerWorkingCopyInfo(ICompilationUnit workingCopy, IProblemRequestor problemRequestor) {
578                         this.workingCopy = workingCopy;
579                         this.problemRequestor = problemRequestor;
580                 }
581                 public void acceptProblem(IProblem problem) {
582                         if (this.problemRequestor == null) return;
583                         this.problemRequestor.acceptProblem(problem);
584                 }
585                 public void beginReporting() {
586                         if (this.problemRequestor == null) return;
587                         this.problemRequestor.beginReporting();
588                 }
589                 public void endReporting() {
590                         if (this.problemRequestor == null) return;
591                         this.problemRequestor.endReporting();
592                 }
593                 public ICompilationUnit getWorkingCopy() {
594                         return this.workingCopy;
595                 }
596                 public boolean isActive() {
597                         return this.problemRequestor != null && this.problemRequestor.isActive();
598                 }
599                 public String toString() {
600                         StringBuffer buffer = new StringBuffer();
601                         buffer.append("Info for "); //$NON-NLS-1$
602                         buffer.append(((JavaElement)workingCopy).toStringWithAncestors());
603                         buffer.append("\nUse count = "); //$NON-NLS-1$
604                         buffer.append(this.useCount);
605                         buffer.append("\nProblem requestor:\n  "); //$NON-NLS-1$
606                         buffer.append(this.problemRequestor);
607                         return buffer.toString();
608                 }
609         }
610         public static boolean VERBOSE = true;
611         public static boolean CP_RESOLVE_VERBOSE = false;
612         public static boolean ZIP_ACCESS_VERBOSE = false;
613         
614         /**
615          * A cache of opened zip files per thread.
616          * (map from Thread to map of IPath to java.io.ZipFile)
617          * NOTE: this object itself is used as a lock to synchronize creation/removal of entries
618          */
619         private HashMap zipFiles = new HashMap();
620         
621         
622         /**
623          * Update the classpath variable cache
624          */
625         public static class PluginPreferencesListener implements Preferences.IPropertyChangeListener {
626                 /**
627                  * @see org.eclipse.core.runtime.Preferences.IPropertyChangeListener#propertyChange(PropertyChangeEvent)
628                  */
629                 public void propertyChange(Preferences.PropertyChangeEvent event) {
630 //                      TODO : jsurfer temp-del
631 //                      String propertyName = event.getProperty();
632 //                      if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)) {
633 //                              String varName = propertyName.substring(CP_VARIABLE_PREFERENCES_PREFIX.length());
634 //                              String newValue = (String)event.getNewValue();
635 //                              if (newValue != null && !(newValue = newValue.trim()).equals(CP_ENTRY_IGNORE)) {
636 //                                      Variables.put(varName, new Path(newValue));
637 //                              } else {
638 //                                      Variables.remove(varName);
639 //                              }
640 //                      }
641 //                      if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)) {
642 //                              recreatePersistedContainer(propertyName, (String)event.getNewValue(), false);
643 //                      }
644                 }
645         }
646
647         /**
648          * Line separator to use throughout the JavaModel for any source edit operation
649          */
650   public static String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
651         /**
652          * Constructs a new JavaModelManager
653          */
654         private JavaModelManager() {
655         }
656
657         /**
658          * @deprecated - discard once debug has converted to not using it
659          */
660         public void addElementChangedListener(IElementChangedListener listener) {
661                 this.addElementChangedListener(listener, ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE);
662         }
663         /**
664          * addElementChangedListener method comment.
665          * Need to clone defensively the listener information, in case some listener is reacting to some notification iteration by adding/changing/removing
666          * any of the other (for example, if it deregisters itself).
667          */
668         public void addElementChangedListener(IElementChangedListener listener, int eventMask) {
669                 for (int i = 0; i < this.elementChangedListenerCount; i++){
670                         if (this.elementChangedListeners[i].equals(listener)){
671                                 
672                                 // only clone the masks, since we could be in the middle of notifications and one listener decide to change
673                                 // any event mask of another listeners (yet not notified).
674                                 int cloneLength = this.elementChangedListenerMasks.length;
675                                 System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[cloneLength], 0, cloneLength);
676                                 this.elementChangedListenerMasks[i] = eventMask; // could be different
677                                 return;
678                         }
679                 }
680                 // 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.
681                 int length;
682                 if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount){
683                         System.arraycopy(this.elementChangedListeners, 0, this.elementChangedListeners = new IElementChangedListener[length*2], 0, length);
684                         System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[length*2], 0, length);
685                 }
686                 this.elementChangedListeners[this.elementChangedListenerCount] = listener;
687                 this.elementChangedListenerMasks[this.elementChangedListenerCount] = eventMask;
688                 this.elementChangedListenerCount++;
689         }
690
691         /**
692          * Starts caching ZipFiles.
693          * Ignores if there are already clients.
694          */
695         public void cacheZipFiles() {
696                 synchronized(this.zipFiles) {
697                         Thread currentThread = Thread.currentThread();
698                         if (this.zipFiles.get(currentThread) != null) return;
699                         this.zipFiles.put(currentThread, new HashMap());
700                 }
701         }
702         public void closeZipFile(ZipFile zipFile) {
703                 if (zipFile == null) return;
704                 synchronized(this.zipFiles) {
705                         if (this.zipFiles.get(Thread.currentThread()) != null) {
706                                 return; // zip file will be closed by call to flushZipFiles
707                         }
708                         try {
709                                 if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
710                                         System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.closeZipFile(ZipFile)] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$   //$NON-NLS-2$
711                                 }
712                                 zipFile.close();
713                         } catch (IOException e) {
714                         }
715                 }
716         }
717         
718
719
720         /**
721          * Configure the plugin with respect to option settings defined in ".options" file
722          */
723         public void configurePluginDebugOptions(){
724                 if(JavaCore.getPlugin().isDebugging()){
725 //              TODO jsurfer temp-del
726                         
727                         String option = Platform.getDebugOption(BUILDER_DEBUG);
728 //                      if(option != null) JavaBuilder.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
729 //                      
730 //                      option = Platform.getDebugOption(COMPILER_DEBUG);
731 //                      if(option != null) Compiler.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
732 //
733 //                      option = Platform.getDebugOption(COMPLETION_DEBUG);
734 //                      if(option != null) CompletionEngine.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
735 //                      
736                         option = Platform.getDebugOption(CP_RESOLVE_DEBUG);
737                         if(option != null) JavaModelManager.CP_RESOLVE_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
738
739                         option = Platform.getDebugOption(DELTA_DEBUG);
740                         if(option != null) DeltaProcessor.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
741
742 //                      option = Platform.getDebugOption(HIERARCHY_DEBUG);
743 //                      if(option != null) TypeHierarchy.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
744 //
745 //                      option = Platform.getDebugOption(INDEX_MANAGER_DEBUG);
746 //                      if(option != null) IndexManager.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
747                         
748                         option = Platform.getDebugOption(JAVAMODEL_DEBUG);
749                         if(option != null) JavaModelManager.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
750
751                         option = Platform.getDebugOption(POST_ACTION_DEBUG);
752                         if(option != null) JavaModelOperation.POST_ACTION_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
753
754 //                      option = Platform.getDebugOption(SEARCH_DEBUG);
755 //                      if(option != null) SearchEngine.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
756 //
757 //                      option = Platform.getDebugOption(SELECTION_DEBUG);
758 //                      if(option != null) SelectionEngine.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
759
760                         option = Platform.getDebugOption(ZIP_ACCESS_DEBUG);
761                         if(option != null) JavaModelManager.ZIP_ACCESS_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
762                 }
763         }
764         
765
766         /*
767          * Discards the per working copy info for the given working copy (making it a compilation unit)
768          * if its use count was 1. Otherwise, just decrement the use count.
769          * If the working copy is primary, computes the delta between its state and the original compilation unit
770          * and register it.
771          * Close the working copy, its buffer and remove it from the shared working copy table.
772          * Ignore if no per-working copy info existed.
773          * NOTE: it must be synchronized as it may interact with the element info cache (if useCount is decremented to 0), see bug 50667.
774          * Returns the new use count (or -1 if it didn't exist).
775          */
776         public synchronized int discardPerWorkingCopyInfo(CompilationUnit workingCopy) throws JavaModelException {
777                 synchronized(perWorkingCopyInfos) {
778                         WorkingCopyOwner owner = workingCopy.owner;
779                         Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
780                         if (workingCopyToInfos == null) return -1;
781                         
782                         PerWorkingCopyInfo info = (PerWorkingCopyInfo)workingCopyToInfos.get(workingCopy);
783                         if (info == null) return -1;
784                         
785                         if (--info.useCount == 0) {
786                                 // create the delta builder (this remembers the current content of the working copy)
787                                 JavaElementDeltaBuilder deltaBuilder = null;
788                                 if (workingCopy.isPrimary()) {
789                                         deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
790                                 }
791
792                                 // remove per working copy info
793                                 workingCopyToInfos.remove(workingCopy);
794                                 if (workingCopyToInfos.isEmpty()) {
795                                         this.perWorkingCopyInfos.remove(owner);
796                                 }
797
798                                 // remove infos + close buffer (since no longer working copy)
799                                 removeInfoAndChildren(workingCopy);
800                                 workingCopy.closeBuffer();
801
802                                 // compute the delta if needed and register it if there are changes
803                                 if (deltaBuilder != null) {
804                                         deltaBuilder.buildDeltas();
805                                         if ((deltaBuilder.delta != null) && (deltaBuilder.delta.getAffectedChildren().length > 0)) {
806                                                 getDeltaProcessor().registerJavaModelDelta(deltaBuilder.delta);
807                                         }
808                                 }
809                                 
810                         }
811                         return info.useCount;
812                 }
813         }
814         
815         /**
816          * @see ISaveParticipant
817          */
818         public void doneSaving(ISaveContext context){
819         }
820         
821         /**
822          * Fire Java Model delta, flushing them after the fact after post_change notification.
823          * If the firing mode has been turned off, this has no effect. 
824          */
825         public void fire(IJavaElementDelta customDelta, int eventType) {
826
827                 if (!this.isFiring) return;
828                 
829                 if (DeltaProcessor.VERBOSE && (eventType == DEFAULT_CHANGE_EVENT || eventType == ElementChangedEvent.PRE_AUTO_BUILD)) {
830                         System.out.println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$
831                 }
832
833                 IJavaElementDelta deltaToNotify;
834                 if (customDelta == null){
835                         deltaToNotify = this.mergeDeltas(this.javaModelDeltas);
836                 } else {
837                         deltaToNotify = customDelta;
838                 }
839                         
840                 // Refresh internal scopes
841                 if (deltaToNotify != null) {
842 //              TODO khartlage temp-del
843 //                      Iterator scopes = this.scopes.keySet().iterator();
844 //                      while (scopes.hasNext()) {
845 //                              AbstractSearchScope scope = (AbstractSearchScope)scopes.next();
846 //                              scope.processDelta(deltaToNotify);
847 //                      }
848                 }
849                         
850                 // Notification
851         
852                 // Important: if any listener reacts to notification by updating the listeners list or mask, these lists will
853                 // be duplicated, so it is necessary to remember original lists in a variable (since field values may change under us)
854                 IElementChangedListener[] listeners = this.elementChangedListeners;
855                 int[] listenerMask = this.elementChangedListenerMasks;
856                 int listenerCount = this.elementChangedListenerCount;
857
858                 switch (eventType) {
859                         case DEFAULT_CHANGE_EVENT:
860                                 firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, listenerCount);
861                                 firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
862                                 fireReconcileDelta(listeners, listenerMask, listenerCount);
863                                 break;
864                         case ElementChangedEvent.PRE_AUTO_BUILD:
865                                 firePreAutoBuildDelta(deltaToNotify, listeners, listenerMask, listenerCount);
866                                 break;
867                         case ElementChangedEvent.POST_CHANGE:
868                                 firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
869                                 fireReconcileDelta(listeners, listenerMask, listenerCount);
870                                 break;
871                 }
872
873         }
874
875         private void firePreAutoBuildDelta(
876                 IJavaElementDelta deltaToNotify,
877                 IElementChangedListener[] listeners,
878                 int[] listenerMask,
879                 int listenerCount) {
880                         
881                 if (DeltaProcessor.VERBOSE){
882                         System.out.println("FIRING PRE_AUTO_BUILD Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
883                         System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
884                 }
885                 if (deltaToNotify != null) {
886                         notifyListeners(deltaToNotify, ElementChangedEvent.PRE_AUTO_BUILD, listeners, listenerMask, listenerCount);
887                 }
888         }
889
890         private void firePostChangeDelta(
891                 IJavaElementDelta deltaToNotify,
892                 IElementChangedListener[] listeners,
893                 int[] listenerMask,
894                 int listenerCount) {
895                         
896                 // post change deltas
897                 if (DeltaProcessor.VERBOSE){
898                         System.out.println("FIRING POST_CHANGE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
899                         System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
900                 }
901                 if (deltaToNotify != null) {
902                         // flush now so as to keep listener reactions to post their own deltas for subsequent iteration
903                         this.flush();
904                         
905                         notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, listeners, listenerMask, listenerCount);
906                 } 
907         }               
908         private void fireReconcileDelta(
909                 IElementChangedListener[] listeners,
910                 int[] listenerMask,
911                 int listenerCount) {
912
913
914                 IJavaElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas.values());
915                 if (DeltaProcessor.VERBOSE){
916                         System.out.println("FIRING POST_RECONCILE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
917                         System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
918                 }
919                 if (deltaToNotify != null) {
920                         // flush now so as to keep listener reactions to post their own deltas for subsequent iteration
921                         this.reconcileDeltas = new HashMap();
922                 
923                         notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, listeners, listenerMask, listenerCount);
924                 } 
925         }
926
927         public void notifyListeners(IJavaElementDelta deltaToNotify, int eventType, IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {
928                 final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType);
929                 for (int i= 0; i < listenerCount; i++) {
930                         if ((listenerMask[i] & eventType) != 0){
931                                 final IElementChangedListener listener = listeners[i];
932                                 long start = -1;
933                                 if (DeltaProcessor.VERBOSE) {
934                                         System.out.print("Listener #" + (i+1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$
935                                         start = System.currentTimeMillis();
936                                 }
937                                 // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
938                                 Platform.run(new ISafeRunnable() {
939                                         public void handleException(Throwable exception) {
940                                                 Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$
941                                         }
942                                         public void run() throws Exception {
943                                                 listener.elementChanged(extraEvent);
944                                         }
945                                 });
946                                 if (DeltaProcessor.VERBOSE) {
947                                         System.out.println(" -> " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
948                                 }
949                         }
950                 }
951         }
952         
953         /**
954          * Flushes all deltas without firing them.
955          */
956         protected void flush() {
957                 this.javaModelDeltas = new ArrayList();
958         }
959
960         /**
961          * Flushes ZipFiles cache if there are no more clients.
962          */
963         public void flushZipFiles() {
964                 synchronized(this.zipFiles) {
965                         Thread currentThread = Thread.currentThread();
966                         HashMap map = (HashMap)this.zipFiles.remove(currentThread);
967                         if (map == null) return;
968                         Iterator iterator = map.values().iterator();
969                         while (iterator.hasNext()) {
970                                 try {
971                                         ZipFile zipFile = (ZipFile)iterator.next();
972                                         if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
973                                                 System.out.println("(" + currentThread + ") [JavaModelManager.flushZipFiles()] Closing ZipFile on " +zipFile.getName()); //$NON-NLS-1$//$NON-NLS-2$
974                                         }
975                                         zipFile.close();
976                                 } catch (IOException e) {
977                                 }
978                         }
979                 }       
980         }
981         
982
983         public DeltaProcessor getDeltaProcessor() {
984                 return this.deltaState.getDeltaProcessor();
985         }
986         /** 
987          * Returns the set of elements which are out of synch with their buffers.
988          */
989         protected Map getElementsOutOfSynchWithBuffers() {
990                 return this.elementsOutOfSynchWithBuffers;
991         }
992
993         /**
994          * Returns the <code>IJavaElement</code> represented by the 
995          * <code>String</code> memento.
996          */
997         public IJavaElement getHandleFromMemento(String memento) throws JavaModelException {
998                 if (memento == null) {
999                         return null;
1000                 }
1001                 JavaModel model= (JavaModel) getJavaModel();
1002                 if (memento.equals("")){ // workspace memento //$NON-NLS-1$
1003                         return model;
1004                 }
1005                 int modelEnd= memento.indexOf(JavaElement.JEM_JAVAPROJECT);
1006                 if (modelEnd == -1) {
1007                         return null;
1008                 }
1009                 boolean returnProject= false;
1010                 int projectEnd= memento.indexOf(JavaElement.JEM_PACKAGEFRAGMENTROOT, modelEnd);
1011                 if (projectEnd == -1) {
1012                         projectEnd= memento.length();
1013                         returnProject= true;
1014                 }
1015                 String projectName= memento.substring(modelEnd + 1, projectEnd);
1016                 JavaProject proj= (JavaProject) model.getJavaProject(projectName);
1017                 if (returnProject) {
1018                         return proj;
1019                 }
1020                 int rootEnd= memento.indexOf(JavaElement.JEM_PACKAGEFRAGMENT, projectEnd + 1);
1021 //      TODO khartlage temp-del
1022 //              if (rootEnd == -1) {
1023 //                      return model.getHandleFromMementoForRoot(memento, proj, projectEnd, memento.length());
1024 //              }
1025 //              IPackageFragmentRoot root = model.getHandleFromMementoForRoot(memento, proj, projectEnd, rootEnd);
1026 //              if (root == null)
1027 //                      return null;
1028 //
1029 //              int end= memento.indexOf(JavaElement.JEM_COMPILATIONUNIT, rootEnd);
1030 //              if (end == -1) {
1031 //                      end= memento.indexOf(JavaElement.JEM_CLASSFILE, rootEnd);
1032 //                      if (end == -1) {
1033 //                              if (rootEnd + 1 == memento.length()) {
1034 //                                      return root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
1035 //                              } else {
1036 //                                      return root.getPackageFragment(memento.substring(rootEnd + 1));
1037 //                              }
1038 //                      }
1039 //                      //deal with class file and binary members
1040 //                      return model.getHandleFromMementoForBinaryMembers(memento, root, rootEnd, end);
1041 //              }
1042 //
1043 //              //deal with compilation units and source members
1044 //              return model.getHandleFromMementoForSourceMembers(memento, root, rootEnd, end);
1045           return null;
1046         }
1047 //      public IndexManager getIndexManager() {
1048 //              return this.deltaProcessor.indexManager;
1049 //      }
1050
1051         /**
1052          *  Returns the info for the element.
1053          */
1054         public Object getInfo(IJavaElement element) {
1055                 return this.cache.getInfo(element);
1056         }
1057
1058         /**
1059          * Returns the handle to the active Java Model.
1060          */
1061         public final JavaModel getJavaModel() {
1062                 return javaModel;
1063         }
1064
1065         /**
1066          * Returns the singleton JavaModelManager
1067          */
1068         public final static JavaModelManager getJavaModelManager() {
1069                 return Manager;
1070         }
1071
1072         /**
1073          * Returns the last built state for the given project, or null if there is none.
1074          * Deserializes the state if necessary.
1075          *
1076          * For use by image builder and evaluation support only
1077          */
1078         public Object getLastBuiltState(IProject project, IProgressMonitor monitor) {
1079                 if (!JavaProject.hasJavaNature(project)) return null; // should never be requested on non-Java projects
1080                 PerProjectInfo info = getPerProjectInfo(project, true/*create if missing*/);
1081                 if (!info.triedRead) {
1082                         info.triedRead = true;
1083                         try {
1084                                 if (monitor != null)
1085                                         monitor.subTask(Util.bind("build.readStateProgress", project.getName())); //$NON-NLS-1$
1086                                 info.savedState = readState(project);
1087                         } catch (CoreException e) {
1088                                 e.printStackTrace();
1089                         }
1090                 }
1091                 return info.savedState;
1092         }
1093
1094         /*
1095          * Returns the per-project info for the given project. If specified, create the info if the info doesn't exist.
1096          */
1097         public PerProjectInfo getPerProjectInfo(IProject project, boolean create) {
1098                 synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock
1099                         PerProjectInfo info= (PerProjectInfo) perProjectInfo.get(project);
1100                         if (info == null && create) {
1101                                 info= new PerProjectInfo(project);
1102                                 perProjectInfo.put(project, info);
1103                         }
1104                         return info;
1105                 }
1106         }       
1107         
1108         /*
1109          * Returns  the per-project info for the given project.
1110          * If the info doesn't exist, check for the project existence and create the info.
1111          * @throws JavaModelException if the project doesn't exist.
1112          */
1113         public PerProjectInfo getPerProjectInfoCheckExistence(IProject project) throws JavaModelException {
1114                 JavaModelManager.PerProjectInfo info = getPerProjectInfo(project, false /* don't create info */);
1115                 if (info == null) {
1116                         if (!JavaProject.hasJavaNature(project)) {
1117                                 throw ((JavaProject)JavaCore.create(project)).newNotPresentException();
1118                         }
1119                         info = getPerProjectInfo(project, true /* create info */);
1120                 }
1121                 return info;
1122         }
1123         /*
1124          * Returns the per-working copy info for the given working copy at the given path.
1125          * If it doesn't exist and if create, add a new per-working copy info with the given problem requestor.
1126          * If recordUsage, increment the per-working copy info's use count.
1127          * Returns null if it doesn't exist and not create.
1128          */
1129         public PerWorkingCopyInfo getPerWorkingCopyInfo(CompilationUnit workingCopy,boolean create, boolean recordUsage, IProblemRequestor problemRequestor) {
1130                 synchronized(perWorkingCopyInfos) { // use the perWorkingCopyInfo collection as its own lock
1131                         WorkingCopyOwner owner = workingCopy.owner;
1132                         Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
1133                         if (workingCopyToInfos == null && create) {
1134                                 workingCopyToInfos = new HashMap();
1135                                 this.perWorkingCopyInfos.put(owner, workingCopyToInfos);
1136                         }
1137
1138                         PerWorkingCopyInfo info = workingCopyToInfos == null ? null : (PerWorkingCopyInfo) workingCopyToInfos.get(workingCopy);
1139                         if (info == null && create) {
1140                                 info= new PerWorkingCopyInfo(workingCopy, problemRequestor);
1141                                 workingCopyToInfos.put(workingCopy, info);
1142                         }
1143                         if (info != null && recordUsage) info.useCount++;
1144                         return info;
1145                 }
1146         }       
1147         /**
1148          * Returns the name of the variables for which an CP variable initializer is registered through an extension point
1149          */
1150         public static String[] getRegisteredVariableNames(){
1151                 
1152                 Plugin jdtCorePlugin = JavaCore.getPlugin();
1153                 if (jdtCorePlugin == null) return null;
1154
1155                 ArrayList variableList = new ArrayList(5);
1156 //              IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID);
1157 //              if (extension != null) {
1158 //                      IExtension[] extensions =  extension.getExtensions();
1159 //                      for(int i = 0; i < extensions.length; i++){
1160 //                              IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
1161 //                              for(int j = 0; j < configElements.length; j++){
1162 //                                      String varAttribute = configElements[j].getAttribute("variable"); //$NON-NLS-1$
1163 //                                      if (varAttribute != null) variableList.add(varAttribute);
1164 //                              }
1165 //                      }       
1166 //              }
1167                 String[] variableNames = new String[variableList.size()];
1168                 variableList.toArray(variableNames);
1169                 return variableNames;
1170         }       
1171
1172         /**
1173          * Returns the name of the container IDs for which an CP container initializer is registered through an extension point
1174          */
1175 //      public static String[] getRegisteredContainerIDs(){
1176 //              
1177 //              Plugin jdtCorePlugin = PHPCore.getPlugin();
1178 //              if (jdtCorePlugin == null) return null;
1179 //
1180 //              ArrayList containerIDList = new ArrayList(5);
1181 //              IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID);
1182 //              if (extension != null) {
1183 //                      IExtension[] extensions =  extension.getExtensions();
1184 //                      for(int i = 0; i < extensions.length; i++){
1185 //                              IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
1186 //                              for(int j = 0; j < configElements.length; j++){
1187 //                                      String idAttribute = configElements[j].getAttribute("id"); //$NON-NLS-1$
1188 //                                      if (idAttribute != null) containerIDList.add(idAttribute);
1189 //                              }
1190 //                      }       
1191 //              }
1192 //              String[] containerIDs = new String[containerIDList.size()];
1193 //              containerIDList.toArray(containerIDs);
1194 //              return containerIDs;
1195 //      }       
1196
1197         /**
1198          * Returns the File to use for saving and restoring the last built state for the given project.
1199          */
1200         private File getSerializationFile(IProject project) {
1201                 if (!project.exists()) return null;
1202                 IPath workingLocation = project.getWorkingLocation(JavaCore.PLUGIN_ID);
1203                 return workingLocation.append("state.dat").toFile(); //$NON-NLS-1$
1204         }
1205         /*
1206          * Returns the temporary cache for newly opened elements for the current thread.
1207          * Creates it if not already created.
1208          */
1209         public HashMap getTemporaryCache() {
1210                 HashMap result = (HashMap)this.temporaryCache.get();
1211                 if (result == null) {
1212                         result = new HashMap();
1213                         this.temporaryCache.set(result);
1214                 }
1215                 return result;
1216         }
1217         /**
1218          * Returns the open ZipFile at the given location. If the ZipFile
1219          * does not yet exist, it is created, opened, and added to the cache
1220          * of open ZipFiles. The location must be a absolute path.
1221          *
1222          * @exception CoreException If unable to create/open the ZipFile
1223          */
1224         public ZipFile getZipFile(IPath path) throws CoreException {
1225                         
1226                 synchronized(this.zipFiles) { // TODO:  use PeThreadObject which does synchronization
1227                         Thread currentThread = Thread.currentThread();
1228                         HashMap map = null;
1229                         ZipFile zipFile;
1230                         if ((map = (HashMap)this.zipFiles.get(currentThread)) != null 
1231                                         && (zipFile = (ZipFile)map.get(path)) != null) {
1232                                         
1233                                 return zipFile;
1234                         }
1235                         String fileSystemPath= null;
1236                         IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
1237                         IResource file = root.findMember(path);
1238                         if (path.isAbsolute() && file != null) {
1239                                 if (file == null) { // external file
1240                                         fileSystemPath= path.toOSString();
1241                                 } else { // internal resource (not an IFile or not existing)
1242                                         IPath location;
1243                                         if (file.getType() != IResource.FILE || (location = file.getLocation()) == null) {
1244                                                 throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
1245                                         }
1246                                         fileSystemPath= location.toOSString();
1247                                 }
1248                         } else if (!path.isAbsolute()) {
1249                                 file= root.getFile(path);
1250                                 if (file == null || file.getType() != IResource.FILE) {
1251                                         throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
1252                                 }
1253                                 IPath location = file.getLocation();
1254                                 if (location == null) {
1255                                         throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
1256                                 }
1257                                 fileSystemPath= location.toOSString();
1258                         } else {
1259                                 fileSystemPath= path.toOSString();
1260                         }
1261         
1262                         try {
1263                                 if (ZIP_ACCESS_VERBOSE) {
1264                                         System.out.println("(" + currentThread + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + fileSystemPath ); //$NON-NLS-1$ //$NON-NLS-2$
1265                                 }
1266                                 zipFile = new ZipFile(fileSystemPath);
1267                                 if (map != null) {
1268                                         map.put(path, zipFile);
1269                                 }
1270                                 return zipFile;
1271                         } catch (IOException e) {
1272                                 throw new CoreException(new Status(Status.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("status.IOException"), e)); //$NON-NLS-1$
1273                         }
1274                 }
1275         }
1276         /*
1277          * Returns whether there is a temporary cache for the current thread.
1278          */
1279         public boolean hasTemporaryCache() {
1280                 return this.temporaryCache.get() != null;
1281         }
1282 //      public void loadVariablesAndContainers() throws CoreException {
1283 //
1284 //              // backward compatibility, consider persistent property 
1285 //              QualifiedName qName = new QualifiedName(PHPCore.PLUGIN_ID, "variables"); //$NON-NLS-1$
1286 //              String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName);
1287 //              
1288 //              try {
1289 //                      if (xmlString != null){
1290 //                              StringReader reader = new StringReader(xmlString);
1291 //                              Element cpElement;
1292 //                              try {
1293 //                                      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
1294 //                                      cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
1295 //                              } catch(SAXException e) {
1296 //                                      return;
1297 //                              } catch(ParserConfigurationException e){
1298 //                                      return;
1299 //                              } finally {
1300 //                                      reader.close();
1301 //                              }
1302 //                              if (cpElement == null) return;
1303 //                              if (!cpElement.getNodeName().equalsIgnoreCase("variables")) { //$NON-NLS-1$
1304 //                                      return;
1305 //                              }
1306 //                              
1307 //                              NodeList list= cpElement.getChildNodes();
1308 //                              int length= list.getLength();
1309 //                              for (int i= 0; i < length; ++i) {
1310 //                                      Node node= list.item(i);
1311 //                                      short type= node.getNodeType();
1312 //                                      if (type == Node.ELEMENT_NODE) {
1313 //                                              Element element= (Element) node;
1314 //                                              if (element.getNodeName().equalsIgnoreCase("variable")) { //$NON-NLS-1$
1315 //                                                      variablePut( 
1316 //                                                              element.getAttribute("name"), //$NON-NLS-1$
1317 //                                                              new Path(element.getAttribute("path"))); //$NON-NLS-1$
1318 //                                              }
1319 //                                      }
1320 //                              }
1321 //                      }
1322 //              } catch(IOException e){
1323 //              } finally {
1324 //                      if (xmlString != null){
1325 //                              ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one
1326 //                      }
1327 //                      
1328 //              }
1329 //              
1330 //              // load variables and containers from preferences into cache
1331 //              Preferences preferences = PHPCore.getPlugin().getPluginPreferences();
1332 //
1333 //              // only get variable from preferences not set to their default
1334 //              String[] propertyNames = preferences.propertyNames();
1335 //              int variablePrefixLength = CP_VARIABLE_PREFERENCES_PREFIX.length();
1336 //              for (int i = 0; i < propertyNames.length; i++){
1337 //                      String propertyName = propertyNames[i];
1338 //                      if (propertyName.startsWith(CP_VARIABLE_PREFERENCES_PREFIX)){
1339 //                              String varName = propertyName.substring(variablePrefixLength);
1340 //                              IPath varPath = new Path(preferences.getString(propertyName).trim());
1341 //                              
1342 //                              Variables.put(varName, varPath); 
1343 //                              PreviousSessionVariables.put(varName, varPath);
1344 //                      }
1345 //                      if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)){
1346 //                              recreatePersistedContainer(propertyName, preferences.getString(propertyName), true/*add to container values*/);
1347 //                      }
1348 //              }
1349 //              // override persisted values for variables which have a registered initializer
1350 //              String[] registeredVariables = getRegisteredVariableNames();
1351 //              for (int i = 0; i < registeredVariables.length; i++) {
1352 //                      String varName = registeredVariables[i];
1353 //                      Variables.put(varName, null); // reset variable, but leave its entry in the Map, so it will be part of variable names.
1354 //              }
1355 //              // override persisted values for containers which have a registered initializer
1356 //              String[] registeredContainerIDs = getRegisteredContainerIDs();
1357 //              for (int i = 0; i < registeredContainerIDs.length; i++) {
1358 //                      String containerID = registeredContainerIDs[i];
1359 //                      Iterator projectIterator = Containers.keySet().iterator();
1360 //                      while (projectIterator.hasNext()){
1361 //                              IJavaProject project = (IJavaProject)projectIterator.next();
1362 //                              Map projectContainers = (Map)Containers.get(project);
1363 //                              if (projectContainers != null){
1364 //                                      Iterator containerIterator = projectContainers.keySet().iterator();
1365 //                                      while (containerIterator.hasNext()){
1366 //                                              IPath containerPath = (IPath)containerIterator.next();
1367 //                                              if (containerPath.segment(0).equals(containerID)) { // registered container
1368 //                                                      projectContainers.put(containerPath, null); // reset container value, but leave entry in Map
1369 //                                              }
1370 //                                      }
1371 //                              }
1372 //                      }
1373 //              }
1374 //      }
1375
1376         /**
1377          * Merged all awaiting deltas.
1378          */
1379         public IJavaElementDelta mergeDeltas(Collection deltas) {
1380                 if (deltas.size() == 0) return null;
1381                 if (deltas.size() == 1) return (IJavaElementDelta)deltas.iterator().next();
1382                 
1383                 if (DeltaProcessor.VERBOSE) {
1384                         System.out.println("MERGING " + deltas.size() + " DELTAS ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1385                 }
1386                 
1387                 Iterator iterator = deltas.iterator();
1388                 IJavaElement javaModel = this.getJavaModel();
1389                 JavaElementDelta rootDelta = new JavaElementDelta(javaModel);
1390                 boolean insertedTree = false;
1391                 while (iterator.hasNext()) {
1392                         JavaElementDelta delta = (JavaElementDelta)iterator.next();
1393                         if (DeltaProcessor.VERBOSE) {
1394                                 System.out.println(delta.toString());
1395                         }
1396                         IJavaElement element = delta.getElement();
1397                         if (javaModel.equals(element)) {
1398                                 IJavaElementDelta[] children = delta.getAffectedChildren();
1399                                 for (int j = 0; j < children.length; j++) {
1400                                         JavaElementDelta projectDelta = (JavaElementDelta) children[j];
1401                                         rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta);
1402                                         insertedTree = true;
1403                                 }
1404                                 IResourceDelta[] resourceDeltas = delta.getResourceDeltas();
1405                                 if (resourceDeltas != null) {
1406                                         for (int i = 0, length = resourceDeltas.length; i < length; i++) {
1407                                                 rootDelta.addResourceDelta(resourceDeltas[i]);
1408                                                 insertedTree = true;
1409                                         }
1410                                 }
1411                         } else {
1412                                 rootDelta.insertDeltaTree(element, delta);
1413                                 insertedTree = true;
1414                         }
1415                 }
1416                 if (insertedTree) {
1417                         return rootDelta;
1418                 }
1419                 else {
1420                         return null;
1421                 }
1422         }       
1423
1424         /**
1425          *  Returns the info for this element without
1426          *  disturbing the cache ordering.
1427          */ // TODO: should be synchronized, could answer unitialized info or if cache is in middle of rehash, could even answer distinct element info
1428         protected Object peekAtInfo(IJavaElement element) {
1429                 return this.cache.peekAtInfo(element);
1430         }
1431
1432         /**
1433          * @see ISaveParticipant
1434          */
1435         public void prepareToSave(ISaveContext context) throws CoreException {
1436         }
1437         
1438         protected void putInfo(IJavaElement element, Object info) {
1439                 this.cache.putInfo(element, info);
1440         }
1441         /*
1442          * Puts the infos in the given map (keys are IJavaElements and values are JavaElementInfos)
1443          * in the Java model cache in an atomic way.
1444          * First checks that the info for the opened element (or one of its ancestors) has not been 
1445          * added to the cache. If it is the case, another thread has opened the element (or one of
1446          * its ancestors). So returns without updating the cache.
1447          */
1448         protected synchronized void putInfos(IJavaElement openedElement, Map newElements) {
1449                 // remove children
1450                 Object existingInfo = this.cache.peekAtInfo(openedElement);
1451                 if (openedElement instanceof IParent && existingInfo instanceof JavaElementInfo) {
1452                         IJavaElement[] children = ((JavaElementInfo)existingInfo).getChildren();
1453                         for (int i = 0, size = children.length; i < size; ++i) {
1454                                 JavaElement child = (JavaElement) children[i];
1455                                 try {
1456                                         child.close();
1457                                 } catch (JavaModelException e) {
1458                                         // ignore
1459                                 }
1460                         }
1461                 }
1462         
1463                 Iterator iterator = newElements.keySet().iterator();
1464                 while (iterator.hasNext()) {
1465                         IJavaElement element = (IJavaElement)iterator.next();
1466                         Object info = newElements.get(element);
1467                         this.cache.putInfo(element, info);
1468                 }
1469         }
1470         /**
1471          * Reads the build state for the relevant project.
1472          */
1473         protected Object readState(IProject project) throws CoreException {
1474                 File file = getSerializationFile(project);
1475                 if (file != null && file.exists()) {
1476                         try {
1477                                 DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
1478                                 try {
1479                                         String pluginID= in.readUTF();
1480                                         if (!pluginID.equals(JavaCore.PLUGIN_ID))
1481                                                 throw new IOException(Util.bind("build.wrongFileFormat")); //$NON-NLS-1$
1482                                         String kind= in.readUTF();
1483                                         if (!kind.equals("STATE")) //$NON-NLS-1$
1484                                                 throw new IOException(Util.bind("build.wrongFileFormat")); //$NON-NLS-1$
1485                                         if (in.readBoolean())
1486                                                 return PHPBuilder.readState(project, in);
1487                                         if (PHPBuilder.DEBUG)
1488                                                 System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$
1489                                 } finally {
1490                                         in.close();
1491                                 }
1492                         } catch (Exception e) {
1493                                 e.printStackTrace();
1494                                 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$
1495                         }
1496                 }
1497                 return null;
1498         }
1499
1500 //      public static void recreatePersistedContainer(String propertyName, String containerString, boolean addToContainerValues) {
1501 //              int containerPrefixLength = CP_CONTAINER_PREFERENCES_PREFIX.length();
1502 //              int index = propertyName.indexOf('|', containerPrefixLength);
1503 //              if (containerString != null) containerString = containerString.trim();
1504 //              if (index > 0) {
1505 //                      final String projectName = propertyName.substring(containerPrefixLength, index).trim();
1506 //                      JavaProject project = (JavaProject)getJavaModelManager().getJavaModel().getJavaProject(projectName);
1507 //                      final IPath containerPath = new Path(propertyName.substring(index+1).trim());
1508 //                      
1509 //                      if (containerString == null || containerString.equals(CP_ENTRY_IGNORE)) {
1510 //                              containerPut(project, containerPath, null);
1511 //                      } else {
1512 //                              final IClasspathEntry[] containerEntries = project.decodeClasspath(containerString, false, false);
1513 //                              if (containerEntries != null && containerEntries != JavaProject.INVALID_CLASSPATH) {
1514 //                                      IClasspathContainer container = new IClasspathContainer() {
1515 //                                              public IClasspathEntry[] getClasspathEntries() {
1516 //                                                      return containerEntries;
1517 //                                              }
1518 //                                              public String getDescription() {
1519 //                                                      return "Persisted container ["+containerPath+" for project ["+ projectName+"]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
1520 //                                              }
1521 //                                              public int getKind() {
1522 //                                                      return 0; 
1523 //                                              }
1524 //                                              public IPath getPath() {
1525 //                                                      return containerPath;
1526 //                                              }
1527 //                                              public String toString() {
1528 //                                                      return getDescription();
1529 //                                              }
1530 //
1531 //                                      };
1532 //                                      if (addToContainerValues) {
1533 //                                              containerPut(project, containerPath, container);
1534 //                                      }
1535 //                                      Map projectContainers = (Map)PreviousSessionContainers.get(project);
1536 //                                      if (projectContainers == null){
1537 //                                              projectContainers = new HashMap(1);
1538 //                                              PreviousSessionContainers.put(project, projectContainers);
1539 //                                      }
1540 //                                      projectContainers.put(containerPath, container);
1541 //                              }
1542 //                      }
1543 //              }
1544 //      }
1545
1546         /**
1547          * Registers the given delta with this manager.
1548          */
1549         protected void registerJavaModelDelta(IJavaElementDelta delta) {
1550                 this.javaModelDeltas.add(delta);
1551         }
1552         
1553         /**
1554          * Remembers the given scope in a weak set
1555          * (so no need to remove it: it will be removed by the garbage collector)
1556          */
1557 //      public void rememberScope(AbstractSearchScope scope) {
1558 //              // NB: The value has to be null so as to not create a strong reference on the scope
1559 //              this.scopes.put(scope, null); 
1560 //      }
1561
1562         /**
1563          * removeElementChangedListener method comment.
1564          */
1565         public void removeElementChangedListener(IElementChangedListener listener) {
1566                 
1567                 for (int i = 0; i < this.elementChangedListenerCount; i++){
1568                         
1569                         if (this.elementChangedListeners[i].equals(listener)){
1570                                 
1571                                 // need to clone defensively since we might be in the middle of listener notifications (#fire)
1572                                 int length = this.elementChangedListeners.length;
1573                                 IElementChangedListener[] newListeners = new IElementChangedListener[length];
1574                                 System.arraycopy(this.elementChangedListeners, 0, newListeners, 0, i);
1575                                 int[] newMasks = new int[length];
1576                                 System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, 0, i);
1577                                 
1578                                 // copy trailing listeners
1579                                 int trailingLength = this.elementChangedListenerCount - i - 1;
1580                                 if (trailingLength > 0){
1581                                         System.arraycopy(this.elementChangedListeners, i+1, newListeners, i, trailingLength);
1582                                         System.arraycopy(this.elementChangedListenerMasks, i+1, newMasks, i, trailingLength);
1583                                 }
1584                                 
1585                                 // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto
1586                                 // the original ones)
1587                                 this.elementChangedListeners = newListeners;
1588                                 this.elementChangedListenerMasks = newMasks;
1589                                 this.elementChangedListenerCount--;
1590                                 return;
1591                         }
1592                 }
1593         }
1594         
1595 //      PROTECTED VOID REMOVEINFO(IJAVAELEMENT ELEMENT) {
1596 //              THIS.CACHE.REMOVEINFO(ELEMENT);
1597 //      }
1598         /*
1599          * Removes all cached info for the given element (including all children)
1600          * from the cache.
1601          * Returns the info for the given element, or null if it was closed.
1602          */
1603         public synchronized Object removeInfoAndChildren(JavaElement element) throws JavaModelException {
1604                 Object info = this.cache.peekAtInfo(element);
1605                 if (info != null) {
1606                         boolean wasVerbose = false;
1607                         try {
1608                                 if (VERBOSE) {
1609                                         System.out.println("CLOSING Element ("+ Thread.currentThread()+"): " + element.toStringWithAncestors());  //$NON-NLS-1$//$NON-NLS-2$
1610                                         wasVerbose = true;
1611                                         VERBOSE = false;
1612                                 }
1613                                 element.closing(info);
1614                                 if (element instanceof IParent && info instanceof JavaElementInfo) {
1615                                         IJavaElement[] children = ((JavaElementInfo)info).getChildren();
1616                                         for (int i = 0, size = children.length; i < size; ++i) {
1617                                                 JavaElement child = (JavaElement) children[i];
1618                                                 child.close();
1619                                         }
1620                                 }
1621                                 this.cache.removeInfo(element);
1622                                 if (wasVerbose) {
1623                                         System.out.println("-> Package cache size = " + this.cache.pkgSize()); //$NON-NLS-1$
1624                                         System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(this.cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
1625                                 }
1626                         } finally {
1627                                 JavaModelManager.VERBOSE = wasVerbose;
1628                         }
1629                         return info;
1630                 }
1631                 return null;
1632         }       
1633         public void removePerProjectInfo(JavaProject javaProject) {
1634                 synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock
1635                         IProject project = javaProject.getProject();
1636                         PerProjectInfo info= (PerProjectInfo) perProjectInfo.get(project);
1637                         if (info != null) {
1638                                 perProjectInfo.remove(project);
1639                         }
1640                 }
1641         }
1642         /*
1643          * Resets the temporary cache for newly created elements to null.
1644          */
1645         public void resetTemporaryCache() {
1646                 this.temporaryCache.set(null);
1647         }
1648         /**
1649          * @see ISaveParticipant
1650          */
1651         public void rollback(ISaveContext context){
1652         }
1653
1654         private void saveState(PerProjectInfo info, ISaveContext context) throws CoreException {
1655
1656                 // passed this point, save actions are non trivial
1657                 if (context.getKind() == ISaveContext.SNAPSHOT) return;
1658                 
1659                 // save built state
1660                 if (info.triedRead) saveBuiltState(info);
1661         }
1662         
1663         /**
1664          * Saves the built state for the project.
1665          */
1666         private void saveBuiltState(PerProjectInfo info) throws CoreException {
1667                 if (PHPBuilder.DEBUG)
1668                         System.out.println(Util.bind("build.saveStateProgress", info.project.getName())); //$NON-NLS-1$
1669                 File file = getSerializationFile(info.project);
1670                 if (file == null) return;
1671                 long t = System.currentTimeMillis();
1672                 try {
1673                         DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
1674                         try {
1675                                 out.writeUTF(JavaCore.PLUGIN_ID);
1676                                 out.writeUTF("STATE"); //$NON-NLS-1$
1677                                 if (info.savedState == null) {
1678                                         out.writeBoolean(false);
1679                                 } else {
1680                                         out.writeBoolean(true);
1681                                         PHPBuilder.writeState(info.savedState, out);
1682                                 }
1683                         } finally {
1684                                 out.close();
1685                         }
1686                 } catch (RuntimeException e) {
1687                         try {file.delete();} catch(SecurityException se) {}
1688                         throw new CoreException(
1689                                 new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
1690                                         Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$
1691                 } catch (IOException e) {
1692                         try {file.delete();} catch(SecurityException se) {}
1693                         throw new CoreException(
1694                                 new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
1695                                         Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$
1696                 }
1697                 if (PHPBuilder.DEBUG) {
1698                         t = System.currentTimeMillis() - t;
1699                         System.out.println(Util.bind("build.saveStateComplete", String.valueOf(t))); //$NON-NLS-1$
1700                 }
1701         }
1702
1703         /**
1704          * @see ISaveParticipant
1705          */
1706         public void saving(ISaveContext context) throws CoreException {
1707         
1708                 IProject savedProject = context.getProject();
1709                 if (savedProject != null) {
1710                         if (!JavaProject.hasJavaNature(savedProject)) return; // ignore
1711                         PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */);
1712                         saveState(info, context);
1713                         return;
1714                 }
1715
1716                 ArrayList vStats= null; // lazy initialized
1717                 for (Iterator iter =  perProjectInfo.values().iterator(); iter.hasNext();) {
1718                         try {
1719                                 PerProjectInfo info = (PerProjectInfo) iter.next();
1720                                 saveState(info, context);
1721                         } catch (CoreException e) {
1722                                 if (vStats == null)
1723                                         vStats= new ArrayList();
1724                                 vStats.add(e.getStatus());
1725                         }
1726                 }
1727                 if (vStats != null) {
1728                         IStatus[] stats= new IStatus[vStats.size()];
1729                         vStats.toArray(stats);
1730                         throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Util.bind("build.cannotSaveStates"), null)); //$NON-NLS-1$
1731                 }
1732         }
1733
1734         /**
1735          * Record the order in which to build the java projects (batch build). This order is based
1736          * on the projects classpath settings.
1737          */
1738         protected void setBuildOrder(String[] javaBuildOrder) throws JavaModelException {
1739
1740                 // optional behaviour
1741                 // possible value of index 0 is Compute
1742                 if (!JavaCore.COMPUTE.equals(JavaCore.getOption(JavaCore.CORE_JAVA_BUILD_ORDER))) return; // cannot be customized at project level
1743                 
1744                 if (javaBuildOrder == null || javaBuildOrder.length <= 1) return;
1745                 
1746                 IWorkspace workspace = ResourcesPlugin.getWorkspace();
1747                 IWorkspaceDescription description = workspace.getDescription();
1748                 String[] wksBuildOrder = description.getBuildOrder();
1749
1750                 String[] newOrder;
1751                 if (wksBuildOrder == null){
1752                         newOrder = javaBuildOrder;
1753                 } else {
1754                         // remove projects which are already mentionned in java builder order
1755                         int javaCount = javaBuildOrder.length;
1756                         HashMap newSet = new HashMap(javaCount); // create a set for fast check
1757                         for (int i = 0; i < javaCount; i++){
1758                                 newSet.put(javaBuildOrder[i], javaBuildOrder[i]);
1759                         }
1760                         int removed = 0;
1761                         int oldCount = wksBuildOrder.length;
1762                         for (int i = 0; i < oldCount; i++){
1763                                 if (newSet.containsKey(wksBuildOrder[i])){
1764                                         wksBuildOrder[i] = null;
1765                                         removed++;
1766                                 }
1767                         }
1768                         // add Java ones first
1769                         newOrder = new String[oldCount - removed + javaCount];
1770                         System.arraycopy(javaBuildOrder, 0, newOrder, 0, javaCount); // java projects are built first
1771
1772                         // copy previous items in their respective order
1773                         int index = javaCount;
1774                         for (int i = 0; i < oldCount; i++){
1775                                 if (wksBuildOrder[i] != null){
1776                                         newOrder[index++] = wksBuildOrder[i];
1777                                 }
1778                         }
1779                 }
1780                 // commit the new build order out
1781                 description.setBuildOrder(newOrder);
1782                 try {
1783                         workspace.setDescription(description);
1784                 } catch(CoreException e){
1785                         throw new JavaModelException(e);
1786                 }
1787         }
1788
1789         /**
1790          * Sets the last built state for the given project, or null to reset it.
1791          */
1792         public void setLastBuiltState(IProject project, Object state) {
1793                 if (!JavaProject.hasJavaNature(project)) return; // should never be requested on non-Java projects
1794                 PerProjectInfo info = getPerProjectInfo(project, true /*create if missing*/);
1795                 info.triedRead = true; // no point trying to re-read once using setter
1796                 info.savedState = state;
1797                 if (state == null) { // delete state file to ensure a full build happens if the workspace crashes
1798                         try {
1799                                 File file = getSerializationFile(project);
1800                                 if (file != null && file.exists())
1801                                         file.delete();
1802                         } catch(SecurityException se) {}
1803                 }
1804         }
1805
1806         public void shutdown () {
1807 //      TODO khartlage temp-del
1808 //              if (this.deltaProcessor.indexManager != null){ // no more indexing
1809 //                      this.deltaProcessor.indexManager.shutdown();
1810 //              }
1811                 try {
1812                         IJavaModel model = this.getJavaModel();
1813                         if (model != null) {
1814
1815                                 model.close();
1816                         }
1817                 } catch (JavaModelException e) {
1818                 }
1819         }
1820
1821         /**
1822          * Turns the firing mode to on. That is, deltas that are/have been
1823          * registered will be fired.
1824          */
1825         public void startDeltas() {
1826                 this.isFiring= true;
1827         }
1828
1829         /**
1830          * Turns the firing mode to off. That is, deltas that are/have been
1831          * registered will not be fired until deltas are started again.
1832          */
1833         public void stopDeltas() {
1834                 this.isFiring= false;
1835         }
1836         
1837         /**
1838          * Update Java Model given some delta
1839          */
1840 //      public void updateJavaModel(IJavaElementDelta customDelta) {
1841 //
1842 //              if (customDelta == null){
1843 //                      for (int i = 0, length = this.javaModelDeltas.size(); i < length; i++){
1844 //                              IJavaElementDelta delta = (IJavaElementDelta)this.javaModelDeltas.get(i);
1845 //                              this.modelUpdater.processJavaDelta(delta);
1846 //                      }
1847 //              } else {
1848 //                      this.modelUpdater.processJavaDelta(customDelta);
1849 //              }
1850 //      }
1851
1852
1853         
1854         public static IPath variableGet(String variableName){
1855                 return (IPath)Variables.get(variableName);
1856         }
1857
1858         public static String[] variableNames(){
1859                 int length = Variables.size();
1860                 String[] result = new String[length];
1861                 Iterator vars = Variables.keySet().iterator();
1862                 int index = 0;
1863                 while (vars.hasNext()) {
1864                         result[index++] = (String) vars.next();
1865                 }
1866                 return result;
1867         }
1868         
1869         public static void variablePut(String variableName, IPath variablePath){                
1870
1871                 // update cache - do not only rely on listener refresh          
1872                 if (variablePath == null) {
1873                         Variables.remove(variableName);
1874                         PreviousSessionVariables.remove(variableName);
1875                 } else {
1876                         Variables.put(variableName, variablePath);
1877                 }
1878
1879                 // do not write out intermediate initialization value
1880                 if (variablePath == JavaModelManager.VariableInitializationInProgress){
1881                         return;
1882                 } 
1883                 Preferences preferences = JavaCore.getPlugin().getPluginPreferences();
1884                 String variableKey = CP_VARIABLE_PREFERENCES_PREFIX+variableName;
1885                 String variableString = variablePath == null ? CP_ENTRY_IGNORE : variablePath.toString();
1886                 preferences.setDefault(variableKey, CP_ENTRY_IGNORE); // use this default to get rid of removed ones
1887                 preferences.setValue(variableKey, variableString);
1888                 JavaCore.getPlugin().savePluginPreferences();
1889         }
1890         /*
1891          * Returns all the working copies which have the given owner.
1892          * Adds the working copies of the primary owner if specified.
1893          * Returns null if it has none.
1894          */
1895         public ICompilationUnit[] getWorkingCopies(WorkingCopyOwner owner, boolean addPrimary) {
1896                 synchronized(perWorkingCopyInfos) {
1897                         ICompilationUnit[] primaryWCs = addPrimary && owner != DefaultWorkingCopyOwner.PRIMARY 
1898                                 ? getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false) 
1899                                 : null;
1900                         Map workingCopyToInfos = (Map)perWorkingCopyInfos.get(owner);
1901                         if (workingCopyToInfos == null) return primaryWCs;
1902                         int primaryLength = primaryWCs == null ? 0 : primaryWCs.length;
1903                         int size = workingCopyToInfos.size(); // note size is > 0 otherwise pathToPerWorkingCopyInfos would be null
1904                         ICompilationUnit[] result = new ICompilationUnit[primaryLength + size];
1905                         if (primaryWCs != null) {
1906                                 System.arraycopy(primaryWCs, 0, result, 0, primaryLength);
1907                         }
1908                         Iterator iterator = workingCopyToInfos.values().iterator();
1909                         int index = primaryLength;
1910                         while(iterator.hasNext()) {
1911                                 result[index++] = ((JavaModelManager.PerWorkingCopyInfo)iterator.next()).getWorkingCopy();
1912                         }
1913                         return result;
1914                 }               
1915         }
1916 }