Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
   * Other names may be trademarks of their respective owners.
   *
   * The contents of this file are subject to the terms of either the GNU
  * General Public License Version 2 only ("GPL") or the Common
  * Development and Distribution License("CDDL") (collectively, the
  * "License"). You may not use this file except in compliance with the
  * License. You can obtain a copy of the License at
  * http://www.netbeans.org/cddl-gplv2.html
  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  * specific language governing permissions and limitations under the
  * License.  When distributing the software, include this License Header
  * Notice in each file and include the License file at
  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
  * by Oracle in the GPL Version 2 section of the License file that
  * accompanied this code. If applicable, add the following below the
  * License Header, with the fields enclosed by brackets [] replaced by
  * your own identifying information:
  * "Portions Copyrighted [year] [name of copyright owner]"
  *
  * Contributor(s):
  *
  * The Original Software is NetBeans. The Initial Developer of the Original
  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
  * Microsystems, Inc. All Rights Reserved.
  *
  * If you wish your version of this file to be governed by only the CDDL
  * or only the GPL Version 2, indicate your decision by adding
  * "[Contributor] elects to include this software in this distribution
  * under the [CDDL or GPL Version 2] license." If you do not indicate a
  * single choice of license, a recipient has the option to distribute
  * your version of this file under either the CDDL, the GPL Version 2 or
  * to extend the choice of license to its licensees as provided above.
  * However, if you add GPL Version 2 code and therefore, elected the GPL
  * Version 2 license, then the option applies only if the new code is
  * made subject to such option by the copyright holder.
  */
 
 package org.netbeans.modules.i18n.java;
 
 import java.util.List;
 import java.util.Map;
 
 /*
  * This class was originally written as a static nested class of class
  * {@link JavaI18nSupport}.
  */

Finder which search hard coded strings in java sources.

Author(s):
Peter Zavadsky
 
 public class JavaI18nFinder implements I18nFinder {

    
State when finder is in normal java code.
 
     protected static final int STATE_JAVA = 0;
    
State when finder is at backslash in normal java code.
 
     protected static final int STATE_JAVA_A_SLASH = 1;
    
State when finder is in line comment.
 
     protected static final int STATE_LINECOMMENT = 2;
    
State when finder is in block comment.
 
     protected static final int STATE_BLOCKCOMMENT = 3;
    
State when finder is at star in block commnet.
 
     protected static final int STATE_BLOCKCOMMENT_A_STAR = 4;
    
State when finder is in string found in nornal java code.
 
     protected static final int STATE_STRING = 5;
    
State when finder is at backslash in string.
 
    protected static final int STATE_STRING_A_BSLASH = 6;
    
State when finder is in char in noraml java code.
    protected static final int STATE_CHAR = 7; // to avoid misinterpreting of '"' resp. '\"' char.

    
Document on which the search is performed.
    protected StyledDocument document;

    
Keeps current state.
    protected int state;

    
Flag of search type, if it is searched for i18n-ized strings or non-i18n-ized ones.
    protected boolean i18nSearch;

    
Keeps position from last search iteration.
    protected Position lastPosition;

    
Helper variable for keeping the java string (means pure java code, no coments etc.).
    protected StringBuffer lastJavaString;

    
Helper variable. Buffer at which perform search.
    protected char[] buffer;

    
Helper variable. Actual position of search in buffer.
    protected int position;

    
Helper variable. Start of actual found hard coded string or -1.
    protected int currentStringStart;

    
Helper variable. End of actual found hard coded string or -1.
    protected int currentStringEnd;
    
    
Helper variable. Used to recognize "a" + "b" as "ab" (bug 185645).
    private boolean concatenatedStringsFound;
    
    
Helper variable. Used to recognize "a" + variable [+ "b"]* (bug 33759).
    public final String strAndVarFound = "$strAndVarFound$"//NOI18N

    
Constructs finder.
    public JavaI18nFinder(StyledDocument document) {
        super();
        this. = document;
        init();
    }

    
Initializes finder.
    private void init() {
         = ;
        initJavaStringBuffer();
         = null;
         = false;
    }

    
Resets finder.
    protected void reset() {
        init();
    }

    
Implements I18nFinder interface method. Finds all non-internationalized hard coded strings in source document.
        reset();
         = false;
        return findAllStrings();
    }

    
