b345248e39f44292c6377d0b12df71d6c19bb419
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpdt / internal / core / builder / PHPBuilder.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.builder;
12 import java.io.DataInputStream;
13 import java.io.DataOutputStream;
14 import java.io.IOException;
15 import java.util.ArrayList;
16 import java.util.Date;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.Map;
20
21 import net.sourceforge.phpdt.core.IClasspathEntry;
22 import net.sourceforge.phpdt.core.IJavaModelMarker;
23 import net.sourceforge.phpdt.core.JavaCore;
24 import net.sourceforge.phpdt.core.JavaModelException;
25 import net.sourceforge.phpdt.core.compiler.CharOperation;
26 import net.sourceforge.phpdt.internal.core.JavaModel;
27 import net.sourceforge.phpdt.internal.core.JavaModelManager;
28 import net.sourceforge.phpdt.internal.core.JavaProject;
29 import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable;
30 import net.sourceforge.phpdt.internal.core.util.Util;
31 import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
32 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
33 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
34
35 import org.eclipse.core.resources.IFile;
36 import org.eclipse.core.resources.IMarker;
37 import org.eclipse.core.resources.IProject;
38 import org.eclipse.core.resources.IResource;
39 import org.eclipse.core.resources.IResourceChangeEvent;
40 import org.eclipse.core.resources.IResourceDelta;
41 import org.eclipse.core.resources.IResourceVisitor;
42 import org.eclipse.core.resources.IWorkspaceRoot;
43 import org.eclipse.core.resources.IncrementalProjectBuilder;
44 import org.eclipse.core.runtime.CoreException;
45 import org.eclipse.core.runtime.IPath;
46 import org.eclipse.core.runtime.IProgressMonitor;
47 import org.eclipse.core.runtime.OperationCanceledException;
48 public class PHPBuilder extends IncrementalProjectBuilder {
49   IProject currentProject;
50   JavaProject javaProject;
51   IWorkspaceRoot workspaceRoot;
52   NameEnvironment nameEnvironment;
53   SimpleLookupTable binaryLocationsPerProject; // maps a project to its binary
54   // resources (output folders,
55   // class folders, zip/jar files)
56   State lastState;
57   BuildNotifier notifier;
58   char[][] extraResourceFileFilters;
59   String[] extraResourceFolderFilters;
60   public static final String CLASS_EXTENSION = "class"; //$NON-NLS-1$
61   public static boolean DEBUG = false;
62   /**
63    * A list of project names that have been built. This list is used to reset
64    * the JavaModel.existingExternalFiles cache when a build cycle begins so
65    * that deleted external jars are discovered.
66    */
67   static ArrayList builtProjects = null;
68   public static IMarker[] getProblemsFor(IResource resource) {
69     try {
70       if (resource != null && resource.exists())
71         return resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
72             false, IResource.DEPTH_INFINITE);
73     } catch (CoreException e) {
74     } // assume there are no problems
75     return new IMarker[0];
76   }
77   public static IMarker[] getTasksFor(IResource resource) {
78     try {
79       if (resource != null && resource.exists())
80         return resource.findMarkers(IJavaModelMarker.TASK_MARKER, false,
81             IResource.DEPTH_INFINITE);
82     } catch (CoreException e) {
83     } // assume there are no tasks
84     return new IMarker[0];
85   }
86   public static void finishedBuilding(IResourceChangeEvent event) {
87     BuildNotifier.resetProblemCounters();
88   }
89   public static void removeProblemsFor(IResource resource) {
90     try {
91       if (resource != null && resource.exists())
92         resource.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
93             false, IResource.DEPTH_INFINITE);
94     } catch (CoreException e) {
95     } // assume there were no problems
96   }
97   public static void removeTasksFor(IResource resource) {
98     try {
99       if (resource != null && resource.exists())
100         resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false,
101             IResource.DEPTH_INFINITE);
102     } catch (CoreException e) {
103     } // assume there were no problems
104   }
105   public static void removeProblemsAndTasksFor(IResource resource) {
106     try {
107       if (resource != null && resource.exists()) {
108         resource.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
109             false, IResource.DEPTH_INFINITE);
110         resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false,
111             IResource.DEPTH_INFINITE);
112       }
113     } catch (CoreException e) {
114     } // assume there were no problems
115   }
116   public static State readState(IProject project, DataInputStream in)
117       throws IOException {
118     return State.read(project, in);
119   }
120   public static void writeState(Object state, DataOutputStream out)
121       throws IOException {
122     ((State) state).write(out);
123   }
124   public PHPBuilder() {
125   }
126   protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor)
127       throws CoreException {
128     this.currentProject = getProject();
129     if (currentProject == null || !currentProject.isAccessible())
130       return new IProject[0];
131     if (DEBUG)
132       System.out.println("\nStarting build of " + currentProject.getName() //$NON-NLS-1$
133           + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
134     this.notifier = new BuildNotifier(monitor, currentProject);
135     notifier.begin();
136     boolean ok = false;
137     try {
138       notifier.checkCancel();
139       initializeBuilder();
140       if (isWorthBuilding()) {
141         if (kind == FULL_BUILD) {
142           processFullPHPIndex(currentProject, monitor);
143           buildAll();
144         } else {
145           if ((this.lastState = getLastState(currentProject)) == null) {
146             if (DEBUG)
147               System.out
148                   .println("Performing full build since last saved state was not found"); //$NON-NLS-1$
149             processFullPHPIndex(currentProject, monitor);
150             buildAll();
151 //          } else if (hasClasspathChanged()) {
152 //            // if the output location changes, do not delete the binary files
153 //            // from old location
154 //            // the user may be trying something
155 //            buildAll();
156           } else if (nameEnvironment.sourceLocations.length > 0) {
157             // if there is no source to compile & no classpath changes then we
158             // are done
159             SimpleLookupTable deltas = findDeltas();
160             if (deltas == null)
161               buildAll();
162             else if (deltas.elementSize > 0)
163               buildDeltas(deltas);
164             else if (DEBUG)
165               System.out.println("Nothing to build since deltas were empty"); //$NON-NLS-1$
166           } else {
167             if (hasStructuralDelta()) { // double check that a jar file didn't
168               // get replaced in a binary project
169               processFullPHPIndex(currentProject, monitor);
170               buildAll();
171             } else {
172               if (DEBUG)
173                 System.out
174                     .println("Nothing to build since there are no source folders and no deltas"); //$NON-NLS-1$
175               lastState.tagAsNoopBuild();
176             }
177           }
178         }
179         ok = true;
180       }
181     } catch (CoreException e) {
182       Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$
183       IMarker marker = currentProject
184           .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
185       marker.setAttribute(IMarker.MESSAGE, Util.bind(
186           "build.inconsistentProject", e.getLocalizedMessage())); //$NON-NLS-1$
187       marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
188     } catch (ImageBuilderInternalException e) {
189       Util.log(e.getThrowable(),
190           "JavaBuilder handling ImageBuilderInternalException"); //$NON-NLS-1$
191       IMarker marker = currentProject
192           .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
193       marker.setAttribute(IMarker.MESSAGE, Util.bind(
194           "build.inconsistentProject", e.coreException.getLocalizedMessage())); //$NON-NLS-1$
195       marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
196     } catch (MissingClassFileException e) {
197       // do not log this exception since its thrown to handle aborted compiles
198       // because of missing class files
199       if (DEBUG)
200         System.out.println(Util.bind("build.incompleteClassPath",
201             e.missingClassFile)); //$NON-NLS-1$
202       IMarker marker = currentProject
203           .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
204       marker.setAttribute(IMarker.MESSAGE, Util.bind(
205           "build.incompleteClassPath", e.missingClassFile)); //$NON-NLS-1$
206       marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
207     } catch (MissingSourceFileException e) {
208       // do not log this exception since its thrown to handle aborted compiles
209       // because of missing source files
210       if (DEBUG)
211         System.out.println(Util.bind("build.missingSourceFile",
212             e.missingSourceFile)); //$NON-NLS-1$
213       removeProblemsAndTasksFor(currentProject); // make this the only problem
214       // for this project
215       IMarker marker = currentProject
216           .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
217       marker.setAttribute(IMarker.MESSAGE, Util.bind("build.missingSourceFile",
218           e.missingSourceFile)); //$NON-NLS-1$
219       marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
220     } catch (Exception e) {
221       e.printStackTrace();
222     } finally {
223       if (!ok)
224         // If the build failed, clear the previously built state, forcing a
225         // full build next time.
226         clearLastState();
227       notifier.done();
228       cleanup();
229     }
230     IProject[] requiredProjects = getRequiredProjects(true);
231     if (DEBUG)
232       System.out.println("Finished build of " + currentProject.getName() //$NON-NLS-1$
233           + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
234     return requiredProjects;
235   }
236   /**
237    * Performs a <code>FULL_BUILD</code> by visiting all nodes in the resource
238    * tree under the specified project.
239    * 
240    * @param iProject
241    */
242   private void processFullPHPIndex(final IProject iProject,
243       final IProgressMonitor monitor) {
244     final IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault()
245         .getIndexManager(iProject);
246     // Create resource visitor logic
247     IResourceVisitor myVisitor = new IResourceVisitor() {
248       public boolean visit(IResource resource) throws CoreException {
249         if (resource.getType() == IResource.FILE) {
250           if (monitor.isCanceled()) {
251             throw new OperationCanceledException();
252           }
253           if ((resource.getFileExtension() != null)
254               && PHPFileUtil.isPHPFile((IFile) resource)) {
255             monitor.worked(1);
256             monitor.subTask("Parsing: " + resource.getFullPath());
257             // update indexfile for the project:
258 //            PHPProject nature = (PHPProject) iProject
259 //                .getNature(PHPeclipsePlugin.PHP_NATURE_ID);
260             indexManager.addFile((IFile) resource);
261           }
262         }
263         return true;
264       }
265     };
266     // Process the project using the visitor just created
267     try {
268       //      if (iProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
269       //        thePHPProject = new PHPProject();
270       //        thePHPProject.setProject(iProject);
271       //      }
272       indexManager.initialize();
273       iProject.accept(myVisitor);
274       indexManager.writeFile();
275     } catch (CoreException e) {
276       e.printStackTrace();
277     }
278   }
279   private void buildAll() {
280     notifier.checkCancel();
281     notifier.subTask(Util.bind("build.preparingBuild")); //$NON-NLS-1$
282     if (DEBUG && lastState != null)
283       System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$
284     clearLastState();
285     BatchImageBuilder imageBuilder = new BatchImageBuilder(this);
286     imageBuilder.build();
287     recordNewState(imageBuilder.newState);
288   }
289   private void buildDeltas(SimpleLookupTable deltas) {
290     notifier.checkCancel();
291     notifier.subTask(Util.bind("build.preparingBuild")); //$NON-NLS-1$
292     if (DEBUG && lastState != null)
293       System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$
294     clearLastState(); // clear the previously built state so if the build
295     // fails, a full build will occur next time
296     IncrementalImageBuilder imageBuilder = new IncrementalImageBuilder(this);
297     if (imageBuilder.build(deltas))
298       recordNewState(imageBuilder.newState);
299     else {
300       processFullPHPIndex(currentProject, notifier.monitor);
301       buildAll();
302     }
303   }
304   private void cleanup() {
305     this.nameEnvironment = null;
306     this.binaryLocationsPerProject = null;
307     this.lastState = null;
308     this.notifier = null;
309     this.extraResourceFileFilters = null;
310     this.extraResourceFolderFilters = null;
311   }
312   private void clearLastState() {
313     JavaModelManager.getJavaModelManager().setLastBuiltState(currentProject,
314         null);
315   }
316   boolean filterExtraResource(IResource resource) {
317     if (extraResourceFileFilters != null) {
318       char[] name = resource.getName().toCharArray();
319       for (int i = 0, l = extraResourceFileFilters.length; i < l; i++)
320         if (CharOperation.match(extraResourceFileFilters[i], name, true))
321           return true;
322     }
323     if (extraResourceFolderFilters != null) {
324       IPath path = resource.getProjectRelativePath();
325       String pathName = path.toString();
326       int count = path.segmentCount();
327       if (resource.getType() == IResource.FILE)
328         count--;
329       for (int i = 0, l = extraResourceFolderFilters.length; i < l; i++)
330         if (pathName.indexOf(extraResourceFolderFilters[i]) != -1)
331           for (int j = 0; j < count; j++)
332             if (extraResourceFolderFilters[i].equals(path.segment(j)))
333               return true;
334     }
335     return false;
336   }
337   private SimpleLookupTable findDeltas() {
338     notifier.subTask(Util.bind("build.readingDelta", currentProject.getName())); //$NON-NLS-1$
339     IResourceDelta delta = getDelta(currentProject);
340     SimpleLookupTable deltas = new SimpleLookupTable(3);
341     if (delta != null) {
342       if (delta.getKind() != IResourceDelta.NO_CHANGE) {
343         if (DEBUG)
344           System.out.println("Found source delta for: "
345               + currentProject.getName()); //$NON-NLS-1$
346         deltas.put(currentProject, delta);
347       }
348     } else {
349       if (DEBUG)
350         System.out.println("Missing delta for: " + currentProject.getName()); //$NON-NLS-1$
351       notifier.subTask(""); //$NON-NLS-1$
352       return null;
353     }
354     Object[] keyTable = binaryLocationsPerProject.keyTable;
355     Object[] valueTable = binaryLocationsPerProject.valueTable;
356     nextProject : for (int i = 0, l = keyTable.length; i < l; i++) {
357       IProject p = (IProject) keyTable[i];
358       if (p != null && p != currentProject) {
359         State s = getLastState(p);
360         if (!lastState.wasStructurallyChanged(p, s)) { // see if we can skip
361           // its delta
362           if (s.wasNoopBuild())
363             continue nextProject; // project has no source folders and can be
364           // skipped
365           //                            ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[])
366           // valueTable[i];
367           boolean canSkip = true;
368           //                            for (int j = 0, m = classFoldersAndJars.length; j < m; j++) {
369           //                                    if (classFoldersAndJars[j].isOutputFolder())
370           //                                            classFoldersAndJars[j] = null; // can ignore output folder since
371           // project was not structurally changed
372           //                                    else
373           //                                            canSkip = false;
374           //                            }
375           if (canSkip)
376             continue nextProject; // project has no structural changes in its
377           // output folders
378         }
379         notifier.subTask(Util.bind("build.readingDelta", p.getName())); //$NON-NLS-1$
380         delta = getDelta(p);
381         if (delta != null) {
382           if (delta.getKind() != IResourceDelta.NO_CHANGE) {
383             if (DEBUG)
384               System.out.println("Found binary delta for: " + p.getName()); //$NON-NLS-1$
385             deltas.put(p, delta);
386           }
387         } else {
388           if (DEBUG)
389             System.out.println("Missing delta for: " + p.getName()); //$NON-NLS-1$
390           notifier.subTask(""); //$NON-NLS-1$
391           return null;
392         }
393       }
394     }
395     notifier.subTask(""); //$NON-NLS-1$
396     return deltas;
397   }
398   private State getLastState(IProject project) {
399     return (State) JavaModelManager.getJavaModelManager().getLastBuiltState(
400         project, notifier.monitor);
401   }
402   /*
403    * Return the list of projects for which it requires a resource delta. This
404    * builder's project is implicitly included and need not be specified.
405    * Builders must re-specify the list of interesting projects every time they
406    * are run as this is not carried forward beyond the next build. Missing
407    * projects should be specified but will be ignored until they are added to
408    * the workspace.
409    */
410   private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) {
411     if (javaProject == null || workspaceRoot == null)
412       return new IProject[0];
413     ArrayList projects = new ArrayList();
414     try {
415       IClasspathEntry[] entries = javaProject.getExpandedClasspath(true);
416       for (int i = 0, l = entries.length; i < l; i++) {
417         IClasspathEntry entry = entries[i];
418         IPath path = entry.getPath();
419         IProject p = null;
420         switch (entry.getEntryKind()) {
421           case IClasspathEntry.CPE_PROJECT :
422             p = workspaceRoot.getProject(path.lastSegment()); // missing
423             // projects are
424             // considered too
425             break;
426           case IClasspathEntry.CPE_LIBRARY :
427             if (includeBinaryPrerequisites && path.segmentCount() > 1) {
428               // some binary resources on the class path can come from projects
429               // that are not included in the project references
430               IResource resource = workspaceRoot.findMember(path.segment(0));
431               if (resource instanceof IProject)
432                 p = (IProject) resource;
433             }
434         }
435         if (p != null && !projects.contains(p))
436           projects.add(p);
437       }
438     } catch (JavaModelException e) {
439       return new IProject[0];
440     }
441     IProject[] result = new IProject[projects.size()];
442     projects.toArray(result);
443     return result;
444   }
445 //  private boolean hasClasspathChanged() {
446 //    ClasspathMultiDirectory[] newSourceLocations = nameEnvironment.sourceLocations;
447 //    ClasspathMultiDirectory[] oldSourceLocations = lastState.sourceLocations;
448 //    int newLength = newSourceLocations.length;
449 //    int oldLength = oldSourceLocations.length;
450 //    int n, o;
451 //    for (n = o = 0; n < newLength && o < oldLength; n++, o++) {
452 //      if (newSourceLocations[n].equals(oldSourceLocations[o]))
453 //        continue; // checks source & output folders
454 //      try {
455 //        if (newSourceLocations[n].sourceFolder.members().length == 0) { // added
456 //          // new
457 //          // empty
458 //          // source
459 //          // folder
460 //          o--;
461 //          continue;
462 //        }
463 //      } catch (CoreException ignore) {
464 //      }
465 //      if (DEBUG)
466 //        System.out.println(newSourceLocations[n] + " != "
467 //            + oldSourceLocations[o]); //$NON-NLS-1$
468 //      return true;
469 //    }
470 //    while (n < newLength) {
471 //      try {
472 //        if (newSourceLocations[n].sourceFolder.members().length == 0) { // added
473 //          // new
474 //          // empty
475 //          // source
476 //          // folder
477 //          n++;
478 //          continue;
479 //        }
480 //      } catch (CoreException ignore) {
481 //      }
482 //      if (DEBUG)
483 //        System.out.println("Added non-empty source folder"); //$NON-NLS-1$
484 //      return true;
485 //    }
486 //    if (o < oldLength) {
487 //      if (DEBUG)
488 //        System.out.println("Removed source folder"); //$NON-NLS-1$
489 //      return true;
490 //    }
491 //    //        ClasspathLocation[] newBinaryLocations =
492 //    // nameEnvironment.binaryLocations;
493 //    //        ClasspathLocation[] oldBinaryLocations = lastState.binaryLocations;
494 //    //        newLength = newBinaryLocations.length;
495 //    //        oldLength = oldBinaryLocations.length;
496 //    //        for (n = o = 0; n < newLength && o < oldLength; n++, o++) {
497 //    //                if (newBinaryLocations[n].equals(oldBinaryLocations[o])) continue;
498 //    //                if (DEBUG)
499 //    //                        System.out.println(newBinaryLocations[n] + " != " +
500 //    // oldBinaryLocations[o]); //$NON-NLS-1$
501 //    //                return true;
502 //    //        }
503 //    //        if (n < newLength || o < oldLength) {
504 //    //                if (DEBUG)
505 //    //                        System.out.println("Number of binary folders/jar files has changed");
506 //    // //$NON-NLS-1$
507 //    //                return true;
508 //    //        }
509 //    return false;
510 //  }
511   private boolean hasStructuralDelta() {
512     // handle case when currentProject has only .class file folders and/or jar
513     // files... no source/output folders
514     IResourceDelta delta = getDelta(currentProject);
515     if (delta != null && delta.getKind() != IResourceDelta.NO_CHANGE) {
516       //                ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[])
517       // binaryLocationsPerProject.get(currentProject);
518       //                if (classFoldersAndJars != null) {
519       //                        for (int i = 0, l = classFoldersAndJars.length; i < l; i++) {
520       //                                ClasspathLocation classFolderOrJar = classFoldersAndJars[i]; // either
521       // a .class file folder or a zip/jar file
522       //                                if (classFolderOrJar != null) {
523       //                                        IPath p = classFolderOrJar.getProjectRelativePath();
524       //                                        if (p != null) {
525       //                                                IResourceDelta binaryDelta = delta.findMember(p);
526       //                                                if (binaryDelta != null && binaryDelta.getKind() !=
527       // IResourceDelta.NO_CHANGE)
528       //                                                        return true;
529       //                                        }
530       //                                }
531       //                        }
532       //                }
533     }
534     return false;
535   }
536   private void initializeBuilder() throws CoreException {
537     this.javaProject = (JavaProject) JavaCore.create(currentProject);
538     this.workspaceRoot = currentProject.getWorkspace().getRoot();
539     // Flush the existing external files cache if this is the beginning of a
540     // build cycle
541     String projectName = currentProject.getName();
542     if (builtProjects == null || builtProjects.contains(projectName)) {
543       JavaModel.flushExternalFileCache();
544       builtProjects = new ArrayList();
545     }
546     builtProjects.add(projectName);
547     this.binaryLocationsPerProject = new SimpleLookupTable(3);
548     this.nameEnvironment = new NameEnvironment(workspaceRoot, javaProject,
549         binaryLocationsPerProject);
550     String filterSequence = javaProject.getOption(
551         JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true);
552     char[][] filters = filterSequence != null && filterSequence.length() > 0
553         ? CharOperation.splitAndTrimOn(',', filterSequence.toCharArray())
554         : null;
555     if (filters == null) {
556       this.extraResourceFileFilters = null;
557       this.extraResourceFolderFilters = null;
558     } else {
559       int fileCount = 0, folderCount = 0;
560       for (int i = 0, l = filters.length; i < l; i++) {
561         char[] f = filters[i];
562         if (f.length == 0)
563           continue;
564         if (f[f.length - 1] == '/')
565           folderCount++;
566         else
567           fileCount++;
568       }
569       this.extraResourceFileFilters = new char[fileCount][];
570       this.extraResourceFolderFilters = new String[folderCount];
571       for (int i = 0, l = filters.length; i < l; i++) {
572         char[] f = filters[i];
573         if (f.length == 0)
574           continue;
575         if (f[f.length - 1] == '/')
576           extraResourceFolderFilters[--folderCount] = new String(CharOperation
577               .subarray(f, 0, f.length - 1));
578         else
579           extraResourceFileFilters[--fileCount] = f;
580       }
581     }
582   }
583   private boolean isClasspathBroken(IClasspathEntry[] classpath, IProject p)
584       throws CoreException {
585     if (classpath == JavaProject.INVALID_CLASSPATH) // the .classpath file
586       // could not be read
587       return true;
588     IMarker[] markers = p.findMarkers(
589         IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
590     for (int i = 0, l = markers.length; i < l; i++)
591       if (((Integer) markers[i].getAttribute(IMarker.SEVERITY)).intValue() == IMarker.SEVERITY_ERROR)
592         return true;
593     return false;
594   }
595   private boolean isWorthBuilding() throws CoreException {
596     boolean abortBuilds = JavaCore.ABORT.equals(javaProject.getOption(
597         JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true));
598     if (!abortBuilds)
599       return true;
600     // Abort build only if there are classpath errors
601     //    if (isClasspathBroken(javaProject.getRawClasspath(), currentProject)) {
602     //      if (DEBUG)
603     //        System.out.println("Aborted build because project has classpath errors
604     // (incomplete or involved in cycle)"); //$NON-NLS-1$
605     //
606     //      JavaModelManager.getJavaModelManager().deltaProcessor.addForRefresh(javaProject);
607     //
608     //      removeProblemsAndTasksFor(currentProject); // remove all compilation
609     // problems
610     //
611     //      IMarker marker =
612     // currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
613     //      marker.setAttribute(IMarker.MESSAGE,
614     // Util.bind("build.abortDueToClasspathProblems")); //$NON-NLS-1$
615     //      marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
616     //      return false;
617     //    }
618     // make sure all prereq projects have valid build states... only when
619     // aborting builds since projects in cycles do not have build states
620     // except for projects involved in a 'warning' cycle (see below)
621     IProject[] requiredProjects = getRequiredProjects(false);
622     next : for (int i = 0, l = requiredProjects.length; i < l; i++) {
623       IProject p = requiredProjects[i];
624       if (getLastState(p) == null) {
625         // The prereq project has no build state: if this prereq project has a
626         // 'warning' cycle marker then allow build (see bug id 23357)
627         JavaProject prereq = (JavaProject) JavaCore.create(p);
628         if (prereq.hasCycleMarker()
629             && JavaCore.WARNING.equals(javaProject.getOption(
630                 JavaCore.CORE_CIRCULAR_CLASSPATH, true)))
631           continue;
632         if (DEBUG)
633           System.out.println("Aborted build because prereq project "
634               + p.getName() //$NON-NLS-1$
635               + " was not built"); //$NON-NLS-1$
636         removeProblemsAndTasksFor(currentProject); // make this the only
637         // problem for this project
638         IMarker marker = currentProject
639             .createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
640         marker.setAttribute(IMarker.MESSAGE, isClasspathBroken(prereq
641             .getRawClasspath(), p) ? Util.bind(
642             "build.prereqProjectHasClasspathProblems", p.getName()) //$NON-NLS-1$
643             : Util.bind("build.prereqProjectMustBeRebuilt", p.getName())); //$NON-NLS-1$
644         marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
645         return false;
646       }
647     }
648     return true;
649   }
650   /*
651    * Instruct the build manager that this project is involved in a cycle and
652    * needs to propagate structural changes to the other projects in the cycle.
653    */
654   void mustPropagateStructuralChanges() {
655     HashSet cycleParticipants = new HashSet(3);
656     javaProject.updateCycleParticipants(null, new ArrayList(),
657         cycleParticipants, workspaceRoot, new HashSet(3));
658     IPath currentPath = javaProject.getPath();
659     Iterator i = cycleParticipants.iterator();
660     while (i.hasNext()) {
661       IPath participantPath = (IPath) i.next();
662       if (participantPath != currentPath) {
663         IProject project = this.workspaceRoot.getProject(participantPath
664             .segment(0));
665         if (hasBeenBuilt(project)) {
666           if (DEBUG)
667             System.out
668                 .println("Requesting another build iteration since cycle participant "
669                     + project.getName() //$NON-NLS-1$
670                     + " has not yet seen some structural changes"); //$NON-NLS-1$
671           needRebuild();
672           return;
673         }
674       }
675     }
676   }
677   private void recordNewState(State state) {
678     Object[] keyTable = binaryLocationsPerProject.keyTable;
679     for (int i = 0, l = keyTable.length; i < l; i++) {
680       IProject prereqProject = (IProject) keyTable[i];
681       if (prereqProject != null && prereqProject != currentProject)
682         state.recordStructuralDependency(prereqProject,
683             getLastState(prereqProject));
684     }
685     if (DEBUG)
686       System.out.println("Recording new state : " + state); //$NON-NLS-1$
687     // state.dump();
688     JavaModelManager.getJavaModelManager().setLastBuiltState(currentProject,
689         state);
690   }
691   /**
692    * String representation for debugging purposes
693    */
694   public String toString() {
695     return currentProject == null ? "JavaBuilder for unknown project" //$NON-NLS-1$
696         : "JavaBuilder for " + currentProject.getName(); //$NON-NLS-1$
697   }
698 }