Example #1
0
 private UTF8String toTitleCaseSlow() {
   StringBuffer sb = new StringBuffer();
   String s = toString();
   sb.append(s);
   sb.setCharAt(0, Character.toTitleCase(sb.charAt(0)));
   for (int i = 1; i < s.length(); i++) {
     if (sb.charAt(i - 1) == ' ') {
       sb.setCharAt(i, Character.toTitleCase(sb.charAt(i)));
     }
   }
   return fromString(sb.toString());
 }
Example #2
0
  /** Returns the title case of this string, that could be used as title. */
  public UTF8String toTitleCase() {
    if (numBytes == 0) {
      return EMPTY_UTF8;
    }

    byte[] bytes = new byte[numBytes];
    for (int i = 0; i < numBytes; i++) {
      byte b = getByte(i);
      if (i == 0 || getByte(i - 1) == ' ') {
        if (numBytesForFirstByte(b) != 1) {
          // fallback
          return toTitleCaseSlow();
        }
        int upper = Character.toTitleCase(b);
        if (upper > 127) {
          // fallback
          return toTitleCaseSlow();
        }
        bytes[i] = (byte) upper;
      } else {
        bytes[i] = b;
      }
    }
    return fromBytes(bytes);
  }
Example #3
0
 /** Returns the setter-method for the given field name or null if no setter exists. */
 public static Method getSetter(String fieldName, Class<?> clazz, Class<?> fieldType) {
   String setterName =
       "set"
           + Character.toTitleCase(fieldName.charAt(0))
           + fieldName.substring(1, fieldName.length());
   try {
     // Using getMathods(), getMathod(...) expects exact parameter type
     // matching and ignores inheritance-tree.
     Method[] methods = clazz.getMethods();
     for (Method method : methods) {
       if (method.getName().equals(setterName)) {
         Class<?>[] paramTypes = method.getParameterTypes();
         if (paramTypes != null
             && paramTypes.length == 1
             && paramTypes[0].isAssignableFrom(fieldType)) {
           return method;
         }
       }
     }
     return null;
   } catch (SecurityException e) {
     throw new ActivitiException(
         "Not allowed to access method " + setterName + " on class " + clazz.getCanonicalName());
   }
 }
Example #4
0
  /**
   * 功能:切换字符串中的所有字母大小写。<br>
   *
   * <pre>
   * StringUtil.swapCase(null)                 = null
   * StringUtil.swapCase("")                   = ""
   * StringUtil.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
   * </pre>
   *
   * @param str 源字符串
   * @return String
   */
  public static String swapCase(String str) {
    if (StringUtil.isEmpty(str)) {
      return str;
    }
    char[] buffer = str.toCharArray();

    boolean whitespace = true;

    for (int i = 0; i < buffer.length; i++) {
      char ch = buffer[i];
      if (Character.isUpperCase(ch)) {
        buffer[i] = Character.toLowerCase(ch);
        whitespace = false;
      } else if (Character.isTitleCase(ch)) {
        buffer[i] = Character.toLowerCase(ch);
        whitespace = false;
      } else if (Character.isLowerCase(ch)) {
        if (whitespace) {
          buffer[i] = Character.toTitleCase(ch);
          whitespace = false;
        } else {
          buffer[i] = Character.toUpperCase(ch);
        }
      } else {
        whitespace = Character.isWhitespace(ch);
      }
    }
    return new String(buffer);
  }
Example #5
0
 protected Method getMethod(Class<?> beanClass) {
   String methodName =
       "is" + Character.toTitleCase(getFieldName().charAt(0)) + getFieldName().substring(1);
   try {
     return beanClass.getMethod(methodName);
   } catch (NoSuchMethodException e) {
   }
   return null;
 }
Example #6
0
 /**
  * capitalize the first character
  *
  * @param str
  * @return
  */
 public static String capitalize(String str) {
   int strLen;
   if (str == null || (strLen = str.length()) == 0) {
     return str;
   }
   return new StringBuilder(strLen)
       .append(Character.toTitleCase(str.charAt(0)))
       .append(str.substring(1))
       .toString();
 }
