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));
    }
  }
示例#2
0
  public static String normalizeCamelCase(String s) {
    StringBuilder sb = new StringBuilder();

    boolean upperCase = false;

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      boolean nextUpperCase = true;
      if (i < (s.length() - 1)) {
        nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
      }

      if ((i > 0) && Character.isUpperCase(c)) {
        if (upperCase && nextUpperCase) {
          c = Character.toLowerCase(c);
        }

        upperCase = true;
      } else {
        upperCase = false;
      }

      sb.append(c);
    }

    return sb.toString();
  }
示例#3
0
  public static String fromCamelCase(String s, char delimiter) {
    StringBuilder sb = new StringBuilder();

    boolean upperCase = false;

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      boolean nextUpperCase = true;

      if (i < (s.length() - 1)) {
        nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
      }

      if ((i > 0) && Character.isUpperCase(c)) {
        if (!upperCase || !nextUpperCase) {
          sb.append(delimiter);
        }

        c = Character.toLowerCase(c);

        upperCase = true;
      } else {
        upperCase = false;
      }

      sb.append(c);
    }

    return sb.toString();
  }
示例#4
0
 /**
  * creates a NewAnnotationAction from the input processed by StreamTokenizer <I>tok</I>, which
  * should have the form <br>
  * add [type feature=value feature=value ...] <br>
  * or <br>
  * add [type feature=value feature=value ...] over spanVariable
  */
 public NewAnnotationAction(StreamTokenizer tok) throws IOException, PatternSyntaxError {
   if (tok.nextToken() == StreamTokenizer.TT_WORD && Character.isUpperCase(tok.sval.charAt(0))) {
     bindingVariable = new Variable(tok.sval);
     if (tok.nextToken() != '=') throw new PatternSyntaxError("= expected");
     tok.nextToken();
   }
   if (tok.ttype != '[') throw new PatternSyntaxError("[ expected");
   if (tok.nextToken() != StreamTokenizer.TT_WORD)
     throw new PatternSyntaxError("annotation type expected");
   type = tok.sval;
   features = new FeatureSet(tok, true, ']');
   if (tok.nextToken() == StreamTokenizer.TT_WORD && tok.sval.equalsIgnoreCase("over")) {
     if (tok.nextToken() == StreamTokenizer.TT_WORD && Character.isUpperCase(tok.sval.charAt(0))) {
       spanVariable = new Variable(tok.sval);
       tok.nextToken();
     } else if (tok.ttype == StreamTokenizer.TT_NUMBER && tok.nval == 0) {
       spanVariable = new Variable("0");
       tok.nextToken();
     } else {
       throw new PatternSyntaxError("variable expected after 'over'");
     }
   } else {
     spanVariable = null;
   }
 }