Implements I18nFinder inetrface method. Finds hard coded non-internationalized string in buffer.

Returns:
next HardCodedString or null if there is no more one.
         = false;
        return findNextString();
    }

    
Implements I18nFinder interface method. Finds all internationalized hard coded strings in source document. It's used in test tool.
    public HardCodedString[] findAllI18nStrings() {
        reset();
         = true;
        return findAllStrings();
    }

    
Implements I18nFinder inetrface method. Finds hard coded internationalized string in buffer. It's used in test tool.

Returns:
next HardCodedString or null if there is no more one.
         = true;
        return findNextString();
    }

    
Finds all strings according specified regular expression.
    protected HardCodedString[] findAllStrings() {
        List<HardCodedStringlist = new ArrayList<HardCodedString>();
        HardCodedString hardString;
        while ((hardString = findNextString()) != null) {
            list.add(hardString);
        }
        return !list.isEmpty()
               ? list.toArray(new HardCodedString[list.size()])
               : null;
    }
    protected HardCodedString findNextString() {
        // Reset buffer.
        try {
             = .getText(0, .getLength()).toCharArray();
        } catch (BadLocationException ble) {
            if (Boolean.getBoolean("netbeans.debug.exception")) {       //NOI18N
                ble.printStackTrace();
            }
            return null;
        }
        // Initialize position.
         = ( == null)
                   ? 0
                   : .getOffset();
        // Reset hard coded string offsets.
         = -1;
         = -1;
        // Now serious work.
        while ( < .) {
            char ch = [];
            // Other chars than '\n' (new line).
            if (ch != '\n') {
                HardCodedString foundHardString = handleCharacter(ch);
                if (foundHardString != null) {
                    return foundHardString;
                }
            } else {
                handleNewLineCharacter();
            }
            ++;
        } // End of while.
        // Indicate end was reached and nothing found.
        return null;
    }

    
Handles state changes according next charcter.
    protected HardCodedString handleCharacter(char character) {
        if ( == ) {
            return handleStateJava(character);
        } else if ( == ) {
            return handleStateJavaASlash(character);
        } else if ( == ) {
            return handleStateChar(character);
        } else if ( == ) {
            return handleStateStringABSlash(character);
        } else if ( == ) {
            return handleStateLineComment(character);
        } else if ( == ) {
            return handleStateBlockComment(character);
        } else if ( == ) {
            return handleStateBlockCommentAStar(character);
        } else if ( == ) {
            return handleStateString(character);
        }
        return null;
    }

    
Handles state when new line '\n' char occures.
    protected void handleNewLineCharacter() {
        // New line char '\n' -> reset the state.
        if ( == 
                ||  == 
                ||  == 
                ||  == 
                ||  == 
                ||  == ) {
            initJavaStringBuffer();
             = -1;
             = -1;
             = ;
        } else if ( == 
                   ||  == ) {
             = ;
        }
    }

    
Handles state STATE_JAVA.

Parameters:
character char to proceede
Returns:
HardCodedString or null if not found yet
    protected HardCodedString handleStateJava(char character) {
        .append(character);
        if (character == '/') {
             = ;
        } else if (character == '\"') {
             = ;
            if ( == -1) {
                // Found start of hard coded string.
                 = ;
            }
        } else if (character == '\'') {
             = ;
        }
        return null;
    }

    
Handles state STATE_JAVA_A_SLASH.

Parameters:
character char to proceede
Returns:
HardCodedString or null if not found yet
    protected HardCodedString handleStateJavaASlash(char character) {
        .append(character);
        if (character == '/') {
             = ;
        } else if (character == '*') {
             = ;
        }
        return null;
    }

    
Handles state STATE_CHAR.

Parameters:
character char to proceede
Returns:
HardCodedString or null if not found yet
    protected HardCodedString handleStateChar(char character) {
        .append(character);
        if (character == '\'') {
             = ;
        }
        return null;
    }

    
Handles state STATE_STRING_A_BSLASH.

Parameters:
character char to proceede
Returns:
HardCodedString or null if not found yet
    protected HardCodedString handleStateStringABSlash(char character) {
         = ;
        return null;
    }

    
Handles state STATE_LINECOMMENT.

Parameters:
character char to proceede
Returns:
null
    protected HardCodedString handleStateLineComment(char character) {
        return null;
    }

    