Example #7
0
  /** We're using setter injection, create and populate a bean using property setters */
  private Object createUsingSetterInjection(
      Class<?> paramType, InboundVariable data, Map<String, String> tokens)
      throws InstantiationException, IllegalAccessException {
    Object bean;
    if (instanceType != null) {
      bean = instanceType.newInstance();
    } else {
      bean = paramType.newInstance();
    }

    // We should put the new object into the working map in case it
    // is referenced later nested down in the conversion process.
    if (instanceType != null) {
      data.getContext().addConverted(data, instanceType, bean);
    } else {
      data.getContext().addConverted(data, paramType, bean);
    }

    Map<String, Property> properties = getPropertyMapFromObject(bean, false, true);

    for (Entry<String, String> entry : tokens.entrySet()) {
      String key = entry.getKey();

      // TODO: We don't URL decode method names we probably should. This is $dwr
      // TODO: We should probably have stripped these out already
      if (key.startsWith("%24dwr")) {
        continue;
      }

      Property property = properties.get(key);
      if (property == null) {
        log.warn(
            "Missing setter: "
                + paramType.getName()
                + ".set"
                + Character.toTitleCase(key.charAt(0))
                + key.substring(1)
                + "() to match javascript property: "
                + key
                + ". Check include/exclude rules and overloaded methods.");
        continue;
      }

      Object output =
          convert(entry.getValue(), property.getPropertyType(), data.getContext(), property);
      property.setValue(bean, output);
    }
    return bean;
  }
Example #8
0
  public static String toTitleCase(String input) {
    String[] words = WORD_BOUNDARIES.split(input);

    StringBuilder result = new StringBuilder();

    for (String word : words) {
      if (result.length() > 0) {
        result.append(" ");
      }
      result.append(Character.toTitleCase(word.charAt(0)));
      result.append(word.substring(1));
    }

    return result.toString();
  }
 /**
  * Upper case each word in the phrase. For example, convert "line item" to "Line Item". Converts
  * "p&l" to "P&L".
  *
  * <p>More formally, a word is considered to be any contiguous string of letters, digits, hyphens
  * or single quotes. Everything else is considered a delimiter.
  *
  * <p>Hyphens and single quotes aren't considered delimiters because they are often used in
  * contractions, possessives and compound words.
  *
  * @param phrase, the String to alter.
  * @return the input with each word capitalized.
  */
 public static String upperCaseEachWord(final String phrase) {
   boolean isInWord = false;
   final char[] res = new char[phrase.length()];
   for (int i = 0; i < res.length; i++) {
     char ch = phrase.charAt(i);
     if (Character.isLetterOrDigit(ch)) {
       if (!isInWord) {
         ch = Character.toTitleCase(ch);
         isInWord = true;
       }
     } else if ((ch == '\'' || ch == '-') && isInWord) {
       // do not exit being in the word--this is a contraction or possesive, or hyphened word
     } else isInWord = false;
     res[i] = ch;
   }
   return new String(res);
 }
Example #10
0
  public static String toTitleCase(String input) {
    StringBuilder titleCase = new StringBuilder();
    boolean nextTitleCase = true;

    for (char c : input.toCharArray()) {
      if (Character.isSpaceChar(c)) {
        nextTitleCase = true;
      } else if (nextTitleCase) {
        c = Character.toTitleCase(c);
        nextTitleCase = false;
      }

      titleCase.append(c);
    }

    return titleCase.toString();
  }
 private static ResourceBundle searchBundleByName(String bundleName, Locale locale) {
   bundleName = bundleName.replaceFirst("^" + RESOURCES_PREFIX, "");
   bundleName = bundleName.replace(RESOURCES_SUFFIX + "$", "");
   if (bundleName.length() >= 1) {
     bundleName = Character.toTitleCase(bundleName.charAt(0)) + bundleName.substring(1);
   }
   try {
     return getBundle(bundleName, locale);
   } catch (MissingResourceException e) {
     try {
       if (bundleName.length() >= 1) {
         bundleName = bundleName.charAt(0) + bundleName.substring(1).toLowerCase();
       }
       return getBundle(bundleName, locale);
     } catch (MissingResourceException ex) {
       return getBundle(bundleName.toUpperCase(), locale);
     }
   }
 }
Example #12
0
  /** Returns the lower case of this string */
  public UTF8String toLowerCase() {
    if (numBytes == 0) {
      return EMPTY_UTF8;
    }

    byte[] bytes = new byte[numBytes];
    bytes[0] = (byte) Character.toTitleCase(getByte(0));
    for (int i = 0; i < numBytes; i++) {
      byte b = getByte(i);
      if (numBytesForFirstByte(b) != 1) {
        // fallback
        return toLowerCaseSlow();
      }
      int lower = Character.toLowerCase((int) b);
      if (lower > 127) {
        // fallback
        return toLowerCaseSlow();
      }
      bytes[i] = (byte) lower;
    }
    return fromBytes(bytes);
  }
 private String capitalize(String string) {
   return new StringBuilder(string.length())
       .append(Character.toTitleCase(string.charAt(0)))
       .append(string.substring(1))
       .toString();
 }