示例#5
0
 /**
  * Construct a JSONObject from an Object using bean getters. It reflects on all of the public
  * methods of the object. For each of the methods with no parameters and a name starting with
  * <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, the method is invoked,
  * and a key and the value returned from the getter method are put into the new JSONObject.
  *
  * <p>The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. If the
  * second remaining character is not upper case, then the first character is converted to lower
  * case.
  *
  * <p>For example, if an object has a method named <code>"getName"</code>, and if the result of
  * calling <code>object.getName()</code> is <code>"Larry Fine"</code>, then the JSONObject will
  * contain <code>"name": "Larry Fine"</code>.
  *
  * @param bean An object that has getter methods that should be used to make a JSONObject.
  */
 public JSONObject(Object bean) {
   this();
   Class klass = bean.getClass();
   Method[] methods = klass.getMethods();
   for (int i = 0; i < methods.length; i += 1) {
     try {
       Method method = methods[i];
       String name = method.getName();
       String key = "";
       if (name.startsWith("get")) {
         key = name.substring(3);
       } else if (name.startsWith("is")) {
         key = name.substring(2);
       }
       if (key.length() > 0
           && Character.isUpperCase(key.charAt(0))
           && method.getParameterTypes().length == 0) {
         if (key.length() == 1) {
           key = key.toLowerCase();
         } else if (!Character.isUpperCase(key.charAt(1))) {
           key = key.substring(0, 1).toLowerCase() + key.substring(1);
         }
         this.put(key, method.invoke(bean, (Object[]) null));
       }
     } catch (Exception e) {
       /* forget about it */
     }
   }
 }
 /**
  * Apply a processed input event.
  *
  * <p>All input events should be supported, including software/hardware events, characters as well
  * as deletions, multiple inputs and gestures.
  *
  * @param event the event to apply. Must not be null.
  */
 public void applyProcessedEvent(final Event event) {
   mCombinerChain.applyProcessedEvent(event);
   final int primaryCode = event.mCodePoint;
   final int keyX = event.mX;
   final int keyY = event.mY;
   final int newIndex = size();
   refreshTypedWordCache();
   mCursorPositionWithinWord = mCodePointSize;
   // We may have deleted the last one.
   if (0 == mCodePointSize) {
     mIsOnlyFirstCharCapitalized = false;
   }
   if (Constants.CODE_DELETE != event.mKeyCode) {
     if (newIndex < MAX_WORD_LENGTH) {
       // In the batch input mode, the {@code mInputPointers} holds batch input points and
       // shouldn't be overridden by the "typed key" coordinates
       // (See {@link #setBatchInputWord}).
       if (!mIsBatchMode) {
         // TODO: Set correct pointer id and time
         mInputPointers.addPointerAt(newIndex, keyX, keyY, 0, 0);
       }
     }
     if (0 == newIndex) {
       mIsOnlyFirstCharCapitalized = Character.isUpperCase(primaryCode);
     } else {
       mIsOnlyFirstCharCapitalized =
           mIsOnlyFirstCharCapitalized && !Character.isUpperCase(primaryCode);
     }
     if (Character.isUpperCase(primaryCode)) mCapsCount++;
     if (Character.isDigit(primaryCode)) mDigitsCount++;
   }
   mAutoCorrection = null;
 }
示例#7
0
  /**
   * 驼峰命名法工具
   *
   * @return toCamelCase("hello_world") == "helloWorld" toCapitalizeCamelCase("hello_world") ==
   *     "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world"
   */
  public static String toUnderScoreCase(String s) {
    if (s == null) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    boolean upperCase = false;
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      boolean nextUpperCase = true;

      if (i < (s.length() - 1)) {
        nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
      }

      if ((i > 0) && Character.isUpperCase(c)) {
        if (!upperCase || !nextUpperCase) {
          sb.append(SEPARATOR);
        }
        upperCase = true;
      } else {
        upperCase = false;
      }

      sb.append(Character.toLowerCase(c));
    }

    return sb.toString();
  }
  public static String javaToXMLName(String javaName) {

    // Strip "package name".
    int lastDot = javaName.lastIndexOf('.');
    if (lastDot != -1 && lastDot + 1 < javaName.length())
      javaName = javaName.substring(lastDot + 1);

    // Strip "inner class prefix".
    int lastDollar = javaName.lastIndexOf('$');
    if (lastDollar != -1) javaName = javaName.substring(lastDollar + 1);

    StringBuilder result = new StringBuilder();
    for (int i = 0; i < javaName.length(); i++) {
      // ASTWhen switch from lower to upper, add a dash before upper.
      if (i > 0
          && Character.isLowerCase(javaName.charAt(i - 1))
          && Character.isUpperCase(javaName.charAt(i))) result.append('-');
      // ASTWhen switch from upper to lower, add dash before upper.
      else if (i > 0
          && i < javaName.length() - 1
          && Character.isUpperCase(javaName.charAt(i))
          && Character.isLowerCase(javaName.charAt(i + 1))) result.append('-');
      result.append(Character.toLowerCase(javaName.charAt(i)));
    }
    return result.toString();
  }
 public static String camelCaseToWords(String camelCase, char separator) {
   // special case if short string
   if (camelCase == null || camelCase.length() <= 2) {
     return camelCase;
   }
   StringBuffer sb = new StringBuffer(camelCase.length() + 3);
   sb.append(camelCase.charAt(0));
   sb.append(camelCase.charAt(1));
   for (int i = 2; i < camelCase.length(); i++) {
     sb.append(camelCase.charAt(i));
     if (camelCase.charAt(i - 2) == separator) {
       continue;
     } else if (Character.isUpperCase(camelCase.charAt(i - 1))
         && Character.isLowerCase(camelCase.charAt(i))) {
       sb.insert(sb.length() - 2, separator);
     } else if (Character.isLowerCase(camelCase.charAt(i - 2))
         && Character.isUpperCase(camelCase.charAt(i - 1))
         && Character.isUpperCase(camelCase.charAt(i))) {
       sb.insert(sb.length() - 2, separator);
     }
   }
   // special case if last is upper
   if (Character.isUpperCase(sb.charAt(sb.length() - 1))
       && Character.isLowerCase(sb.charAt(sb.length() - 2))) {
     sb.insert(sb.length() - 1, ' ');
   }
   return sb.toString();
 }