Handles state STATE_BLOCKCOMMENT.

Parameters:
character char to proceede
Returns:
HardCodedString or null if not found yet
    protected HardCodedString handleStateBlockComment(char character) {
        if (character == '*') {
             = ;
        }
        return null;
    }

    
Handles state STATE_BLOCKCOMMENT_A_STAR.

Parameters:
character char to proceede
Returns:
HardCodedString or null if not found yet
    protected HardCodedString handleStateBlockCommentAStar(char character) {
        if (character == '/') {
             = ;
            initJavaStringBuffer();
        } else if (character != '*') {
             = ;
        }
        return null;
    }

    
Handles state STATE_STRING.

Parameters:
character char to proceede
Returns:
HardCodedString or null if not found yet
    protected HardCodedString handleStateString(char character) {
        if (character == '\\') {
             = ;
        } else if (character == '\"') {
             = ;
            if (( == -1) && ( != -1)) {
                // Found end of hard coded string.
                 =  + 1;
                int foundStringLength =  - ;
                try {
                    // Get hard coded string.
                    Position hardStringStart = .createPosition();
                    Position hardStringEnd = .createPosition();
                    String hardString = .getText(hardStringStart.getOffset(),
                                                         foundStringLength);
                    // Retrieve offset of the end of line where was found hard coded string.
                    String restBuffer = new String(,
                                                   ,
                                                   . - );
                    int endOfLine = restBuffer.indexOf('\n');
                    if (endOfLine == -1) {
                        endOfLine = restBuffer.length();
                    }
                    
                    if () {
                        .append(.getText( + 1, hardString.length()).replace("\" + \"""")); //NOI18N
                    } else {
                        .append(.getText( + 1, hardString.length()));
                    }
                    
                    // Get the rest of line.
                    String restOfLine = .getText( + 1 + hardString.length(),
                                                          + endOfLine -  - hardString.length());
                    if(restOfLine.trim().startsWith("+ \"")) { //NOI18N
                         = true;
                         = -1;
                         = ;
                         += 4;
                         = .delete(.lastIndexOf("\"") - 1, .length()); //NOI18N
                        return null;
                    } if(restOfLine.trim().startsWith("+ ")) { // NOI18N
                        //Handle Bug 33759 (http://netbeans.org/bugzilla/show_bug.cgi?id=33759)
                        return handleStringWithVariable(hardStringrestOfLine);
                    }
                    
                    // Replace rest of occurences of \" to cheat out regular expression for very minor case when the same string is after our at the same line.
                    .append(restOfLine.replace('\"''_'));
                    
                    if () {
                         = false;
                        hardString = hardString.replace("\" + \""""); //NOI18N
                    }
                    // If not matches regular expression -> is not internationalized.
                    if (isSearchedString(.toString(), hardString)) {
                         = hardStringEnd;
                        // Search was successful -> return.
                        return new HardCodedString(extractString(hardString),
                                hardStringStart,
                                hardStringEnd);
                    }
                } catch (BadLocationException ble) {
                    ErrorManager.getDefault().notify(.,
                                                     ble);
                } finally {
                    if ( == ) {
                         = -1;
                         = -1;
                        
                        initJavaStringBuffer();
                    }
                }
            }
        }
        return null;
    }
    
    
Handles the situation where a string is followed by a variable which again is followed by a String or variable (bug 33759).