Example #14
0
 public static String titlecase(String str) {
   return (Character.toTitleCase(str.charAt(0)) + str.substring(1));
 }
Example #15
0
  @Override
  public void handle(
      AnnotationValues<Builder> annotation, JCAnnotation ast, JavacNode annotationNode) {
    handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.BUILDER_FLAG_USAGE, "@Builder");

    Builder builderInstance = annotation.getInstance();
    String builderMethodName = builderInstance.builderMethodName();
    String buildMethodName = builderInstance.buildMethodName();
    String builderClassName = builderInstance.builderClassName();

    if (builderMethodName == null) builderMethodName = "builder";
    if (buildMethodName == null) buildMethodName = "build";
    if (builderClassName == null) builderClassName = "";

    if (!checkName("builderMethodName", builderMethodName, annotationNode)) return;
    if (!checkName("buildMethodName", buildMethodName, annotationNode)) return;
    if (!builderClassName.isEmpty()) {
      if (!checkName("builderClassName", builderClassName, annotationNode)) return;
    }

    deleteAnnotationIfNeccessary(annotationNode, Builder.class);
    deleteImportFromCompilationUnit(annotationNode, "lombok.experimental.Builder");

    JavacNode parent = annotationNode.up();

    java.util.List<JCExpression> typesOfParameters = new ArrayList<JCExpression>();
    java.util.List<Name> namesOfParameters = new ArrayList<Name>();
    JCExpression returnType;
    List<JCTypeParameter> typeParams = List.nil();
    List<JCExpression> thrownExceptions = List.nil();
    Name nameOfStaticBuilderMethod;
    JavacNode tdParent;

    JCMethodDecl fillParametersFrom =
        parent.get() instanceof JCMethodDecl ? ((JCMethodDecl) parent.get()) : null;

    if (parent.get() instanceof JCClassDecl) {
      tdParent = parent;
      JCClassDecl td = (JCClassDecl) tdParent.get();
      ListBuffer<JavacNode> allFields = new ListBuffer<JavacNode>();
      @SuppressWarnings("deprecation")
      boolean valuePresent =
          (hasAnnotation(lombok.Value.class, parent)
              || hasAnnotation(lombok.experimental.Value.class, parent));
      for (JavacNode fieldNode : HandleConstructor.findAllFields(tdParent)) {
        JCVariableDecl fd = (JCVariableDecl) fieldNode.get();
        // final fields with an initializer cannot be written to, so they can't be 'builderized'.
        // Unfortunately presence of @Value makes
        // non-final fields final, but @Value's handler hasn't done this yet, so we have to do this
        // math ourselves.
        // Value will only skip making a field final if it has an explicit @NonFinal annotation, so
        // we check for that.
        if (fd.init != null && valuePresent && !hasAnnotation(NonFinal.class, fieldNode)) continue;
        namesOfParameters.add(removePrefixFromField(fieldNode));
        typesOfParameters.add(fd.vartype);
        allFields.append(fieldNode);
      }

      new HandleConstructor()
          .generateConstructor(
              tdParent,
              AccessLevel.PACKAGE,
              List.<JCAnnotation>nil(),
              allFields.toList(),
              null,
              SkipIfConstructorExists.I_AM_BUILDER,
              null,
              annotationNode);

      returnType = namePlusTypeParamsToTypeReference(tdParent.getTreeMaker(), td.name, td.typarams);
      typeParams = td.typarams;
      thrownExceptions = List.nil();
      nameOfStaticBuilderMethod = null;
      if (builderClassName.isEmpty()) builderClassName = td.name.toString() + "Builder";
    } else if (fillParametersFrom != null
        && fillParametersFrom.getName().toString().equals("<init>")) {
      if (!fillParametersFrom.typarams.isEmpty()) {
        annotationNode.addError(
            "@Builder is not supported on constructors with constructor type parameters.");
        return;
      }
      tdParent = parent.up();
      JCClassDecl td = (JCClassDecl) tdParent.get();
      returnType = namePlusTypeParamsToTypeReference(tdParent.getTreeMaker(), td.name, td.typarams);
      typeParams = td.typarams;
      thrownExceptions = fillParametersFrom.thrown;
      nameOfStaticBuilderMethod = null;
      if (builderClassName.isEmpty()) builderClassName = td.name.toString() + "Builder";
    } else if (fillParametersFrom != null) {
      tdParent = parent.up();
      JCClassDecl td = (JCClassDecl) tdParent.get();
      if ((fillParametersFrom.mods.flags & Flags.STATIC) == 0) {
        annotationNode.addError(
            "@Builder is only supported on types, constructors, and static methods.");
        return;
      }
      returnType = fillParametersFrom.restype;
      typeParams = fillParametersFrom.typarams;
      thrownExceptions = fillParametersFrom.thrown;
      nameOfStaticBuilderMethod = fillParametersFrom.name;
      if (builderClassName.isEmpty()) {
        if (returnType instanceof JCTypeApply) {
          returnType = ((JCTypeApply) returnType).clazz;
        }
        if (returnType instanceof JCFieldAccess) {
          builderClassName = ((JCFieldAccess) returnType).name.toString() + "Builder";
        } else if (returnType instanceof JCIdent) {
          Name n = ((JCIdent) returnType).name;

          for (JCTypeParameter tp : typeParams) {
            if (tp.name.equals(n)) {
              annotationNode.addError(
                  "@Builder requires specifying 'builderClassName' if used on methods with a type parameter as return type.");
              return;
            }
          }
          builderClassName = n.toString() + "Builder";
        } else if (returnType instanceof JCPrimitiveTypeTree) {
          builderClassName = returnType.toString() + "Builder";
          if (Character.isLowerCase(builderClassName.charAt(0))) {
            builderClassName =
                Character.toTitleCase(builderClassName.charAt(0)) + builderClassName.substring(1);
          }

        } else {
          // This shouldn't happen.
          System.err.println(
              "Lombok bug ID#20140614-1651: javac HandleBuilder: return type to name conversion failed: "
                  + returnType.getClass());
          builderClassName = td.name.toString() + "Builder";
        }
      }
    } else {
      annotationNode.addError(
          "@Builder is only supported on types, constructors, and static methods.");
      return;
    }

    if (fillParametersFrom != null) {
      for (JCVariableDecl param : fillParametersFrom.params) {
        namesOfParameters.add(param.name);
        typesOfParameters.add(param.vartype);
      }
    }

    JavacNode builderType = findInnerClass(tdParent, builderClassName);
    if (builderType == null) {
      builderType = makeBuilderClass(tdParent, builderClassName, typeParams, ast);
    } else {
      sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(builderType, annotationNode);
    }
    java.util.List<JavacNode> fieldNodes =
        addFieldsToBuilder(builderType, namesOfParameters, typesOfParameters, ast);
    java.util.List<JCMethodDecl> newMethods = new ArrayList<JCMethodDecl>();
    for (JavacNode fieldNode : fieldNodes) {
      JCMethodDecl newMethod =
          makeSetterMethodForBuilder(
              builderType,
              fieldNode,
              annotationNode,
              builderInstance.fluent(),
              builderInstance.chain());
      if (newMethod != null) newMethods.add(newMethod);
    }

    if (constructorExists(builderType) == MemberExistsResult.NOT_EXISTS) {
      JCMethodDecl cd =
          HandleConstructor.createConstructor(
              AccessLevel.PACKAGE,
              List.<JCAnnotation>nil(),
              builderType,
              List.<JavacNode>nil(),
              null,
              annotationNode);
      if (cd != null) injectMethod(builderType, cd);
    }

    for (JCMethodDecl newMethod : newMethods) injectMethod(builderType, newMethod);

    if (methodExists(buildMethodName, builderType, -1) == MemberExistsResult.NOT_EXISTS) {
      JCMethodDecl md =
          generateBuildMethod(
              buildMethodName,
              nameOfStaticBuilderMethod,
              returnType,
              namesOfParameters,
              builderType,
              thrownExceptions);
      if (md != null) injectMethod(builderType, md);
    }

    if (methodExists("toString", builderType, 0) == MemberExistsResult.NOT_EXISTS) {
      JCMethodDecl md =
          HandleToString.createToString(
              builderType, fieldNodes, true, false, FieldAccess.ALWAYS_FIELD, ast);
      if (md != null) injectMethod(builderType, md);
    }

    if (methodExists(builderMethodName, tdParent, -1) == MemberExistsResult.NOT_EXISTS) {
      JCMethodDecl md =
          generateBuilderMethod(builderMethodName, builderClassName, tdParent, typeParams);
      if (md != null) injectMethod(tdParent, md);
    }
  }
 public static String toTitleCase(String in) {
   if (in.isEmpty()) return in;
   return "" + Character.toTitleCase(in.charAt(0)) + in.substring(1).toLowerCase();
 }