示例#10
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);
  }
示例#11
0
  @Test
  public void testMapping() {
    List<String> input = Arrays.asList("Capital", "lower", "Foo", "bar");
    Collector<String, ?, Map<Boolean, Optional<Integer>>> collector =
        MoreCollectors.partitioningBy(
            str -> Character.isUpperCase(str.charAt(0)),
            MoreCollectors.mapping(String::length, MoreCollectors.first()));
    checkShortCircuitCollector(
        "mapping", new BooleanMap<>(Optional.of(7), Optional.of(5)), 2, input::stream, collector);
    Collector<String, ?, Map<Boolean, Optional<Integer>>> collectorLast =
        MoreCollectors.partitioningBy(
            str -> Character.isUpperCase(str.charAt(0)),
            MoreCollectors.mapping(String::length, MoreCollectors.last()));
    checkCollector(
        "last", new BooleanMap<>(Optional.of(3), Optional.of(3)), input::stream, collectorLast);

    input = Arrays.asList("Abc", "Bac", "Aac", "Abv", "Bbc", "Bgd", "Atc", "Bpv");
    Map<Character, List<String>> expected =
        EntryStream.of('A', Arrays.asList("Abc", "Aac"), 'B', Arrays.asList("Bac", "Bbc")).toMap();
    AtomicInteger cnt = new AtomicInteger();
    Collector<String, ?, Map<Character, List<String>>> groupMap =
        Collectors.groupingBy(
            s -> s.charAt(0),
            MoreCollectors.mapping(
                x -> {
                  cnt.incrementAndGet();
                  return x;
                },
                MoreCollectors.head(2)));
    checkCollector("groupMap", expected, input::stream, groupMap);
    cnt.set(0);
    assertEquals(expected, input.stream().collect(groupMap));
    assertEquals(4, cnt.get());
  }
  protected int seekNextCaretLocation(int pos, boolean forward) {

    int dir = forward ? 1 : -1;
    int e = forward ? textLength : 0;
    if (pos == textLength) {
      --pos;
    }
    char prevChar = text[pos];
    while (pos != e && Character.isSpaceChar(prevChar)) {
      prevChar = text[pos += dir];
    }

    if (smartCaret) {
      for (int i = pos; i != e; i += dir) {
        char curChar = text[i];
        boolean caze = Character.isUpperCase(curChar) != Character.isUpperCase(prevChar);
        if (caze
            || Character.isSpaceChar(curChar) != Character.isSpaceChar(prevChar)
            || Character.isLetterOrDigit(curChar) != Character.isLetterOrDigit(prevChar)) {
          if ((pos + dir) != i || !Character.isLetterOrDigit(curChar)) {
            return i + (smartCaretCase && caze && Character.isUpperCase(prevChar) ? -dir : 0);
          }
        }
        prevChar = curChar;
      }
    }
    for (int i = pos; i != e; i += dir) {
      char curChar = text[i];
      if (Character.isSpaceChar(curChar) != Character.isSpaceChar(prevChar)) {
        return i;
      }
    }
    return forward ? textLength : 0;
  }
