private static void generateNameByString(
      Set<String> possibleNames,
      String value,
      NameValidator validator,
      boolean forStaticVariable,
      Project project) {
    if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(value)) return;
    if (forStaticVariable) {
      StringBuilder buffer = new StringBuilder(value.length() + 10);
      char[] chars = new char[value.length()];
      value.getChars(0, value.length(), chars, 0);
      boolean wasLow = Character.isLowerCase(chars[0]);

      buffer.append(Character.toUpperCase(chars[0]));
      for (int i = 1; i < chars.length; i++) {
        if (Character.isUpperCase(chars[i])) {
          if (wasLow) {
            buffer.append('_');
            wasLow = false;
          }
        } else {
          wasLow = true;
        }

        buffer.append(Character.toUpperCase(chars[i]));
      }
      possibleNames.add(validator.validateName(buffer.toString(), true));
    } else {
      possibleNames.add(validator.validateName(value, true));
    }
  }
Example #2
0
  private String variableNameToPropertyNameInner(String name, VariableKind variableKind) {
    String prefix = getPrefixByVariableKind(variableKind);
    String suffix = getSuffixByVariableKind(variableKind);
    boolean doDecapitalize = false;

    int pLength = prefix.length();
    if (pLength > 0
        && name.startsWith(prefix)
        && name.length() > pLength
        &&
        // check it's not just a long camel word that happens to begin with the specified prefix
        (!Character.isLetter(prefix.charAt(pLength - 1))
            || Character.isUpperCase(name.charAt(pLength)))) {
      name = name.substring(pLength);
      doDecapitalize = true;
    }

    if (name.endsWith(suffix) && name.length() > suffix.length()) {
      name = name.substring(0, name.length() - suffix.length());
      doDecapitalize = true;
    }

    if (doDecapitalize) {
      name = Introspector.decapitalize(name);
    }

    return name;
  }
Example #3
0
  @Override
  public String variableNameToPropertyName(String name, VariableKind variableKind) {
    if (variableKind == VariableKind.STATIC_FINAL_FIELD
        || variableKind == VariableKind.STATIC_FIELD && name.contains("_")) {
      StringBuilder buffer = new StringBuilder();
      for (int i = 0; i < name.length(); i++) {
        char c = name.charAt(i);
        if (c != '_') {
          if (Character.isLowerCase(c)) {
            return variableNameToPropertyNameInner(name, variableKind);
          }

          buffer.append(Character.toLowerCase(c));
          continue;
        }
        //noinspection AssignmentToForLoopParameter
        i++;
        if (i < name.length()) {
          c = name.charAt(i);
          buffer.append(c);
        }
      }
      return buffer.toString();
    }

    return variableNameToPropertyNameInner(name, variableKind);
  }
  private static void autoImport(final PsiFile file, int offset, final Editor editor) {
    final CharSequence text = editor.getDocument().getCharsSequence();
    while (offset > 0 && Character.isJavaIdentifierPart(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0 || text.charAt(offset) != '.') return;

    offset--;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    PsiJavaCodeReferenceElement element =
        extractReference(
            PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiExpression.class, false));
    if (element == null) return;

    while (true) {
      final PsiJavaCodeReferenceElement qualifier = extractReference(element.getQualifier());
      if (qualifier == null) break;

      element = qualifier;
    }
    if (!(element.getParent() instanceof PsiMethodCallExpression)
        && element.multiResolve(true).length == 0) {
      new ImportClassFix(element).doFix(editor, false, false);
    }
  }
 private boolean findClassOrPackageAtFirst() {
   final String name = getReferenceName();
   if (name == null || name.length() == 0 || hasAt()) return false;
   return Character.isUpperCase(name.charAt(0))
       || getParent() instanceof GrReferenceExpressionImpl
           && ((GrReferenceExpressionImpl) getParent()).findClassOrPackageAtFirst();
 }