Parameters:
hardString String found so far
restOfLine String found till the end of the current line
Returns:
HardCodedString or null if not found yet
    protected HardCodedString handleStringWithVariable(String hardStringString restOfLine) {
        try {
            Position hardStringStart = .createPosition();
            Position hardStringEnd = .createPosition();
            if (restOfLine.contains(";")) { // NOI18N
                restOfLine = restOfLine.substring(0, restOfLine.indexOf(";")); // NOI18N
            }
            hardString = hardString.substring(0, hardString.length() - 1);
            String[] splits = restOfLine.substring(1).split("\\+"); // NOI18N
            String split = ""// NOI18N
            for (int i = 0; i < splits.lengthi++) {
                split = splits[i];
                if (split.trim().startsWith("\"")) { // NOI18N
                    if(!hardString.endsWith()) {
                        hardString = hardString.concat( + );
                    }
                    hardString = hardString.concat(split.trim().substring(1, split.trim().lastIndexOf("\""))); // NOI18N
                } else {
                    hardString = hardString.concat( + split + );
                }
            }
            hardString = hardString.concat("\""); // NOI18N
            if (split.lastIndexOf("\"") == -1) { // NOI18N
                 += restOfLine.indexOf(split) + split.length() + (split.endsWith(" ") ? 0 : 1); // NOI18N
            } else {
                 += restOfLine.indexOf(split) + split.lastIndexOf("\"") + 2; // NOI18N
            }
            hardStringEnd = .createPosition();
             = hardStringEnd;
            // Search was successful -> return.
            return new HardCodedString(extractString(hardString),
                    hardStringStart,
                    hardStringEnd);
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
        return null;
    }
    
    
Modifies the text of a HardCodedString so that it represents the actual text found in the editor and also shown in the ResourceWizardPanel.

Parameters:
hcString HardCodedString to modify
Returns:
modified HardCodedString or null if hcString does not fall in the category specified by Bug 33759 (http://netbeans.org/bugzilla/show_bug.cgi?id=33759)
        String hcStr = hcString.getText();
        int strAndVarLength = .length();
        if (hcStr.contains()) {
            String newHcstrText = ""// NOI18N
            int startVar = hcStr.indexOf();
            int endVar = -1;
            int counterVar = 0;
            newHcstrText = hcStr.substring(0, startVar);
            while (startVar != -1) {
                if (counterVar > 0) {
                    newHcstrText = newHcstrText.concat(" + \"").concat(hcStr.substring(endVar + strAndVarLengthstartVar)); // NOI18N
                }
                endVar = hcStr.indexOf(startVar + strAndVarLength);
                if(startVar + strAndVarLength == endVar) {
                    newHcstrText = newHcstrText.concat("\""); // NOI18N
                    counterVar--;
                } else {
                    newHcstrText = newHcstrText.concat("\" + ").concat(hcStr.substring(startVar + strAndVarLengthendVar).trim()); // NOI18N
                }
                startVar = hcStr.indexOf(endVar + strAndVarLength);
                counterVar++;
                if (startVar == -1) {
                    newHcstrText = hcStr.substring(endVar + strAndVarLength).trim().length() == 0 ? newHcstrText : newHcstrText.concat(" + \""); // NOI18N
                    newHcstrText = newHcstrText.concat(hcStr.substring(endVar + strAndVarLength));
                }
            }
            return new HardCodedString(newHcstrTexthcString.getStartPosition(), hcString.getEndPosition());
        }
        return null;
    }

    
Resets lastJavaString variable.

See also:
lastJavaString/dd>
    private void initJavaStringBuffer() {
         = new StringBuffer();
    }

    
Helper utility method.
    private String extractString(String sourceString) {
        if (sourceString == null) {
            return "";                                                  //NOI18N
        }
        if ((sourceString.length() >= 2)
                && (sourceString.charAt(0) == '\"')
                && (sourceString.charAt(sourceString.length() - 1) == '\"')) {
            sourceString = sourceString.substring(1, sourceString.length() - 1);
        }
        return sourceString;
    }

    
Help method for decision if found hard coded string is searched string. It means if it is i18n-zed or non-internationalized (depending on i18nSearch flag.

The part of line (starts after previous found hard coded string) with current found hard code string is compared against regular expression which can user specify via i18n options. If the compared line matches that regular expression the hard coded string is considered as internationalized.

Parameters:
partHardLine line of code which includes hard coded string and starts from beginning or the end of previous hard coded string.
hardString found hard code string
Returns:
true if string is internationalized and i18nSearch flag is true or if if string is non-internationalized and i18nSearch flag is false
    protected boolean isSearchedString(String partHardLineString hardString) {
        String lineToMatch = UtilConvert.unicodesToChars(partHardLine);
        Boolean regexpTestResult;
        Exception ex = null;
        try {
            String regexp = createRegularExpression(hardString);
            regexpTestResult = (Pattern.compile(regexp).matcher(lineToMatch).find()
                                == );     //auto-boxing
        } catch (ParseException ex1) {
            ex = ex1;
            regexpTestResult = null;
        } catch (PatternSyntaxException ex2) {
            ex = ex2;
            regexpTestResult = null;
        }
        if (..equals(regexpTestResult)) {
            /*
             * the string is an identifier of a bundle or a key
             * of a bundle entry
             */
            return false;
        }
        JavaSource js = JavaSource.forDocument();
        if (js != null) {
            final AnnotationDetector annotationDetector = new AnnotationDetector();
            try {
                boolean firstTry = true;
                do {
                    if (!firstTry) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException exInterrupted) {
                            Exceptions.printStackTrace(exInterrupted);
                            //but still continue
                        }
                    }
                    annotationDetector.reset();
                    js.runUserActionTask(annotationDetectortrue);
                    firstTry = false;
                } while (annotationDetector.wasCancelled()); // XXX: Does not seem necesary.
            } catch (IOException ioEx) {
                Exceptions.printStackTrace(ioEx);
            }
            if (annotationDetector.wasAnnotationDetected()) {
                // the string is within an annotation
                return false;
            }
        }
        if (regexpTestResult != null) {
            /* both tests passed */
            assert regexpTestResult.equals(.);
            return true;
        }
        /*
         * Handle the situation that some syntax error has been detected:
         */
        ErrorManager.getDefault().notify(.ex);
        // Indicate error, but allow user what to do with the found hard coded string to be able go thru
        // this problem.
        // Note: All this shouldn't happen. The reason is 1) bad set reg exp format (in options) or 
        // 2) it's error in this code.
        String msg = NbBundle.getMessage(JavaI18nSupport.class,
                                         "MSG_RegExpCompileError",      //NOI18N
                                         hardString);
        Object answer = DialogDisplayer.getDefault().notify(
                new NotifyDescriptor.Confirmation(
                        msg,
                        .,
                        .));
        return ..equals(answer);
    }

     