示例#13
0
  public String getActionName() {

    // TODO 后期考虑优化为直接注入Struts的ActionNameBuilder方式
    String actionName = this.getClass().getSimpleName();
    String actionSuffix = "Controller";
    if (actionName.equals(actionSuffix))
      throw new IllegalStateException(
          "The action name cannot be the same as the action suffix [" + actionSuffix + "]");

    // Truncate Action suffix if found
    if (actionName.endsWith(actionSuffix)) {
      actionName = actionName.substring(0, actionName.length() - actionSuffix.length());
    }

    // Convert to underscores
    char[] ca = actionName.toCharArray();
    StringBuilder build = new StringBuilder("" + ca[0]);
    boolean lower = true;
    for (int i = 1; i < ca.length; i++) {
      char c = ca[i];
      if (Character.isUpperCase(c) && lower) {
        build.append("-");
        lower = false;
      } else if (!Character.isUpperCase(c)) {
        lower = true;
      }

      build.append(c);
    }

    actionName = build.toString();
    actionName = actionName.toLowerCase();

    return actionName;
  }
示例#14
0
  private void populateInternalMap(Object bean, boolean includeSuperClass) {
    Class klass = bean.getClass();

    /* If klass.getSuperClass is System class then force includeSuperClass to false. */

    if (klass.getClassLoader() == null) {
      includeSuperClass = false;
    }

    Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
      try {
        Method method = methods[i];
        if (Modifier.isPublic(method.getModifiers())) {
          String name = method.getName();
          String key = "";
          if (name.startsWith("get")) {
            key = name.substring(3);
          } else if (name.startsWith("is")) {
            key = name.substring(2);
          }
          if (key.length() > 0
              && Character.isUpperCase(key.charAt(0))
              && method.getParameterTypes().length == 0) {
            if (key.length() == 1) {
              key = key.toLowerCase();
            } else if (!Character.isUpperCase(key.charAt(1))) {
              key = key.substring(0, 1).toLowerCase() + key.substring(1);
            }

            Object result = method.invoke(bean, (Object[]) null);
            if (result == null) {
              map.put(key, NULL);
            } else if (result.getClass().isArray()) {
              map.put(key, new JSONArray(result, includeSuperClass));
            } else if (result instanceof Collection) { // List or Set
              map.put(key, new JSONArray((Collection) result, includeSuperClass));
            } else if (result instanceof Map) {
              map.put(key, new JSONObject((Map) result, includeSuperClass));
            } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper
              map.put(key, result);
            } else {
              if (result.getClass().getPackage().getName().startsWith("java")
                  || result.getClass().getClassLoader() == null) {
                map.put(key, result.toString());
              } else { // User defined Objects
                map.put(key, new JSONObject(result, includeSuperClass));
              }
            }
          }
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
示例#15
0
 private static String getGetter(String name, Class returnType) {
   if (name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3)))
     return Character.toLowerCase(name.charAt(3)) + name.substring(4);
   if ((returnType == boolean.class || returnType == Boolean.class)
       && name.length() > 2
       && name.startsWith("is")
       && Character.isUpperCase(name.charAt(2)))
     return Character.toLowerCase(name.charAt(2)) + name.substring(3);
   return name;
 }
