DefaultGlobalModel.java

Index Score
edu.rice.cs.drjava.model
DrJava

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
DECL_COMMENTSComments in declarations
LINE_COMMENTNumber of line comments
EXEC_COMMENTSComments in executable code
FUNCTIONSNumber of function declarations
EXITSProcedure exits
RETURNSNumber of return points from functions
SIZESize of the file in bytes
INTERFACE_COMPLEXITYInterface complexity
BLOCKSNumber of blocks
CYCLOMATICCyclomatic complexity
UNIQUE_OPERANDSNumber of unique operands
PROGRAM_VOCABHalstead program vocabulary
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0020JAVA0020 Field name does not have required form
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
OPERATORSNumber of operators
PROGRAM_LENGTHHalstead program length
OPERANDSNumber of operands
LOGICAL_LINESNumber of statements
JAVA0034JAVA0034 Missing braces in if statement
COMMENTSComment lines
LINESNumber of lines in the source file
PARAMSNumber of formal parameter declarations
ELOCEffective lines of code
JAVA0080JAVA0080 Import declaration not used
LOCLines of code
WHITESPACENumber of whitespace lines
JAVA0117JAVA0117 Missing javadoc: method 'method'
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0018JAVA0018 Method name does not have required form
JAVA0106JAVA0106 Unnecessary import from current package
UNIQUE_OPERATORSNumber of unique operators
JAVA0126JAVA0126 Method declares unchecked exception in throws
COMPARISONSNumber of comparison operators
LOOPSNumber of loops
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0145JAVA0145 Tab character used in source file
/*BEGIN_COPYRIGHT_BLOCK * * Copyright (c) 2001-2008, JavaPLT group at Rice University (drjava@rice.edu) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the names of DrJava, the JavaPLT group, Rice University, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software is Open Source Initiative approved Open Source Software. * Open Source Initative Approved is a trademark of the Open Source Initiative. * * This file is part of DrJava. Download the current version of this project * from http://www.drjava.org/ or http://sourceforge.net/projects/drjava/ * * END_COPYRIGHT_BLOCK*/ package edu.rice.cs.drjava.model; import java.awt.EventQueue; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.OutputStream; import java.io.*; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.StringTokenizer; import java.util.Map; import java.util.TreeMap; import javax.swing.text.BadLocationException; import javax.swing.SwingUtilities; import edu.rice.cs.drjava.DrJava; import edu.rice.cs.drjava.config.OptionConstants; import edu.rice.cs.drjava.config.OptionEvent; import edu.rice.cs.drjava.config.OptionListener; import edu.rice.cs.drjava.config.FileOption; import edu.rice.cs.drjava.model.FileSaveSelector; import edu.rice.cs.drjava.model.compiler.DummyCompilerListener; import edu.rice.cs.drjava.model.definitions.ClassNameNotFoundException; import edu.rice.cs.drjava.model.definitions.DefinitionsDocument; import edu.rice.cs.drjava.model.definitions.InvalidPackageException; import edu.rice.cs.drjava.model.debug.Breakpoint; import edu.rice.cs.drjava.model.debug.Debugger; import edu.rice.cs.drjava.model.debug.DebugException; import edu.rice.cs.drjava.model.debug.NoDebuggerAvailable; import edu.rice.cs.drjava.model.debug.DebugListener; import edu.rice.cs.drjava.model.debug.DebugWatchData; import edu.rice.cs.drjava.model.debug.DebugThreadData; import edu.rice.cs.drjava.model.javadoc.JavadocModel; import edu.rice.cs.drjava.model.javadoc.NoJavadocAvailable; import edu.rice.cs.drjava.model.repl.DefaultInteractionsModel; import edu.rice.cs.drjava.model.repl.DummyInteractionsListener; import edu.rice.cs.drjava.model.repl.InteractionsDocument; import edu.rice.cs.drjava.model.repl.InteractionsDJDocument; import edu.rice.cs.drjava.model.repl.InteractionsListener; import edu.rice.cs.drjava.model.repl.InteractionsScriptModel; import edu.rice.cs.drjava.model.repl.newjvm.MainJVM; import edu.rice.cs.drjava.model.compiler.CompilerListener; import edu.rice.cs.drjava.model.compiler.CompilerModel; import edu.rice.cs.drjava.model.compiler.DefaultCompilerModel; import edu.rice.cs.drjava.model.compiler.CompilerInterface; import edu.rice.cs.drjava.model.junit.DefaultJUnitModel; import edu.rice.cs.drjava.model.junit.JUnitModel; import edu.rice.cs.drjava.ui.MainFrame; import edu.rice.cs.plt.reflect.JavaVersion; import edu.rice.cs.plt.iter.IterUtil; import edu.rice.cs.plt.io.IOUtil; import edu.rice.cs.util.FileOpenSelector; import edu.rice.cs.util.FileOps; import edu.rice.cs.util.NullFile; import edu.rice.cs.util.OperationCanceledException; import edu.rice.cs.util.UnexpectedException; import edu.rice.cs.util.newjvm.AbstractMasterJVM; import edu.rice.cs.util.text.EditDocumentException; import edu.rice.cs.util.swing.Utilities; import static edu.rice.cs.plt.debug.DebugUtil.debug; /** Handles the bulk of DrJava's program logic. The UI components interface with the GlobalModel through its public * methods, and the GlobalModel responds via the GlobalModelListener interface. This removes the dependency on the * UI for the logical flow of the program's features. With the current implementation, we can finally test the compile * functionality of DrJava, along with many other things. <p> * @version $Id: DefaultGlobalModel.java 4636 2008-08-12 18:47:11Z mgricken $ */ public class DefaultGlobalModel extends AbstractGlobalModel { /* FIELDS */ /* static Log _log inherited from AbstractGlobalModel */ /* Interpreter fields */ /** The document used in the Interactions model. */ protected final InteractionsDJDocument _interactionsDocument; /** RMI interface to the Interactions JVM. */ final MainJVM _jvm; /** Interface between the InteractionsDocument and the JavaInterpreter, which runs in a separate JVM. */ protected final DefaultInteractionsModel _interactionsModel; /** Core listener attached to interactions model */ protected InteractionsListener _interactionsListener = new InteractionsListener() { public void interactionStarted() { } public void interactionEnded() { } public void interactionErrorOccurred(int offset, int length) { } public void interpreterResetting() { } public void interpreterReady(File wd) { File buildDir = _state.getBuildDirectory(); if (buildDir != null) { // System.out.println("adding for reset: " + _state.getBuildDirectory().getAbsolutePath()); _jvm.addBuildDirectoryClassPath(IOUtil.attemptAbsoluteFile(buildDir)); } } public void interpreterResetFailed(Throwable t) { } public void interpreterExited(int status) { } public void interpreterChanged(boolean inProgress) { } public void interactionIncomplete() { } public void slaveJVMUsed() { } }; private CompilerListener _clearInteractionsListener = new DummyCompilerListener() { public void compileEnded(File workDir, List<? extends File> excludedFiles) { // Only clear interactions if there were no errors and unit testing is not in progress if ( (_compilerModel.getNumErrors() == 0 || _compilerModel.getCompilerErrorModel().hasOnlyWarnings()) && ! _junitModel.isTestInProgress() && _resetAfterCompile) { // Utilities.show("compileEnded called in clearInteractionsListener"); resetInteractions(workDir); // use same working directory as current interpreter } } }; // ---- Compiler Fields ---- /** CompilerModel manages all compiler functionality. */ private final CompilerModel _compilerModel; /** Whether or not to reset the interactions JVM after compiling. Should only be false in test cases. */ private volatile boolean _resetAfterCompile = true; /** Number of errors in last compilation. compilerModel._numErrors is trashed when the compile model is reset. */ private volatile int _numCompErrors = 0; /* JUnit Fields */ /** JUnitModel manages all JUnit functionality. */ private final DefaultJUnitModel _junitModel; /* Javadoc Fields */ /** Manages all Javadoc functionality. */ protected volatile JavadocModel _javadocModel; /* Debugger Fields */ /** Interface to the integrated debugger. If unavailable, set NoDebuggerAvailable.ONLY. */ private volatile Debugger _debugger; /* CONSTRUCTORS */ /** Constructs a new GlobalModel. Creates a new MainJVM and starts its Interpreter JVM. */ public DefaultGlobalModel() { Iterable<? extends JDKToolsLibrary> tools = findLibraries(); List<CompilerInterface> compilers = new LinkedList<CompilerInterface>(); _debugger = null; _javadocModel = null; for (JDKToolsLibrary t : tools) { if (t.compiler().isAvailable()) { compilers.add(t.compiler()); } if (_debugger == null && t.debugger().isAvailable()) { _debugger = t.debugger(); } if (_javadocModel == null && t.javadoc().isAvailable()) { _javadocModel = t.javadoc(); } } if (_debugger == null) { _debugger = NoDebuggerAvailable.ONLY; } if (_javadocModel == null) { _javadocModel = new NoJavadocAvailable(this); } File workDir = Utilities.TEST_MODE ? new File(System.getProperty("user.home")) : getWorkingDirectory(); try { _jvm = new MainJVM(workDir); } catch(java.rmi.server.ExportException e) { if (e.getMessage().equals("Listen failed on port: 0")) throw new RuntimeException(e); else throw new UnexpectedException(e); } catch(RemoteException e) { throw new UnexpectedException(e); } // AbstractMasterJVM._log.log(this + " has created a new MainJVM"); _compilerModel = new DefaultCompilerModel(this, compilers); _junitModel = new DefaultJUnitModel(_jvm, _compilerModel, this); _interactionsDocument = new InteractionsDJDocument(); _interactionsModel = new DefaultInteractionsModel(this, _jvm, _interactionsDocument, workDir); _interactionsModel.addListener(_interactionsListener); _jvm.setInteractionsModel(_interactionsModel); _jvm.setJUnitModel(_junitModel); StringBuilder sb = new StringBuilder(); if ((!("".equals(DrJava.getConfig().getSetting(SLAVE_JVM_XMX)))) && (!(OptionConstants.heapSizeChoices.get(0).equals(DrJava.getConfig().getSetting(SLAVE_JVM_XMX))))) { sb.append("-Xmx"); sb.append(DrJava.getConfig().getSetting(SLAVE_JVM_XMX)); sb.append("M "); } sb.append(DrJava.getConfig().getSetting(SLAVE_JVM_ARGS)); _jvm.setOptionArgs(sb.toString()); OptionListener<String> updateListener = new OptionListener<String>() { public void optionChanged(OptionEvent<String> oe) { StringBuilder sb = new StringBuilder(); if ((!("".equals(DrJava.getConfig().getSetting(SLAVE_JVM_XMX)))) && (!(OptionConstants.heapSizeChoices.get(0).equals(DrJava.getConfig().getSetting(SLAVE_JVM_XMX))))) { sb.append("-Xmx"); sb.append(DrJava.getConfig().getSetting(SLAVE_JVM_XMX)); sb.append("M "); } sb.append(DrJava.getConfig().getSetting(SLAVE_JVM_ARGS)); _jvm.setOptionArgs(sb.toString()); } }; DrJava.getConfig().addOptionListener(SLAVE_JVM_ARGS, updateListener); DrJava.getConfig().addOptionListener(SLAVE_JVM_XMX, updateListener); _setupDebugger(); // Chain notifiers so that all events also go to GlobalModelListeners. _interactionsModel.addListener(_notifier); _compilerModel.addListener(_notifier); _junitModel.addListener(_notifier); _javadocModel.addListener(_notifier); // Listen to compiler to clear interactions appropriately. // XXX: The tests need this to be registered after _notifier, sadly. // This is obnoxiously order-dependent, but it works for now. _compilerModel.addListener(_clearInteractionsListener); // Note: starting the JVM in another thread does not appear to improve performance // AbstractMasterJVM._log.log("Starting the interpreter in " + this); _jvm.startInterpreterJVM(); // Any lightweight parsing has been disabled until we have something that is beneficial and works better in the background. // _parsingControl = new DefaultLightWeightParsingControl(this); } private Iterable<JDKToolsLibrary> findLibraries() { // Order to return: config setting, runtime (if different version), from search (if different versions) // We could give priority to libraries that have both available compilers and debuggers, but since this will // almost always be true, it seems like more trouble than it is worth // map is sorted by version, lowest-to-highest Map<JavaVersion, JDKToolsLibrary> results = new TreeMap<JavaVersion, JDKToolsLibrary>(); File configTools = DrJava.getConfig().getSetting(JAVAC_LOCATION); if (configTools != FileOps.NULL_FILE) { JDKToolsLibrary fromConfig = JarJDKToolsLibrary.makeFromFile(configTools, this); if (fromConfig.isValid()) { results.put(fromConfig.version().majorVersion(), fromConfig); } } JDKToolsLibrary fromRuntime = JDKToolsLibrary.makeFromRuntime(this); JavaVersion runtimeVersion = fromRuntime.version().majorVersion(); if (fromRuntime.isValid() && !results.containsKey(runtimeVersion)) { results.put(runtimeVersion, fromRuntime); } Iterable<JarJDKToolsLibrary> fromSearch = JarJDKToolsLibrary.search(this); for (JDKToolsLibrary t : fromSearch) { JavaVersion tVersion = t.version().majorVersion(); // guaranteed to be valid if (!results.containsKey(tVersion)) { results.put(tVersion, t); } } return IterUtil.reverse(results.values()); } // public void compileAll() throws IOException{ //// ScrollableDialog sd = new ScrollableDialog(null, "DefaultGlobalModel.compileAll() called", "", ""); //// sd.show(); // _state.compileAll(); // } // public void junitAll() { _state.junitAll(); } /** Sets the build directory for a project. */ public void setBuildDirectory(File f) { _state.setBuildDirectory(f); if (f != FileOps.NULL_FILE) { // System.out.println("adding: " + f.getAbsolutePath()); _jvm.addBuildDirectoryClassPath(IOUtil.attemptAbsoluteFile(f)); } _notifier.projectBuildDirChanged(); setProjectChanged(true); setClassPathChanged(true); } // ----- METHODS ----- /** @return the interactions model. */ public DefaultInteractionsModel getInteractionsModel() { return _interactionsModel; } /** @return InteractionsDJDocument in use by the InteractionsDocument. */ public InteractionsDJDocument getSwingInteractionsDocument() { return _interactionsDocument; } public InteractionsDocument getInteractionsDocument() { return _interactionsModel.getDocument(); } /** Gets the CompilerModel, which provides all methods relating to compilers. */ public CompilerModel getCompilerModel() { return _compilerModel; } /** Gets the JUnitModel, which provides all methods relating to JUnit testing. */ public JUnitModel getJUnitModel() { return _junitModel; } /** Gets the JavadocModel, which provides all methods relating to Javadoc. */ public JavadocModel getJavadocModel() { return _javadocModel; } public int getNumCompErrors() { return _numCompErrors; } public void setNumCompErrors(int num) { _numCompErrors = num; } /** Prepares this model to be thrown away. Never called in practice outside of quit(), except in tests. */ public void dispose() { // Kill the interpreter _jvm.killInterpreter(null); // Commented out because it invokes UnicastRemoteObject.unexport // try { _jvm.dispose(); } // catch(RemoteException e) { /* ignore */ } _notifier.removeAllListeners(); // removes the global model listeners! } /** Disposes of external resources. Kills the slave JVM. */ public void disposeExternalResources() { // Kill the interpreter _jvm.killInterpreter(null); } public void resetInteractions(File wd) { resetInteractions(wd, false); } /** Clears and resets the slave JVM with working directory wd. Also clears the console if the option is * indicated (on by default). The reset operation is suppressed if the existing slave JVM has not been * used, {@code wd} matches its working directory, and forceReset is false. {@code wd} may be {@code null} * if a valid directory cannot be determined. In that case, the former working directory is used. This * method may run outside the event thread. */ public void resetInteractions(File wd, boolean forceReset) { assert _interactionsModel._pane != null; debug.logStart(); File workDir = _interactionsModel.getWorkingDirectory(); if (wd == null) { wd = workDir; } if (! forceReset && ! _jvm.slaveJVMUsed() && ! isClassPathChanged() && wd.equals(workDir)) { debug.log(); // Eliminate resetting interpreter (slaveJVM) since it has already been reset appropriately. _interactionsModel._notifyInterpreterReady(wd); debug.logEnd(); return; } // update the setting debug.log(); DrJava.getConfig().setSetting(LAST_INTERACTIONS_DIRECTORY, wd); _interactionsModel.resetInterpreter(wd); debug.logEnd(); } /** Interprets the current given text at the prompt in the interactions pane. */ public void interpretCurrentInteraction() { _interactionsModel.interpretCurrentInteraction(); } /** Interprets file selected in the FileOpenSelector. Assumes strings have no trailing whitespace. Interpretation is * aborted after the first error. */ public void loadHistory(final FileOpenSelector selector) { Utilities.invokeLater(new Runnable() { public void run() { try {_interactionsModel.loadHistory(selector); } catch(IOException e) { throw new UnexpectedException(e); } } }); } /** Loads the history/histories from the given selector. */ public InteractionsScriptModel loadHistoryAsScript(FileOpenSelector selector) throws IOException, OperationCanceledException { return _interactionsModel.loadHistoryAsScript(selector); } /** Clears the interactions history */ public void clearHistory() { _interactionsModel.getDocument().clearHistory(); } /** Saves the unedited version of the current history to a file * @param selector File to save to */ public void saveHistory(FileSaveSelector selector) throws IOException { _interactionsModel.getDocument().saveHistory(selector); } /** Saves the edited version of the current history to a file * @param selector File to save to * @param editedVersion Edited verison of the history which will be saved to file instead of the lines saved in * the history. The saved file will still include any tags needed to recognize it as a history file. */ public void saveHistory(FileSaveSelector selector, String editedVersion) throws IOException { _interactionsModel.getDocument().saveHistory(selector, editedVersion); } /** Returns the entire history as a String with semicolons as needed. */ public String getHistoryAsStringWithSemicolons() { return _interactionsModel.getDocument().getHistoryAsStringWithSemicolons(); } /** Returns the entire history as a String. */ public String getHistoryAsString() { return _interactionsModel.getDocument().getHistoryAsString(); } /** Called when the debugger wants to print a message. Inserts a newline. */ public void printDebugMessage(String s) { _interactionsModel.getDocument(). insertBeforeLastPrompt(s + "\n", InteractionsDocument.DEBUGGER_STYLE); } /** Blocks until the interpreter has registered. */ public void waitForInterpreter() { _jvm.ensureInterpreterConnected(); } /** Returns the current classpath in use by the Interpreter JVM. */ public Iterable<File> getInteractionsClassPath() { return _jvm.getClassPath(); } /** Sets whether or not the Interactions JVM will be reset after a compilation succeeds. This should ONLY be used * in tests! This method is not supported by AbstractGlobalModel. * @param shouldReset Whether to reset after compiling */ void setResetAfterCompile(boolean shouldReset) { _resetAfterCompile = shouldReset; } /** Gets the Debugger used by DrJava. */ public Debugger getDebugger() { return _debugger; } /** Returns an available port number to use for debugging the interactions JVM. * @throws IOException if unable to get a valid port number. */ public int getDebugPort() throws IOException { return _interactionsModel.getDebugPort(); } // ---------- ConcreteOpenDefDoc inner class ---------- /** Inner class to handle operations on each of the open DefinitionsDocuments by the GlobalModel. <br><br> * This was at one time called the <code>DefinitionsDocumentHandler</code> * but was renamed (2004-Jun-8) to be more descriptive/intuitive. */ class ConcreteOpenDefDoc extends AbstractGlobalModel.ConcreteOpenDefDoc { /** Standard constructor for a document read from a file. Initializes this ODD's DD. * @param f file describing DefinitionsDocument to manage */ ConcreteOpenDefDoc(File f) { super(f); } /* Standard constructor for a new document (no associated file) */ ConcreteOpenDefDoc(NullFile f) { super(f); } /** Starting compiling this document. Used only for unit testing. Only rus in the event thread. */ public void startCompile() throws IOException { assert EventQueue.isDispatchThread(); _compilerModel.compile(ConcreteOpenDefDoc.this); } private volatile InteractionsListener _runMain; /** Runs the main method in this document in the interactions pane after resetting interactions with the source * root for this document as the working directory. Warns the use if the class files for the doucment are not * up to date. Fires an event to signal when execution is about to begin. * NOTE: this code normally runs in the event thread; it cannot block waiting for an event that is triggered by * event thread execution! * @exception ClassNameNotFoundException propagated from getFirstTopLevelClass() * @exception IOException propagated from GlobalModel.compileAll() */ public void runMain() throws ClassNameNotFoundException, IOException { assert EventQueue.isDispatchThread(); _notifier.prepareForRun(ConcreteOpenDefDoc.this); // Get the class name for this document, the first top level class in the document. final String className = getDocument().getQualifiedClassName(); final InteractionsDocument iDoc = _interactionsModel.getDocument(); if (! checkIfClassFileInSync()) { iDoc.insertBeforeLastPrompt(DOCUMENT_OUT_OF_SYNC_MSG, InteractionsDocument.ERROR_STYLE); return; } final boolean wasDebuggerEnabled = getDebugger().isReady(); _runMain = new DummyInteractionsListener() { public void interpreterReady(File wd) { _interactionsModel.removeListener(_runMain); // listener cannot run // prevent listener from running twice // Restart debugger if it was previously enabled and is now off if (wasDebuggerEnabled && (! getDebugger().isReady())) { // System.err.println("Trying to start debugger"); try { getDebugger().startUp(); } catch(DebugException de) { /* ignore, continue without debugger */ } } // Load the proper text into the interactions document iDoc.clearCurrentInput(); iDoc.append("java " + className, null); // Finally, execute the new interaction and record that event new Thread("Running main method") { public void run() { _interactionsModel.interpretCurrentInteraction(); } }.start(); // This used to be called using invokeLater, so that the listener would be removed // after the read lock of the notifier had been released, but that was not always // safe; the removal could still happen before the read lock was released // Now removeListener has been rewritten and can be called even when the lock is // held. In that case, the removal will be done as soon as possible. } }; _interactionsModel.addListener(_runMain); File workDir; if (isProjectActive()) workDir = getWorkingDirectory(); // use working directory for project else { // use source root of current document try { workDir = getSourceRoot(); } catch (InvalidPackageException e) { workDir = FileOps.NULL_FILE; } } // Reset interactions to the soure root for this document; class will be executed when new interpreter is ready resetInteractions(workDir); } /** Runs JUnit on the current document. Requires that all source documents are compiled before proceeding. */ public void startJUnit() throws ClassNotFoundException, IOException { _junitModel.junit(this); } /** Generates Javadoc for this document, saving the output to a temporary directory. The location is provided to * the javadocEnded event on the given listener. * java@param saver FileSaveSelector for saving the file if it needs to be saved */ public void generateJavadoc(FileSaveSelector saver) throws IOException { // Use the model's classpath, and use the EventNotifier as the listener _javadocModel.javadocDocument(this, saver); } /** Called to indicate the document is being closed, so to remove all related state from the debug manager. */ public void removeFromDebugger() { getBreakpointManager().removeRegions(this); } } /* End of ConcreteOpenDefDoc */ /** Creates a ConcreteOpenDefDoc for a new DefinitionsDocument. * @return OpenDefinitionsDocument object for a new document */ protected ConcreteOpenDefDoc _createOpenDefinitionsDocument(NullFile f) { return new ConcreteOpenDefDoc(f); } /** Creates a ConcreteOpenDefDoc for a given file f * @return OpenDefinitionsDocument object for f */ protected ConcreteOpenDefDoc _createOpenDefinitionsDocument(File f) throws IOException { if (! f.exists()) throw new FileNotFoundException("file " + f + " cannot be found"); return new ConcreteOpenDefDoc(f); } /** Adds the source root for doc to the interactions classpath; this function is a helper to _openFiles. * @param doc the document to add to the classpath */ protected void addDocToClassPath(OpenDefinitionsDocument doc) { try { File sourceRoot = doc.getSourceRoot(); if (doc.isAuxiliaryFile()) { _interactionsModel.addProjectFilesClassPath(sourceRoot); } else { _interactionsModel.addExternalFilesClassPath(sourceRoot); } setClassPathChanged(true); } catch (InvalidPackageException e) { // Invalid package-- don't add it to classpath } } private void _setupDebugger() { _jvm.setDebugModel(_debugger.callback()); // add listener to set the project file to "changed" when a breakpoint or watch is added, removed, or changed getBreakpointManager().addListener(new RegionManagerListener<Breakpoint>() { public void regionAdded(final Breakpoint bp) { setProjectChanged(true); } public void regionChanged(final Breakpoint bp) { setProjectChanged(true); } public void regionRemoved(final Breakpoint bp) { try { getDebugger().removeBreakpoint(bp); } catch(DebugException de) { /* just ignore it */ // TODO: should try to pop up dialog to give the user the option of restarting the debugger (mgricken) // int result = JOptionPane.showConfirmDialog(null, "Could not remove breakpoint.", "Restart debugger?", JOptionPane.YES_NO_OPTION); // if (result==JOptionPane.YES_OPTION) { // getDebugger().shutdown(); // getDebugger().startUp(); // } } setProjectChanged(true); } }); getBookmarkManager().addListener(new RegionManagerListener<OrderedDocumentRegion>() { public void regionAdded(OrderedDocumentRegion r) { setProjectChanged(true); } public void regionChanged(OrderedDocumentRegion r) { setProjectChanged(true); } public void regionRemoved(OrderedDocumentRegion r) { setProjectChanged(true); } }); _debugger.addListener(new DebugListener() { public void watchSet(final DebugWatchData w) { setProjectChanged(true); } public void watchRemoved(final DebugWatchData w) { setProjectChanged(true); } public void regionAdded(final Breakpoint bp) { } public void regionChanged(final Breakpoint bp) { } public void regionRemoved(final Breakpoint bp) { } public void debuggerStarted() { } public void debuggerShutdown() { } public void threadLocationUpdated(OpenDefinitionsDocument doc, int lineNumber, boolean shouldHighlight) { } public void breakpointReached(final Breakpoint bp) { } public void stepRequested() { } public void currThreadSuspended() { } public void currThreadResumed() { } public void threadStarted() { } public void currThreadDied() { } public void nonCurrThreadDied() { } public void currThreadSet(DebugThreadData thread) { } }); } /** Get the class path to be used in all class-related operations. * TODO: Insure that this is used wherever appropriate. */ public Iterable<File> getClassPath() { Iterable<File> result = IterUtil.empty(); if (isProjectActive()) { File buildDir = getBuildDirectory(); if (buildDir != null) { result = IterUtil.compose(result, buildDir); } /* We prefer to assume the project root is the project's source root, rather than * checking *every* file in the project for its source root. This is a bit problematic, * because "Compile Project" won't care if the user has multiple source roots (or even just a * single "src" subdirectory), and the user in this situation (assuming the build dir is * null) wouldn't notice a problem until trying to access the compiled classes in the * Interactions. */ File projRoot = getProjectRoot(); if (projRoot != null) { result = IterUtil.compose(result, projRoot); } Iterable<File> projectExtras = getExtraClassPath(); if (projectExtras != null) { result = IterUtil.compose(result, projectExtras); } } else { result = IterUtil.compose(result, getSourceRootSet()); } Vector<File> globalExtras = DrJava.getConfig().getSetting(EXTRA_CLASSPATH); if (globalExtras != null) { result = IterUtil.compose(result, globalExtras); } /* We must add JUnit to the class path. We do so by including the current JVM's class path. * This is not ideal, because all other classes on the current class path (including all of DrJava's * internal classes) are also included. But we're probably stuck doing something like this if we * want to continue bundling JUnit with DrJava. */ result = IterUtil.compose(result, RUNTIME_CLASS_PATH); return result; } /** Adds the project root (if a project is open), the source roots for other open documents, the paths in the * "extra classpath" config option, as well as any project-specific classpaths to the interpreter's classpath. * This method is called in DefaultInteractionsModel when the interpreter becomes ready. Runs outside the event * thread. */ public void resetInteractionsClassPath() { // System.err.println("Resetting interactions class path"); Iterable<File> projectExtras = getExtraClassPath(); //System.out.println("Adding project classpath vector to interactions classpath: " + projectExtras); if (projectExtras != null) for (File cpE : projectExtras) { _interactionsModel.addProjectClassPath(cpE); } Vector<File> cp = DrJava.getConfig().getSetting(EXTRA_CLASSPATH); if (cp != null) { for (File f : cp) { _interactionsModel.addExtraClassPath(f); } } for (OpenDefinitionsDocument odd: getAuxiliaryDocuments()) { // this forwards directly to InterpreterJVM.addClassPath(String) try { _interactionsModel.addProjectFilesClassPath(odd.getSourceRoot()); } catch(InvalidPackageException e) { /* ignore it */ } } for (OpenDefinitionsDocument odd: getNonProjectDocuments()) { // this forwards directly to InterpreterJVM.addClassPath(String) try { File sourceRoot = odd.getSourceRoot(); if (sourceRoot != null) _interactionsModel.addExternalFilesClassPath(sourceRoot); } catch(InvalidPackageException e) { /* ignore it */ } } // add project source root to projectFilesClassPath. All files in project tree have this root. _interactionsModel.addProjectFilesClassPath(getProjectRoot()); // is sync advisable here? setClassPathChanged(false); // reset classPathChanged state } // private class ExtraClasspathOptionListener implements OptionListener<Vector<File>> { // public void optionChanged (OptionEvent<Vector<File>> oce) { // Vector<File> cp = oce.value; // if (cp != null) { // for (File f: cp) { // // this forwards directly to InterpreterJVM.addClassPath(String) // try { _interactionsModel.addExtraClassPath(f.toURL()); } // catch(MalformedURLException murle) { // /* do nothing; findbugs signals a bug unless this catch clause spans more than two lines */ // } // } // } // } // } }

The table below shows all metrics for DefaultGlobalModel.java.

MetricValueDescription
BLOCKS130.00Number of blocks
BLOCK_COMMENT56.00Number of block comment lines
COMMENTS228.00Comment lines
COMMENT_DENSITY 0.68Comment density
COMPARISONS41.00Number of comparison operators
CYCLOMATIC128.00Cyclomatic complexity
DECL_COMMENTS79.00Comments in declarations
DOC_COMMENT97.00Number of javadoc comment lines
ELOC334.00Effective lines of code
EXEC_COMMENTS47.00Comments in executable code
EXITS121.00Procedure exits
FUNCTIONS79.00Number of function declarations
HALSTEAD_DIFFICULTY64.34Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY141.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 1.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 3.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 7.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA0034 6.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA008011.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 1.00JAVA0106 Unnecessary import from current package
JAVA0108 0.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA011010.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 1.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 0.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 9.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 0.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 1.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 1.00JAVA0144 Line exceeds maximum M characters
JAVA0145 0.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 0.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 1.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 1.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 0.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES744.00Number of lines in the source file
LINE_COMMENT75.00Number of line comments
LOC383.00Lines of code
LOGICAL_LINES244.00Number of statements
LOOPS 0.00Number of loops
NEST_DEPTH 4.00Maximum nesting depth
OPERANDS1221.00Number of operands
OPERATORS2362.00Number of operators
PARAMS44.00Number of formal parameter declarations
PROGRAM_LENGTH3583.00Halstead program length
PROGRAM_VOCAB493.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS97.00Number of return points from functions
SIZE33844.00Size of the file in bytes
UNIQUE_OPERANDS446.00Number of unique operands
UNIQUE_OPERATORS47.00Number of unique operators
WHITESPACE133.00Number of whitespace lines