FindReplaceMachine.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
EXEC_COMMENTSComments in executable code
JAVA0034JAVA0034 Missing braces in if statement
LINE_COMMENTNumber of line comments
JAVA0020JAVA0020 Field name does not have required form
SIZESize of the file in bytes
JAVA0177JAVA0177 Variable declaration missing initializer
JAVA0117JAVA0117 Missing javadoc: method 'method'
CYCLOMATICCyclomatic complexity
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
FUNCTIONSNumber of function declarations
RETURNSNumber of return points from functions
INTERFACE_COMPLEXITYInterface complexity
LOGICAL_LINESNumber of statements
DECL_COMMENTSComments in declarations
COMMENTSComment lines
PARAMSNumber of formal parameter declarations
LINESNumber of lines in the source file
JAVA0018JAVA0018 Method name does not have required form
COMPARISONSNumber of comparison operators
BLOCKSNumber of blocks
OPERATORSNumber of operators
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
PROGRAM_LENGTHHalstead program length
JAVA0144JAVA0144 Line exceeds maximum M characters
OPERANDSNumber of operands
JAVA0171JAVA0171 Unused local variable
ELOCEffective lines of code
JAVA0163JAVA0163 Empty statement
EXITSProcedure exits
PROGRAM_VOCABHalstead program vocabulary
DOC_COMMENTNumber of javadoc comment lines
WHITESPACENumber of whitespace lines
JAVA0080JAVA0080 Import declaration not used
UNIQUE_OPERANDSNumber of unique operands
UNIQUE_OPERATORSNumber of unique operators
LOCLines of code
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0109JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0030JAVA0030 Private field not used
LOOPSNumber of loops
JAVA0100JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0130JAVA0130 Non-static method does not use instance fields
JAVA0068JAVA0068 Modifiers not declared in recommended order
NEST_DEPTHMaximum nesting depth
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 edu.rice.cs.drjava.model.definitions.reducedmodel.ReducedModelStates; import edu.rice.cs.plt.lambda.Runnable1; import edu.rice.cs.util.UnexpectedException; import edu.rice.cs.util.swing.DocumentIterator; import edu.rice.cs.util.swing.Utilities; import edu.rice.cs.util.text.AbstractDocumentInterface; import edu.rice.cs.util.Log; import edu.rice.cs.util.StringOps; import java.awt.EventQueue; import javax.swing.text.BadLocationException; import javax.swing.text.Position; import static edu.rice.cs.drjava.model.definitions.reducedmodel.ReducedModelStates.*; /** Implementation of logic of find/replace over a document. * @version $Id: FindReplaceMachine.java 4633 2008-08-07 21:12:30Z dlsmith $ */ public class FindReplaceMachine { static private Log _log = new Log("FindReplace.txt", false); /* Visible machine state; manipulated directly or indirectly by FindReplacePanel. */ private OpenDefinitionsDocument _doc; // Current search document private OpenDefinitionsDocument _firstDoc; // First document where searching started (when searching all documents) // private Position _current; // Position of the cursor in _doc when machine is stopped private int _current; // Position of the cursor in _doc when machine is stopped // private Position _start; // Position in _doc from which searching started or will start. private String _findWord; // Word to find. */ private String _replaceWord; // Word to replace _findword. private boolean _matchCase; private boolean _matchWholeWord; private boolean _searchAllDocuments; // Whether to search all documents (or just the current document) private boolean _isForward; // Whether search direction is forward (false means backward) private boolean _ignoreCommentsAndStrings; // Whether to ignore matches in comments and strings private boolean _ignoreTestCases; // Whether to ignore documents that end in *Test.java private String _lastFindWord; // Last word found; set to null by FindReplacePanel if caret is updated private boolean _skipText; // Whether to skip over the current match if direction is reversed private DocumentIterator _docIterator; // An iterator of open documents; _doc is current private SingleDisplayModel _model; /** Standard Constructor. * Creates new machine to perform find/replace operations on a particular document starting from a given position. * @param docIterator an object that allows navigation through open Swing documents (it is DefaultGlobalModel) * @exception BadLocationException */ public FindReplaceMachine(SingleDisplayModel model, DocumentIterator docIterator) { _skipText = false; // _checkAllDocsWrapped = false; // _allDocsWrapped = false; _model = model; _docIterator = docIterator; _current = -1; setFindAnyOccurrence(); setFindWord(""); setReplaceWord(""); setSearchBackwards(false); setMatchCase(true); setSearchAllDocuments(false); setIgnoreCommentsAndStrings(false); setIgnoreTestCases(false); } public void cleanUp() { _docIterator = null; setFindWord(""); _doc = null; } /** Called when the current position is updated in the document implying _skipText should not be set * if the user toggles _searchBackwards */ public void positionChanged() { _lastFindWord = null; _skipText = false; } public void setLastFindWord() { _lastFindWord = _findWord; } public boolean isSearchBackwards() { return ! _isForward; } public void setSearchBackwards(boolean searchBackwards) { if (_isForward == searchBackwards) { // If we switch from searching forward to searching backwards or vice versa, isOnMatch is true, and _findword is the // same as the _lastFindWord, we know the user just found _findWord, so skip over this match. if (onMatch() && _findWord.equals(_lastFindWord)) _skipText = true; else _skipText = false; } _isForward = ! searchBackwards; } public void setMatchCase(boolean matchCase) { _matchCase = matchCase; } public boolean getMatchCase() { return _matchCase; } public void setMatchWholeWord() { _matchWholeWord = true; } public boolean getMatchWholeWord() { return _matchWholeWord; } public void setFindAnyOccurrence() { _matchWholeWord = false; } public void setSearchAllDocuments(boolean searchAllDocuments) { _searchAllDocuments = searchAllDocuments; } public void setIgnoreCommentsAndStrings(boolean ignoreCommentsAndStrings) { _ignoreCommentsAndStrings = ignoreCommentsAndStrings; } public boolean getIgnoreCommentsAndStrings() { return _ignoreCommentsAndStrings; } public void setIgnoreTestCases(boolean ignoreTestCases) { _ignoreTestCases = ignoreTestCases; } public boolean getIgnoreTestCases() { return _ignoreTestCases; } public void setDocument(OpenDefinitionsDocument doc) { _doc = doc; } public void setFirstDoc(OpenDefinitionsDocument firstDoc) { _firstDoc = firstDoc; } public void setPosition(int pos) { _current = pos; } /** Gets the character offset to which this machine is currently pointing. */ public int getCurrentOffset() { //return _current.getOffset(); return _current; } public String getFindWord() { return _findWord; } public String getReplaceWord() { return _replaceWord; } public boolean getSearchAllDocuments() { return _searchAllDocuments; } public OpenDefinitionsDocument getDocument() { return _doc; } public OpenDefinitionsDocument getFirstDoc() { return _firstDoc; } /** Change the word being sought. * @param word the new word to seek */ public void setFindWord(String word) { _findWord = StringOps.replace(word, StringOps.EOL, "\n"); } /** Change the replacing word. * @param word the new replacing word */ public void setReplaceWord(String word) { _replaceWord = StringOps.replace(word, StringOps.EOL,"\n"); } /** Determine if the machine is on an instance of the find word. Only executes in event thread except for * initialization. * @return true if the current position is right after an instance of the find word. */ public boolean onMatch() { // assert EventQueue.isDispatchThread(); String findWord = _findWord; int wordLen, off; if(_current == -1) return false; wordLen = findWord.length(); if (_isForward) off = getCurrentOffset() - wordLen; else off = getCurrentOffset(); if (off < 0) return false; String matchSpace; try { if (off + wordLen > _doc.getLength()) return false; matchSpace = _doc.getText(off, wordLen); } catch (BadLocationException e) { throw new UnexpectedException(e); } if (!_matchCase) { matchSpace = matchSpace.toLowerCase(); findWord = findWord.toLowerCase(); } return matchSpace.equals(findWord); } /** If we're on a match for the find word, replace it with the replace word. Only executes in event thread. */ public boolean replaceCurrent() { assert EventQueue.isDispatchThread(); if (! onMatch()) return false; try { // boolean atStart = false; int offset = getCurrentOffset(); if (_isForward) offset -= _findWord.length(); // position is now on left edge of match // assert _findWord.equals(_doc.getText(offset, _findWord.length())); // Utilities.show("ReplaceCurrent called. _doc = " + _doc.getText() + " offset = " + offset + " _findWord = " + _findWord); _doc.remove(offset, _findWord.length()); // if (position == 0) atStart = true; _doc.insertString(offset, _replaceWord, null); // could use _insertString if we had the DefinitionsDocument // update _current Position if (_isForward) setPosition(offset + _replaceWord.length()); else setPosition(offset); return true; } catch (BadLocationException e) { throw new UnexpectedException(e); } } /** Replaces all occurences of the find word with the replace word in the current document of in all documents * depending the value of the machine register _searchAllDocuments. * @return the number of replacements */ public int replaceAll() { return replaceAll(_searchAllDocuments); } /** Replaces all occurences of the find word with the replace word in the current document of in all documents * depending the value of the flag searchAll. * @return the number of replacements */ private int replaceAll(boolean searchAll) { if (searchAll) { OpenDefinitionsDocument startDoc = _doc; int count = 0; // the number of replacements done so farr int n = _docIterator.getDocumentCount(); for (int i = 0; i < n; i++) { // replace all in the rest of the documents count += _replaceAllInCurrentDoc(); _doc = _docIterator.getNextDocument(_doc); } // update display (adding "*") in navigatgorPane _model.getDocumentNavigator().repaint(); return count; } else return _replaceAllInCurrentDoc(); } /** Replaces all occurences of _findWord with _replaceWord in _doc. Never searches in other documents. Starts at * the beginning or the end of the document (depending on find direction). This convention ensures that matches * created by string replacement will not be replaced as in the following example:<p> * findString: "hello"<br> * replaceString: "e"<br> * document text: "hhellollo"<p> * Depending on the cursor position, clicking replace all could either make the document text read "hello" * (which is correct) or "e". This is because of the behavior of findNext(), and it would be incorrect * to change that behavior. Only executes in event thread. * @return the number of replacements */ private int _replaceAllInCurrentDoc() { assert EventQueue.isDispatchThread(); if (_isForward) setPosition(0); else setPosition(_doc.getLength()); int count = 0; FindResult fr = findNext(false); // find next match in current doc // Utilities.show(fr + " returned by call on findNext()"); while (! fr.getWrapped()) { replaceCurrent(); // sets writeLock so that other threads do not see inconsistent state count++; // Utilities.show("Found " + count + " occurrences. Calling findNext() inside loop"); fr = findNext(false); // find next match in current doc // Utilities.show("Call on findNext() returned " + fr.toString() + "in doc '" + _doc.getText() + "'"); } return count; } /** Processes all occurences of the find word with the replace word in the current document or in all documents * depending the value of the machine register _searchAllDocuments. * @param findAction action to perform on the occurrences; input is the FindResult, output is ignored * @return the number of processed occurrences */ public int processAll(Runnable1<FindResult> findAction) { return processAll(findAction, _searchAllDocuments); } /** Processes all occurences of the find word with the replace word in the current document or in all documents * depending the value of the flag searchAll. Assumes that findAction does not modify the document it processes. * Only executes in event thread. * @param findAction action to perform on the occurrences; input is the FindResult, output is ignored * @return the number of replacements */ private int processAll(Runnable1<FindResult> findAction, boolean searchAll) { assert EventQueue.isDispatchThread(); if (searchAll) { OpenDefinitionsDocument startDoc = _doc; int count = 0; // the number of replacements done so farr int n = _docIterator.getDocumentCount(); for (int i = 0; i < n; i++) { // process all in the rest of the documents count += _processAllInCurrentDoc(findAction); _doc = _docIterator.getNextDocument(_doc); } // update display (perhaps adding "*") in navigatgorPane _model.getDocumentNavigator().repaint(); return count; } else return _processAllInCurrentDoc(findAction); } /** Processes all occurences of _findWord in _doc. Never processes other documents. Starts at the beginning or the * end of the document (depending on find direction). This convention ensures that matches created by string * replacement will not be replaced as in the following example:<p> * findString: "hello"<br> * replaceString: "e"<br> * document text: "hhellollo"<p> * Assumes this has mutually exclusive access to _doc (e.g., by hourglassOn) and findAction does not modify _doc. * Only executes in event thread. * @param findAction action to perform on the occurrences; input is the FindResult, output is ignored * @return the number of replacements */ private int _processAllInCurrentDoc(Runnable1<FindResult> findAction) { if (_isForward) setPosition(0); else setPosition(_doc.getLength()); int count = 0; FindResult fr = findNext(false); // find next match in current doc while (! fr.getWrapped()) { findAction.run(fr); count++; fr = findNext(false); // find next match in current doc } return count; } public FindResult findNext() { return findNext(_searchAllDocuments); } /** Finds the next occurrence of the find word and returns an offset at the end of that occurrence or -1 if the word * was not found. In a forward search, the match offset is the RIGHT edge of the word. In subsequent searches, the * same instance won't be found again. In a backward search, the position returned is the LEFT edge of the word. * Also returns a flag indicating whether the end of the document was reached and wrapped around. This is done * using the FindResult class which contains the matching document, an integer offset and two flag indicated whether * the search wrapped (within _doc and across all documents). Only executes in the event thread. * @param searchAll whether to search all documents (or just _doc) * @return a FindResult object containing foundOffset and a flag indicating wrapping to the beginning during a search */ private FindResult findNext(boolean searchAll) { assert EventQueue.isDispatchThread(); // Find next match, if any, in _doc. FindResult fr; int start; int len; // If the user just found a match and toggled the "Search Backwards" option, we should skip the matched text. if (_skipText) { // adjust position (offset) // System.err.println("Skip text is true! Last find word = " + _lastFindWord); int wordLen = _lastFindWord.length(); if (_isForward) setPosition(getCurrentOffset() + wordLen); else setPosition(getCurrentOffset() - wordLen); positionChanged(); } // System.err.println("findNext(" + searchAll + ") called with _doc = [" + _doc.getText() + "] and offset = " + _current.getOffset()); int offset = getCurrentOffset(); // System.err.println("findNext(" + searchAll + ") called; initial offset is " + offset); // System.err.println("_doc = [" + _doc.getText() + "], _doc.getLength() = " + _doc.getLength()); if (_isForward) { start = offset; len = _doc.getLength() - offset; } else { start = 0; len = offset; } fr = _findNextInDoc(_doc, start, len, searchAll); if (fr.getFoundOffset() >= 0 || ! searchAll) return fr; // match found in _doc or search is local // find match in other docs return _findNextInOtherDocs(_doc, start, len); } /** Finds next match in specified doc only. If searching forward, len must be doc.getLength(). If searching backward, * start must be 0. If searchAll, suppress executing in-document wrapped search, because it must be deferred. Assumes * acquireReadLock is already held. Note than this method does a wrapped search if specified search fails. */ private FindResult _findNextInDoc(OpenDefinitionsDocument doc, int start, int len, boolean searchAll) { // search from current position to "end" of document ("end" is start if searching backward) // Utilities.show("_findNextInDoc([" + doc.getText() + "], " + start + ", " + len + ", " + searchAll + ")"); // _log.log("_findNextInDoc([" + doc.getText() + "], " + start + ", " + len + ", " + searchAll + ")"); FindResult fr = _findNextInDocSegment(doc, start, len); if (fr.getFoundOffset() >= 0 || searchAll) return fr; return _findWrapped(doc, start, len, false); // last arg is false because search has not wrapped through all docs } /** Helper method for findNext that looks for a match after searching has wrapped off the "end" (start if searching * backward) of the document. Assumes acquireReadLock is already held! * INVARIANT (! _isForward => start = 0) && (_isForward => start + len = doc.getLength()). * @param doc the document in which search wrapped * @param start the location of preceding text segment where search FAILED. * @param len the length of text segment previously searched * @param allWrapped whether this wrapped search is being performed after an all document search has wrapped * @return the offset where the instance was found. Returns -1 if no instance was found between start and end */ private FindResult _findWrapped(OpenDefinitionsDocument doc, int start, int len, boolean allWrapped) { final int docLen = doc.getLength(); if (docLen == 0) return new FindResult(doc, -1, true, allWrapped); // failure result final int wordLen = _findWord.length(); assert (start >= 0 && start <= docLen) && (len >= 0 && len <= docLen) && wordLen > 0; assert (_isForward && start + len == docLen) || (! _isForward && start == 0); // Utilities.show("_findWrapped(" + doc + ", " + start + ", " + len + ", " + allWrapped + ") docLength = " + // doc.getLength() + ", _isForward = " + _isForward); // _log.log("_findWrapped(" + doc + ", " + start + ", " + len + ", " + allWrapped + ") docLength = " + // doc.getLength() + ", _isForward = " + _isForward); int newLen; int newStart; final int adjustment = wordLen - 1; // non-negative max size of the findWord suffix (prefix) within preceding text if (_isForward) { newStart = 0; newLen = start + adjustment; // formerly start, which was an annoying bug if (newLen > docLen) newLen = docLen; } else { newStart = len - adjustment; if (newStart < 0) newStart = 0; newLen = docLen - newStart; } // _log.log("Calling _findNextInDocSegment(" + doc.getText() + ", newStart = " + newStart + ", newLen = " + // newLen + ", allWrapped = " + allWrapped + ") and _isForward = " + _isForward); return _findNextInDocSegment(doc, newStart, newLen, true, allWrapped); } /** Find first valid match withing specified segment of doc. */ private FindResult _findNextInDocSegment(OpenDefinitionsDocument doc, int start, int len) { return _findNextInDocSegment(doc, start, len, false, false); } /** Main helper method for findNext... that searches for _findWord inside the specified document segment. Assumes * acquireReadLock is already held! * @param doc document to be searched * @param start the location (offset/left edge) of the text segment to be searched * @param len the requested length of the text segment to be searched * @param whether this search should span all documents * @param wrapped whether this search is after wrapping around the document * @param allWrapped whether this seach is after wrapping around all documents * @return a FindResult object with foundOffset and a flag indicating wrapping to the beginning during a search. The * foundOffset returned insided the FindResult is -1 if no instance was found. */ private FindResult _findNextInDocSegment(final OpenDefinitionsDocument doc, final int start, int len, final boolean wrapped, final boolean allWrapped) { // Utilities.show("called _findNextInDocSegment(" + doc.getText() + ",\n" + start + ", " + len + ", " + wrapped + " ...)"); boolean inTestCase = (_doc.getFileName().endsWith("Test.java")); if (!_ignoreTestCases || ! inTestCase) { final int docLen = doc.getLength();; // The length of the segment to be searched final int wordLen = _findWord.length(); // length of search key (word being searched for) assert (start >= 0 && start <= docLen) && (len >= 0 && len <= docLen); if (len == 0 || docLen == 0) return new FindResult(doc, -1, wrapped, allWrapped); if (start + len > docLen) len = docLen - start; // if (start + len > docLen) len = docLen - start; String text; // The text segment to be searched final String findWord; // copy of word being searched (so it can converted to lower case if necessary try { // if (wrapped && allWrapped) Utilities.show(start +", " + len + ", " + docLen + ", doc = '" + doc.getText() + "'"); text = doc.getText(start, len); if (! _matchCase) { text = text.toLowerCase(); findWord = _findWord.toLowerCase(); // does not affect wordLen } else findWord = _findWord; // if (wrapped && allWrapped) Utilities.show("Executing loop with findWord = " + findWord + "; text = " + text + "; len = " + len); // loop to find first valid (not ignored) occurrence of findWord // loop carried variables are rem, foundOffset; // loop invariant variables are _doc, docLen, _isForward, findWord, wordLen, start, len. // Invariant: on forwardsearch, foundOffset + rem == len; on backward search foundOffset == rem. // loop exits by returning match (as FindResult) or by falling through with no match. // if match is returned, _current has been updated to match location int foundOffset = _isForward? 0 : len; int rem = len; // _log.log("Starting search loop; text = '" + text + "' findWord = '" + findWord + "' forward? = " + _isForward + " rem = " + rem + " foundOffset = " + foundOffset); while (rem >= wordLen) { // Find next match in text foundOffset = _isForward ? text.indexOf(findWord, foundOffset) : text.lastIndexOf(findWord, foundOffset); // _log.log("foundOffset = " + foundOffset); if (foundOffset < 0) break; // no valid match in this document int foundLocation = start + foundOffset; int matchLocation; if (_isForward) { foundOffset += wordLen; // skip over matched word // text = text.substring(adjustedOffset, len); // len is length of text before update rem = len - foundOffset; // len is updated to length of remaining text to search matchLocation = foundLocation + wordLen; // matchLocation is index in _doc of right edge of match // _current = docToSearch.createPosition(start); // put caret at beginning of found word } else { foundOffset -= wordLen; // skip over matched word rem = foundOffset; // rem is adjusted to match foundOffset matchLocation = foundLocation; // matchLocation is index in _doc of left edge of match // text = text.substring(0, len); // len is length of text after update // _current = docToSearch.createPosition(foundLocation); // put caret at end of found word } // _log.log("rem = " + rem); // _log.log("Finished iteration with text = " + text + "; len = " + len + "; foundLocation = " + foundLocation); assert foundLocation > -1; if (_shouldIgnore(foundLocation, doc)) continue; //_current = doc.createPosition(matchLocation); // formerly doc.createPosition(...) setPosition(matchLocation); // System.err.println("Returning result = " + new FindResult(doc, matchLocation, wrapped, allWrapped)); return new FindResult(doc, matchLocation, wrapped, allWrapped); // return valid match } } catch (BadLocationException e) { throw new UnexpectedException(e); } } // loop fell through; search failed in doc segment return new FindResult(doc, -1, wrapped, allWrapped); } /** Searches all documents following startDoc for _findWord, cycling through the documents in the direction specified * by _isForward. If the search cycles back to doc without finding a match, performs a wrapped search on doc. * @param startDoc document where searching started and just failed * @param start location in startDoc of the document segment where search failed. * @param len length of the text segment where search failed. * @return the FindResult containing the information for where we found _findWord or a dummy FindResult. */ private FindResult _findNextInOtherDocs(final OpenDefinitionsDocument startDoc, int start, int len) { // System.err.println("_findNextInOtherDocs(" + startDoc.getText() + ", " + start + ", " + len + ")"); boolean allWrapped = false; _doc = _isForward ? _docIterator.getNextDocument(startDoc) : _docIterator.getPrevDocument(startDoc); while (_doc != startDoc) { if (_doc == _firstDoc) allWrapped = true; boolean inTestCase = (_doc.getFileName().endsWith("Test.java")); if (! _ignoreTestCases || ! inTestCase) { // System.err.println("_doc = [" + _doc.getText() + "]"); // if (_isForward) setPosition(0); // else setPosition(_doc.getLength()); // find next match in _doc FindResult fr; fr = _findNextInDocSegment(_doc, 0, _doc.getLength(), false, allWrapped); if (fr.getFoundOffset() >= 0) return fr; } // System.err.println("Advancing from '" + _doc.getText() + "' to next doc"); _doc = _isForward ? _docIterator.getNextDocument(_doc) : _docIterator.getPrevDocument(_doc); // System.err.println("Next doc is: '" + _doc.getText() + "'"); } // No valid match found; perform wrapped search. _findWrapped assumes acquireReadLock is held. return _findWrapped(startDoc, start, len, true); // last arg is true because searching all docs has wrapped } /** Determines whether the whole find word is found at the input position. Assumes read lock or hourglass is * already held. * @param doc - the document where an instance of the find word was found * @param foundOffset - the position where that instance was found * @return true if the whole word is found at foundOffset, false otherwise */ private boolean wholeWordFoundAtCurrent(OpenDefinitionsDocument doc, int foundOffset) { char leftOfMatch = 0; // forced initialization char rightOfMatch = 0; // forced initialization int leftLoc = foundOffset - 1; int rightLoc = foundOffset + _findWord.length(); boolean leftOutOfBounds = false; boolean rightOutOfBounds = false; try { leftOfMatch = doc.getText(leftLoc, 1).charAt(0); } catch (BadLocationException e) { leftOutOfBounds = true; } catch (IndexOutOfBoundsException e) { leftOutOfBounds = true; } try { rightOfMatch = doc.getText(rightLoc, 1).charAt(0); } catch (BadLocationException e) { rightOutOfBounds = true; } catch (IndexOutOfBoundsException e) { rightOutOfBounds = true; } if (! leftOutOfBounds && ! rightOutOfBounds) return isDelimiter(rightOfMatch) && isDelimiter(leftOfMatch); if (! leftOutOfBounds) return isDelimiter(leftOfMatch); if (! rightOutOfBounds) return isDelimiter(rightOfMatch); return true; } /** Determines whether a character is a delimiter (not a letter or digit) as a helper to wholeWordFoundAtCurrent * * @param ch - a character * @return true if ch is a delimiter, false otherwise */ private boolean isDelimiter(char ch) { return ! Character.isLetterOrDigit(ch) && ch != '_'; } /** Returns true if the currently found instance should be ignored (either because it is inside a string or comment or * because it does not match the whole word when either or both of those conditions are set to true). Only executes * in event thread. * @param foundOffset the location of the instance found * @param doc the current document where the instance was found * @return true if the location should be ignored, false otherwise */ private boolean _shouldIgnore(int foundOffset, OpenDefinitionsDocument odd) { assert EventQueue.isDispatchThread(); return (_matchWholeWord && ! wholeWordFoundAtCurrent(odd, foundOffset)) || (_ignoreCommentsAndStrings && odd._isShadowed(foundOffset)); } }

The table below shows all metrics for FindReplaceMachine.java.

MetricValueDescription
BLOCKS77.00Number of blocks
BLOCK_COMMENT36.00Number of block comment lines
COMMENTS224.00Comment lines
COMMENT_DENSITY 0.81Comment density
COMPARISONS55.00Number of comparison operators
CYCLOMATIC119.00Cyclomatic complexity
DECL_COMMENTS27.00Comments in declarations
DOC_COMMENT123.00Number of javadoc comment lines
ELOC276.00Effective lines of code
EXEC_COMMENTS57.00Comments in executable code
EXITS50.00Procedure exits
FUNCTIONS45.00Number of function declarations
HALSTEAD_DIFFICULTY93.08Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY105.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 8.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA002015.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 1.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
JAVA003434.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 1.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
JAVA0080 5.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 1.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 0.00JAVA0106 Unnecessary import from current package
JAVA010811.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 2.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 4.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 1.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 0.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA011723.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 1.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.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 3.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 1.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 2.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
JAVA017712.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 0.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
LINES669.00Number of lines in the source file
LINE_COMMENT65.00Number of line comments
LOC322.00Lines of code
LOGICAL_LINES231.00Number of statements
LOOPS 6.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS814.00Number of operands
OPERATORS1620.00Number of operators
PARAMS42.00Number of formal parameter declarations
PROGRAM_LENGTH2434.00Halstead program length
PROGRAM_VOCAB274.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS63.00Number of return points from functions
SIZE31684.00Size of the file in bytes
UNIQUE_OPERANDS223.00Number of unique operands
UNIQUE_OPERATORS51.00Number of unique operators
WHITESPACE123.00Number of whitespace lines