示例#16
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Calculator response</title>");
    out.println("</head>");
    out.println("<body>");
    String sfirst = request.getParameter("First");
    String ssecond = request.getParameter("Second");
    String sAge = request.getParameter("Age");
    String sGender = request.getParameter("Gender");
    Boolean valid = true;
    String sM = "Client Information is valid";
    String fM = "Client Information is invalid";
    try {
      double age = Double.parseDouble(sAge);
      if ((age > 0) && (age < 120)) {
      } else {
        fM += "<br>invalid age";
        valid = false;
      }

      if (sGender.equals("M") || sGender.equals("F")) {
        valid = valid;
      } else {
        fM += "<br>invalid gender";
        valid = false;
      }

      if (sfirst.matches("[a-zA-Z]+")
          && ssecond.matches("[a-zA-Z]+")
          && Character.isUpperCase(sfirst.charAt(0))
          && Character.isUpperCase(ssecond.charAt(0))) {
      } else {
        valid = false;
        fM += "<br>invalid names";
      }
      if (valid) {
        out.println("<h1>" + sM + "</h1>");
      } else {
        out.println("<h1>" + fM + "</h1>");
      }

    } catch (Exception e) {
      out.println("<h1>Caught an exception. Check if you inputs are valid!</h1>");
    }

    out.println("</body>");
    out.println("</html>"); /* */
    out.close();
  }
示例#17
0
 public static String dbName(String javaName) {
   StringBuilder builder = new StringBuilder(javaName);
   for (int i = 1; i < builder.length(); i++) {
     boolean lastWasUpper = Character.isUpperCase(builder.charAt(i - 1));
     boolean isUpper = Character.isUpperCase(builder.charAt(i));
     if (isUpper && !lastWasUpper) {
       builder.insert(i, '_');
       i++;
     }
   }
   return builder.toString().toUpperCase();
 }
 private static String convertPropertyName(String prop) {
   if (prop.length() == 1) {
     return prop.toLowerCase();
   }
   if (Character.isUpperCase(prop.charAt(0)) && Character.isUpperCase(prop.charAt(1))) {
     return prop;
   }
   if (Character.isDigit(prop.charAt(0))) {
     return prop;
   }
   return Character.toLowerCase(prop.charAt(0)) + prop.substring(1);
 }
示例#19
0
  public void test_others() {
    // calling them just for completion
    // not supported		Character.getNumericValue( 'a' );
    // not supported		Character.getType( 'a' );

    //	  Character.isDefined( 'a' );//sgurin
    //	  Character.isDefined( '\uffff' );//sgurin

    Character.digit('\u0665', 10);
    Character.digit('\u06F5', 10);
    Character.digit('\u0968', 10);
    Character.digit('\u06E8', 10);
    Character.digit('\u0A68', 10);
    Character.digit('\u0AE8', 10);
    Character.digit('\u0B68', 10);
    Character.digit('\u0BE8', 10);
    Character.digit('\u0C68', 10);
    Character.digit('\u0CE8', 10);
    Character.digit('\u0D68', 10);
    Character.digit('\u0E52', 10);
    Character.digit('\u0ED2', 10);
    Character.digit('\uFF12', 10);
    Character.digit('\uFFFF', 10);

    // not supported		Character.isISOControl( 'a' );
    // not supported		Character.isIdentifierIgnorable( 'a' );
    // not supported		Character.isJavaIdentifierPart( 'a' );
    // not supported		Character.isJavaIdentifierStart( 'a' );
    // not supported		Character.isJavaLetter( 'a' );

    // sgurin: commented isJavaLetterOrDigir: nobt supported by j2s
    //	  Character.isJavaLetterOrDigit( 'a' );
    //	  harness.check(!(Character.isJavaLetterOrDigit('\uFFFF')),
    //	      "isJavaLetterOrDigit - 60");
    //	  harness.check(!(Character.isLetterOrDigit('\uFFFF')),
    //	      "isLetterOrDigit - 61");

    // not supported		Character.isLetter( 'a' );
    Character.isLetterOrDigit('a');
    Character.isLowerCase('A');
    Character.isLowerCase('a');
    Character.isWhitespace('a'); // sgurin Changed this to use non deprecated method

    // not supported		Character.isSpaceChar( 'a' );
    // not supported		Character.isTitleCase( 'a' );
    // not supported		Character.isUnicodeIdentifierPart( 'a' );
    // not supported		Character.isUnicodeIdentifierStart( 'a' );
    Character.isUpperCase('a');
    Character.isUpperCase('A');
    // not supported		Character.isWhitespace( 'a' );
    // not supported		Character.toTitleCase( 'a' );
  }