Example #6
0
 private String getPrefix() {
   final Class<? extends Intention> aClass = getClass();
   final String name = aClass.getSimpleName();
   final StringBuilder buffer = new StringBuilder(name.length() + 10);
   buffer.append(Character.toLowerCase(name.charAt(0)));
   for (int i = 1; i < name.length(); i++) {
     final char c = name.charAt(i);
     if (Character.isUpperCase(c)) {
       buffer.append('.');
       buffer.append(Character.toLowerCase(c));
     } else {
       buffer.append(c);
     }
   }
   return buffer.toString();
 }
  private boolean findClassOrPackageAtFirst() {
    final String name = getReferenceName();
    if (StringUtil.isEmpty(name) || hasAt()) return false;

    return Character.isUpperCase(name.charAt(0)) && !isMethodCallRef()
        || getParent() instanceof GrReferenceExpressionImpl
            && ((GrReferenceExpressionImpl) getParent()).findClassOrPackageAtFirst();
  }
Example #8
0
 private static String rTrim(String text) {
   int idx = text.length();
   while (idx > 0) {
     if (!Character.isWhitespace(text.charAt(idx - 1))) break;
     idx--;
   }
   return text.substring(0, idx);
 }
 private static String truncDigits(String name) {
   int count = name.length() - 1;
   while (count >= 0) {
     char c = name.charAt(count);
     if (!Character.isDigit(c)) break;
     count--;
   }
   return name.substring(0, count + 1);
 }
 private static int handleSpaces(String line, int pos, int delta, boolean skip) {
   int len = line.length();
   while (pos >= 0 && pos < len) {
     final char c = line.charAt(pos);
     if (skip != Character.isSpaceChar(c)) break;
     pos += delta;
   }
   return pos;
 }
Example #11
0
 /**
  * Convinient conversion of testSomeTest -> someTest | SomeTest where testSomeTest is the name of
  * current test.
  *
  * @param lowercaseFirstLetter - whether first letter after test should be lowercased.
  */
 protected String getTestName(boolean lowercaseFirstLetter) {
   String name = getName();
   assertTrue("Test name should start with 'test'", name.startsWith("test"));
   name = name.substring("test".length());
   if (lowercaseFirstLetter && !UsefulTestCase.isAllUppercaseName(name)) {
     name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
   }
   return name;
 }
 private static int getNewIndent(final PsiFile psiFile, final int firstWhitespace) {
   final Document document = psiFile.getViewProvider().getDocument();
   final int startOffset = document.getLineStartOffset(document.getLineNumber(firstWhitespace));
   int endOffset = startOffset;
   final CharSequence charsSequence = document.getCharsSequence();
   while (Character.isWhitespace(charsSequence.charAt(endOffset++))) ;
   final String newIndentStr = charsSequence.subSequence(startOffset, endOffset - 1).toString();
   return IndentHelperImpl.getIndent(
       psiFile.getProject(), psiFile.getFileType(), newIndentStr, true);
 }
Example #13
0
  private static void autoImport(
      @NotNull final PsiFile file, int offset, @NotNull final Editor editor) {
    final CharSequence text = editor.getDocument().getCharsSequence();
    while (offset > 0 && Character.isJavaIdentifierPart(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0 || text.charAt(offset) != '.') return;

    offset--;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    autoImportReference(
        file,
        editor,
        extractReference(
            PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiExpression.class, false)));
  }
  private static void registerAddImportFixes(
      GrReferenceElement refElement, @Nullable HighlightInfo info, final HighlightDisplayKey key) {
    final String referenceName = refElement.getReferenceName();
    //noinspection ConstantConditions
    if (StringUtil.isEmpty(referenceName)) return;
    if (!(refElement instanceof GrCodeReferenceElement)
        && Character.isLowerCase(referenceName.charAt(0))) return;
    if (refElement.getQualifier() != null) return;

    QuickFixAction.registerQuickFixAction(info, new GroovyAddImportAction(refElement), key);
  }
 private static String suggestNewName(Project project, PsiVariable variable) {
   // new name should not conflict with another variable at the variable declaration level and
   // usage level
   String name = variable.getName();
   // trim last digit to suggest variable names like i1,i2, i3...
   if (name.length() > 1 && Character.isDigit(name.charAt(name.length() - 1))) {
     name = name.substring(0, name.length() - 1);
   }
   name = "final" + StringUtil.capitalize(StringUtil.trimStart(name, "final"));
   return JavaCodeStyleManager.getInstance(project)
       .suggestUniqueVariableName(name, variable, true);
 }