Creates a regular expression matching the pattern specified in the module options. The pattern specified in the options contains a special token {hardString}. This token is replaced with a regular expression matching exactly the string passed as a parameter and a result of this substitution is returned.

Parameters:
hardString hard-coded string whose regexp-equivalent is to be put in place of token {hardString}
Returns:
regular expression matching the pattern specified in the module options
    private String createRegularExpression(String hardString)
                                                        throws ParseException {
        String regexpForm;
        if () {
            regexpForm = I18nUtil.getOptions().getI18nRegularExpression();
        } else {
            regexpForm = I18nUtil.getOptions().getRegularExpression();
        }
        /*
         * Translate the regexp form to the JDK's java.util.regex syntax
         * and replace tokens "{key}" and "{hardString}" with the passed
         * hard-coded string.
         */
        Map<StringStringmap = new HashMap<StringString>(3);
        map.put("key"hardString);   //older form of regexp format     //NOI18N
        map.put("hardString"hardString);                              //NOI18N
        return Translator.translateRegexp(regexpFormmap);
    }

    
Task that determines whether there is a Java annotation at the given cursor position. It is made for the situation that it is known that there is a string literal at the given cursor position and the goal is to check whether that string literal is a part of an annotation. It may not work in cases that there is e.g. a numeric constant at the current cursor position.

Author(s):
Marian Petras
    static final class AnnotationDetector implements CancellableTask<CompilationController> {
        private final int caretPosition;
        private volatile boolean cancelled;
        private boolean annotationDetected = false;
        private AnnotationDetector(int caretPosition) {
            this. = caretPosition;
        }
        void reset() {
             = false;
             = false;
        }
        public void run(CompilationController controllerthrows IOException {
            if () {
                return;
            }
            controller.toPhase(.); //cursor position needed
            if () {
                return;
            }
            TreePath treePath = controller.getTreeUtilities()
                                          .pathFor();
            if (treePath == null) {
                return;
            }
            Tree.Kind kind = treePath.getLeaf().getKind();
            if (kind == ..) {
                if ((treePath = treePath.getParentPath()) == null) {
                    return;
                }
                kind = treePath.getLeaf().getKind();
            }
            if (kind == ..) {
                if ((treePath = treePath.getParentPath()) == null) {
                    return;
                }
                kind = treePath.getLeaf().getKind();
            }
            if (kind == ..) {
                if ((treePath = treePath.getParentPath()) == null) {
                    return;
                }
                kind = treePath.getLeaf().getKind();
            }
             = (kind == ..);
        }
        public void cancel() {
             = true;
        }
        boolean wasCancelled() {
            return ;
        }
        boolean wasAnnotationDetected() {
            return ;
        }
    }
New to GrepCode? Check out our FAQ X