示例#20
0
  public void charactersToUpperCase(StringBuilder sb) {

    if (!Character.isUpperCase(sb.charAt(0))) {
      sb.replace(0, 1, String.valueOf(sb.charAt(0)).toUpperCase());
    }
    for (int i = 0; i < sb.length() - 2; i++) {

      if (sb.charAt(i) == '.' && !Character.isUpperCase(sb.charAt(i + 2))) {

        sb.replace(i + 2, i + 3, String.valueOf(sb.charAt(i + 2)).toUpperCase());
      }
    }
  }
  /**
   * Returns true if the name of the method specified and the number of arguments make it a javabean
   * property
   *
   * @param name True if its a Javabean property
   * @param args The arguments
   * @return true if it is a javabean property method
   */
  public static boolean isGetter(String name, Class<?>[] args) {
    if (!StringUtils.hasText(name) || args == null) return false;
    if (args.length != 0) return false;

    if (name.startsWith("get")) {
      name = name.substring(3);
      if (name.length() > 0 && Character.isUpperCase(name.charAt(0))) return true;
    } else if (name.startsWith("is")) {
      name = name.substring(2);
      if (name.length() > 0 && Character.isUpperCase(name.charAt(0))) return true;
    }
    return false;
  }
示例#22
0
 public static String convertNameForEnum(@NotNull String name) {
   StringBuilder builder = new StringBuilder();
   char[] chars = name.toCharArray();
   for (int i = 0; i < chars.length; i++) {
     if (Character.isUpperCase(chars[i])) {
       if (i > 0 && !Character.isUpperCase(chars[i - 1])) {
         builder.append("_");
       }
     }
     builder.append(chars[i]);
   }
   return builder.toString().toUpperCase();
 }
示例#23
0
 /**
  * Utility method to take a string and convert it to normal Java variable name capitalization.
  * This normally means converting the first character from upper case to lower case, but in the
  * (unusual) special case when there is more than one character and both the first and second
  * characters are upper case, we leave it alone.
  *
  * <p>Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".
  *
  * @param name The string to be decapitalized.
  * @return The decapitalized version of the string.
  */
 public static String decapitalize(String name) {
   if (name == null || name.length() == 0) {
     return name;
   }
   if (name.length() > 1
       && Character.isUpperCase(name.charAt(1))
       && Character.isUpperCase(name.charAt(0))) {
     return name;
   }
   char chars[] = name.toCharArray();
   chars[0] = Character.toLowerCase(chars[0]);
   return new String(chars);
 }
示例#24
0
  /**
   * Adds to the given list of property descriptors the mapped properties, ie. properties that have
   * a getter method taking a single String value as a parameter.
   *
   * @param clazz to introspect
   * @param result is the list to add to
   */
  protected static void addMappedProperties(Class clazz, List<InternalEventPropDescriptor> result) {
    Set<String> uniquePropertyNames = new HashSet<String>();
    Method[] methods = clazz.getMethods();

    for (int i = 0; i < methods.length; i++) {
      String methodName = methods[i].getName();
      if (!methodName.startsWith("get")) {
        continue;
      }

      String inferredName = methodName.substring(3, methodName.length());
      if (inferredName.length() == 0) {
        continue;
      }

      Class<?> parameterTypes[] = methods[i].getParameterTypes();
      if (parameterTypes.length != 1) {
        continue;
      }

      if (parameterTypes[0] != String.class) {
        continue;
      }

      String newInferredName = null;
      // Leave uppercase inferred names such as URL
      if (inferredName.length() >= 2) {
        if ((Character.isUpperCase(inferredName.charAt(0)))
            && (Character.isUpperCase(inferredName.charAt(1)))) {
          newInferredName = inferredName;
        }
      }
      // camelCase the inferred name
      if (newInferredName == null) {
        newInferredName = Character.toString(Character.toLowerCase(inferredName.charAt(0)));
        if (inferredName.length() > 1) {
          newInferredName += inferredName.substring(1, inferredName.length());
        }
      }
      inferredName = newInferredName;

      // if the property inferred name already exists, don't supply it
      if (uniquePropertyNames.contains(inferredName)) {
        continue;
      }

      result.add(
          new InternalEventPropDescriptor(inferredName, methods[i], EventPropertyType.MAPPED));
      uniquePropertyNames.add(inferredName);
    }
  }
  private boolean isFirstCharMatching(@NotNull String name, int nameIndex, int patternIndex) {
    if (nameIndex >= name.length()) return false;

    boolean ignoreCase = myOptions != NameUtil.MatchingCaseSensitivity.ALL;
    char patternChar = myPattern[patternIndex];
    if (!charEquals(patternChar, patternIndex, name.charAt(nameIndex), ignoreCase)) return false;

    if (myOptions == NameUtil.MatchingCaseSensitivity.FIRST_LETTER
        && (patternIndex == 0 || patternIndex == 1 && isWildcard(0))
        && Character.isUpperCase(patternChar) != Character.isUpperCase(name.charAt(0))) {
      return false;
    }
    return true;
  }