Example #16
0
  private static String[] getSuggestionsByValue(final String stringValue) {
    List<String> result = new ArrayList<String>();
    StringBuffer currentWord = new StringBuffer();

    boolean prevIsUpperCase = false;

    for (int i = 0; i < stringValue.length(); i++) {
      final char c = stringValue.charAt(i);
      if (Character.isUpperCase(c)) {
        if (currentWord.length() > 0 && !prevIsUpperCase) {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
        currentWord.append(c);
      } else if (Character.isLowerCase(c)) {
        currentWord.append(Character.toUpperCase(c));
      } else if (Character.isJavaIdentifierPart(c) && c != '_') {
        if (Character.isJavaIdentifierStart(c) || currentWord.length() > 0 || !result.isEmpty()) {
          currentWord.append(c);
        }
      } else {
        if (currentWord.length() > 0) {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
      }

      prevIsUpperCase = Character.isUpperCase(c);
    }

    if (currentWord.length() > 0) {
      result.add(currentWord.toString());
    }
    return ArrayUtil.toStringArray(result);
  }
Example #17
0
  @SuppressWarnings({"HardCodedStringLiteral"})
  public static boolean hasGetterName(final PsiMethod method) {
    if (method == null) return false;

    if (method.isConstructor()) return false;

    String methodName = method.getName();
    PsiType returnType = method.getReturnType();
    if (methodName.startsWith("get") && methodName.length() > "get".length()) {
      if (Character.isLowerCase(methodName.charAt("get".length()))
          && (methodName.length() == "get".length() + 1
              || Character.isLowerCase(methodName.charAt("get".length() + 1)))) {
        return false;
      }
      if (returnType != null && PsiType.VOID.equals(returnType)) return false;
    } else if (methodName.startsWith("is")) {
      return isBoolean(returnType);
    } else {
      return false;
    }
    return true;
  }
  protected void reparse() {
    String str = myPathStringNonTrimmed;

    final List<FileReference> referencesList = new ArrayList<FileReference>();

    String separatorString = getSeparatorString(); // separator's length can be more then 1 char
    int sepLen = separatorString.length();
    int currentSlash = -sepLen;

    // skip white space
    while (currentSlash + sepLen < str.length()
        && Character.isWhitespace(str.charAt(currentSlash + sepLen))) {
      currentSlash++;
    }

    if (currentSlash + sepLen + sepLen < str.length()
        && str.substring(currentSlash + sepLen, currentSlash + sepLen + sepLen)
            .equals(separatorString)) {
      currentSlash += sepLen;
    }
    int index = 0;

    if (str.equals(separatorString)) {
      final FileReference fileReference =
          createFileReference(
              new TextRange(myStartInElement, myStartInElement + sepLen), index++, separatorString);
      referencesList.add(fileReference);
    }

    while (true) {
      final int nextSlash = str.indexOf(separatorString, currentSlash + sepLen);
      final String subreferenceText =
          nextSlash > 0
              ? str.substring(currentSlash + sepLen, nextSlash)
              : str.substring(currentSlash + sepLen);
      final FileReference ref =
          createFileReference(
              new TextRange(
                  myStartInElement + currentSlash + sepLen,
                  myStartInElement + (nextSlash > 0 ? nextSlash : str.length())),
              index++,
              subreferenceText);
      referencesList.add(ref);
      if ((currentSlash = nextSlash) < 0) {
        break;
      }
    }

    myReferences = referencesList.toArray(new FileReference[referencesList.size()]);
  }
Example #19
0
  protected static String findPrefixDefault(
      final PsiElement insertedElement, final int offset, @NotNull final ElementPattern trimStart) {
    String substr =
        insertedElement
            .getText()
            .substring(0, offset - insertedElement.getTextRange().getStartOffset());
    if (substr.length() == 0 || Character.isWhitespace(substr.charAt(substr.length() - 1)))
      return "";

    substr = substr.trim();

    int i = 0;
    while (substr.length() > i && trimStart.accepts(substr.charAt(i))) i++;
    return substr.substring(i).trim();
  }
Example #20
0
 private static String getDigitPrefix(final String indexName) {
   final StringBuilder builder = StringBuilderSpinAllocator.alloc();
   try {
     for (int i = 0; i < indexName.length(); i++) {
       final char c = indexName.charAt(i);
       if (Character.isDigit(c)) {
         builder.append(c);
       } else {
         break;
       }
     }
     return builder.toString();
   } finally {
     StringBuilderSpinAllocator.dispose(builder);
   }
 }
 /**
  * Getters/Setters are supposed to be kept with their associated property. Search the list of
  * entries to find the property and attach the setter.
  *
  * @param entries list of all items (methods, fields) in the class.
  */
 private void hookGetterToProperty(List<ClassContentsEntry> entries) {
   ListIterator<ClassContentsEntry> li = entries.listIterator();
   String property = MethodUtil.getPropertyName((PsiMethod) myEnd);
   while (li.hasNext()) {
     Object o = li.next();
     if (o instanceof FieldEntry) {
       FieldEntry fe = (FieldEntry) o;
       StringBuffer sb = new StringBuffer(fe.getName());
       sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
       if (fe.getGetterMethod() == null && property.equals(sb.toString())) {
         fe.setGetterMethod(this);
         myKeptWithProperty = true;
         break;
       }
     }
   }
 }
 public static RangeMarker insertTemporary(
     final int endOffset, final Document document, final String temporary) {
   final CharSequence chars = document.getCharsSequence();
   final int length = chars.length();
   final RangeMarker toDelete;
   if (endOffset < length && Character.isJavaIdentifierPart(chars.charAt(endOffset))) {
     document.insertString(endOffset, temporary);
     toDelete = document.createRangeMarker(endOffset, endOffset + 1);
   } else if (endOffset >= length) {
     toDelete = document.createRangeMarker(length, length);
   } else {
     toDelete = document.createRangeMarker(endOffset, endOffset);
   }
   toDelete.setGreedyToLeft(true);
   toDelete.setGreedyToRight(true);
   return toDelete;
 }
Example #23
0
  @SuppressWarnings("HardCodedStringLiteral")
  public static boolean isSimplePropertySetter(PsiMethod method) {
    if (method == null) return false;

    if (method.isConstructor()) return false;

    String methodName = method.getName();

    if (!(methodName.startsWith("set") && methodName.length() > "set".length())) return false;
    if (Character.isLowerCase(methodName.charAt("set".length()))) return false;

    if (method.getParameterList().getParametersCount() != 1) {
      return false;
    }

    final PsiType returnType = method.getReturnType();

    if (returnType == null || PsiType.VOID.equals(returnType)) {
      return true;
    }

    return Comparing.equal(PsiUtil.resolveClassInType(returnType), method.getContainingClass());
  }
Example #24
0
  @Override
  public String propertyNameToVariableName(String propertyName, VariableKind variableKind) {
    if (variableKind == VariableKind.STATIC_FINAL_FIELD) {
      String[] words = NameUtil.nameToWords(propertyName);
      StringBuilder buffer = new StringBuilder();
      for (int i = 0; i < words.length; i++) {
        String word = words[i];
        if (i > 0) {
          buffer.append("_");
        }
        buffer.append(StringUtil.toUpperCase(word));
      }
      return buffer.toString();
    }

    String prefix = getPrefixByVariableKind(variableKind);
    String name = propertyName;
    if (!name.isEmpty() && !prefix.isEmpty() && !StringUtil.endsWithChar(prefix, '_')) {
      name = Character.toUpperCase(name.charAt(0)) + name.substring(1);
    }
    name = prefix + name + getSuffixByVariableKind(variableKind);
    name = changeIfNotIdentifier(name);
    return name;
  }
Example #25
0
 public void append(char name) {
   append(Character.toString(name));
 }