示例#26
0
  private RuleMatch ruleMatchWrongVerbSubject(
      final AnalyzedTokenReadings subject,
      final AnalyzedTokenReadings verb,
      final String expectedVerbPOS) {
    final String msg =
        "Möglicherweise fehlende grammatische Übereinstimmung zwischen Subjekt ("
            + subject.getToken()
            + ") und Prädikat ("
            + verb.getToken()
            + ") bezüglich Person oder Numerus (Einzahl, Mehrzahl - Beispiel: "
            + "'ich sind' statt 'ich bin').";

    List<String> suggestions = new ArrayList<>();
    List<String> verbSuggestions = new ArrayList<>();
    List<String> pronounSuggestions = new ArrayList<>();

    RuleMatch ruleMatch;
    if (subject.getStartPos() < verb.getStartPos()) {
      ruleMatch =
          new RuleMatch(
              this, subject.getStartPos(), verb.getStartPos() + verb.getToken().length(), msg);
      verbSuggestions.addAll(getVerbSuggestions(verb, expectedVerbPOS, false));
      for (String verbSuggestion : verbSuggestions) {
        suggestions.add(subject.getToken() + " " + verbSuggestion);
      }
      pronounSuggestions.addAll(
          getPronounSuggestions(verb, Character.isUpperCase(subject.getToken().charAt(0))));
      for (String pronounSuggestion : pronounSuggestions) {
        suggestions.add(pronounSuggestion + " " + verb.getToken());
      }
      ruleMatch.setSuggestedReplacements(suggestions);
    } else {
      ruleMatch =
          new RuleMatch(
              this, verb.getStartPos(), subject.getStartPos() + subject.getToken().length(), msg);
      verbSuggestions.addAll(
          getVerbSuggestions(
              verb, expectedVerbPOS, Character.isUpperCase(verb.getToken().charAt(0))));
      for (String verbSuggestion : verbSuggestions) {
        suggestions.add(verbSuggestion + " " + subject.getToken());
      }
      pronounSuggestions.addAll(getPronounSuggestions(verb, false));
      for (String pronounSuggestion : pronounSuggestions) {
        suggestions.add(verb.getToken() + " " + pronounSuggestion);
      }
      ruleMatch.setSuggestedReplacements(suggestions);
    }

    return ruleMatch;
  }
示例#27
0
 private static String getPackageName(final String qualifiedName, final boolean strict) {
   Splitter _on = Splitter.on(".");
   Iterable<String> _split = _on.split(qualifiedName);
   final List<String> segments = IterableExtensions.<String>toList(_split);
   int _size = segments.size();
   boolean _equals = (_size == 1);
   if (_equals) {
     return "";
   }
   if (strict) {
     int _length = ((Object[]) Conversions.unwrapArray(segments, Object.class)).length;
     int _minus = (_length - 1);
     final List<String> packageSegments = segments.subList(0, _minus);
     final Function1<String, Boolean> _function =
         (String it) -> {
           char _charAt = it.charAt(0);
           return Boolean.valueOf(Character.isUpperCase(_charAt));
         };
     Iterable<String> _filter = IterableExtensions.<String>filter(packageSegments, _function);
     boolean _isEmpty = IterableExtensions.isEmpty(_filter);
     boolean _not = (!_isEmpty);
     if (_not) {
       throw new IllegalArgumentException(
           (("Cannot determine the package name of \'" + qualifiedName)
               + "\'. Please use the TypeReference(packageName, className) constructor"));
     }
     return IterableExtensions.join(packageSegments, ".");
   } else {
     int _length_1 = ((Object[]) Conversions.unwrapArray(segments, Object.class)).length;
     int _minus_1 = (_length_1 - 1);
     List<String> packageSegments_1 = segments.subList(0, _minus_1);
     while ((!packageSegments_1.isEmpty())) {
       String _last = IterableExtensions.<String>last(packageSegments_1);
       char _charAt = _last.charAt(0);
       boolean _isUpperCase = Character.isUpperCase(_charAt);
       if (_isUpperCase) {
         final List<String> _converted_packageSegments_1 = (List<String>) packageSegments_1;
         int _length_2 =
             ((Object[]) Conversions.unwrapArray(_converted_packageSegments_1, Object.class))
                 .length;
         int _minus_2 = (_length_2 - 1);
         List<String> _subList = packageSegments_1.subList(0, _minus_2);
         packageSegments_1 = _subList;
       } else {
         return IterableExtensions.join(packageSegments_1, ".");
       }
     }
     return "";
   }
 }
  protected static String addUnderscores(String name, boolean pluralize) {
    StringBuffer buf = new StringBuffer(name.replace('.', '_'));
    for (int i = 1; i < buf.length() - 1; i++) {
      if (Character.isLowerCase(buf.charAt(i - 1))
          && Character.isUpperCase(buf.charAt(i))
          && Character.isLowerCase(buf.charAt(i + 1))) {
        buf.insert(i++, '_');
      }
    }

    if (pluralize) {
      String[] splitTableNameFragments = buf.toString().toLowerCase().split("_");

      StringBuffer buf2 = new StringBuffer();

      for (int i = 0; i < splitTableNameFragments.length; i++) {

        if (i < (splitTableNameFragments.length - 1)) {
          buf2.append(splitTableNameFragments[i]);
          buf2.append("_");
        } else {
          buf2.append(English.plural(splitTableNameFragments[i]));
        }
      }

      return buf2.toString().toUpperCase();
    }

    return buf.toString().toUpperCase();
  }
示例#29
0
  public static String reportKillData() {
    HashMap hm = getKillHashMap();

    ArrayList al = new ArrayList(hm.keySet());

    Collections.sort(al);

    StringBuffer sb = new StringBuffer();

    sb.append("You have killed the following creatures:\n");
    sb.append("\n");

    boolean uniques = true;

    for (Iterator it = al.iterator(); it.hasNext(); ) {
      String name = (String) it.next();

      // display line after uniques
      if (uniques && (!Character.isUpperCase(name.charAt(0)))) {
        uniques = false;
        sb.append("\n");
      }

      Integer count = (Integer) (hm.get(name));
      String g = Text.centrePad(name, count.toString(), 60);
      sb.append(g + "\n");
    }

    return sb.toString();
  }
 /**
  * Add a new keystroke, with codes[0] containing the pressed key's unicode and the rest of the
  * array containing unicode for adjacent keys, sorted by reducing probability/proximity.
  *
  * @param codes the array of unicode values
  */
 public void add(int primaryCode, int[] codes) {
   mTypedWord.append((char) primaryCode);
   correctPrimaryJuxtapos(primaryCode, codes);
   correctCodesCase(codes);
   mCodes.add(codes);
   if (Character.isUpperCase((char) primaryCode)) mCapsCount++;
 }