Example usage for org.apache.commons.lang3 StringUtils uncapitalize

List of usage examples for org.apache.commons.lang3 StringUtils uncapitalize

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils uncapitalize.

Prototype

public static String uncapitalize(final String str) 

Source Link

Document

Uncapitalizes a String, changing the first letter to lower case as per Character#toLowerCase(char) .

Usage

From source file:org.gvnix.addon.jpa.addon.batch.JpaBatchMetadata.java

/**
 * Return method to create a list of entities
 * //  www . j  av a 2 s  . c  o  m
 * @return
 */
private MethodMetadata getCreateMethod() {

    // Define parameters types

    List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType.convertFromJavaTypes(listOfEntitiesType);

    // Check if a method exist in type
    final MethodMetadata method = methodExists(CREATE_METHOD, parameterTypes);
    if (method != null) {
        // If it already exists, just return the method
        return method;
    }

    // Define method annotations (none in this case)
    List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    annotations.add(new AnnotationMetadataBuilder(SpringJavaType.TRANSACTIONAL));

    // Define method throws types (none in this case)
    List<JavaType> throwsTypes = new ArrayList<JavaType>();

    // Define method parameter names (none in this case)
    JavaSymbolName parameterName = new JavaSymbolName(StringUtils.uncapitalize(entityPlural));
    List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    parameterNames.add(parameterName);

    // --- Create the method body ---

    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();

    // for(Vet vet : vets) {
    // vet.persist();
    // }
    bodyBuilder.appendFormalLine(
            String.format("for( %s %s : %s) {", entityName, entityName.toLowerCase(), parameterName));
    bodyBuilder.indent();
    bodyBuilder.appendFormalLine(String.format("%s.persist();", entityName.toLowerCase()));
    bodyBuilder.indentRemove();
    bodyBuilder.appendFormalLine("}");

    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    JavaType returnType = JavaType.VOID_PRIMITIVE;
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, CREATE_METHOD,
            returnType, parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    methodBuilder.setThrowsTypes(throwsTypes);

    return methodBuilder.build(); // Build and return a MethodMetadata
                                  // instance
}

From source file:org.gvnix.addon.web.mvc.addon.batch.WebJpaBatchMetadata.java

public WebJpaBatchMetadata(String identifier, JavaType aspectName,
        PhysicalTypeMetadata governorPhysicalTypeMetadata, WebJpaBatchAnnotationValues annotationValues,
        JpaBatchMetadata jpaBatchMetadata, WebScaffoldAnnotationValues webScaffoldMetadataValue) {
    super(identifier, aspectName, governorPhysicalTypeMetadata);
    Validate.isTrue(isValid(identifier),
            "Metadata identification string '" + identifier + "' does not appear to be a valid");

    this.helper = new WebItdBuilderHelper(this, governorPhysicalTypeMetadata,
            builder.getImportRegistrationResolver());
    this.annotationValues = annotationValues;

    this.service = annotationValues.getService();

    Validate.notNull(service,// w w  w. ja v a  2s.  c om
            String.format("Missing service value required for %s in %s",
                    WebJpaBatchAnnotationValues.WEB_JPA_BATCH_ANNOTATION.getFullyQualifiedTypeName(),
                    governorPhysicalTypeMetadata.getType().getFullyQualifiedTypeName()));

    this.jpaBatchMetadata = jpaBatchMetadata;

    listOfIdentifiersType = jpaBatchMetadata.getListOfIdentifiersType();
    listOfEntityType = jpaBatchMetadata.getListOfEntitiesType();

    this.entity = jpaBatchMetadata.getEntity();

    this.entityName = JavaSymbolName.getReservedWordSafeName(entity).getSymbolName();

    this.entityIdentifier = jpaBatchMetadata.getEntityIdentifier();

    listOfEntityName = new JavaSymbolName(StringUtils.uncapitalize(jpaBatchMetadata.getEntityPlural()));

    jsonResponseList = new JavaType(JSON_RESPONSE.getFullyQualifiedTypeName(), 0, DataType.TYPE, null,
            Arrays.asList(listOfEntityType));

    Validate.notNull(this.entity, String.format("Missing entity value for %s in %s",
            GvNIXJpaBatch.class.getCanonicalName(), service.getFullyQualifiedTypeName()));

    Validate.isTrue(this.entity.equals(webScaffoldMetadataValue.getFormBackingObject()),
            String.format("Service batch entity and Controller formBackingObject no match in %s",
                    governorPhysicalTypeMetadata.getType().getFullyQualifiedTypeName()));
    // Adding field definition
    builder.addField(getConversionServiceField());
    builder.addField(getLoggerField());

    // Adding methods
    builder.addField(getServiceField());
    builder.addMethod(getDeleteMethod());
    builder.addMethod(getUpdateMethod());
    builder.addMethod(getCreateMethod());
    builder.addMethod(getGetOIDListMethod());
    builder.addMethod(getGetRequestPropertyValuesMethod());

    // Check if deleteBatch, createBatch or updateBatch are duplicated with
    // different name.
    checkIfExistsCUDMethods(governorTypeDetails);

    // Create a representation of the desired output ITD
    itdTypeDetails = builder.build();
}

From source file:org.gvnix.flex.entity.ActionScriptEntityMetadataProvider.java

private void processActionScriptTypeChanged(String asEntityId) {
    List<String> processedFields = new ArrayList<String>();

    ActionScriptType asType = ASPhysicalTypeIdentifier.getActionScriptType(asEntityId);

    JavaType javaType = ActionScriptMappingUtils.toJavaType(asType);
    String javaEntityId = PhysicalTypeIdentifier.createIdentifier(javaType,
            LogicalPath.getInstance(Path.SRC_MAIN_JAVA, ""));

    ClassOrInterfaceTypeDetails javaTypeDetails = getClassDetails(javaEntityId);

    // Nothing to do if Java class doesn't exist
    if (javaTypeDetails == null) {
        return;//from w w w . j a  va 2 s. c  o  m
    }

    ASMutableClassOrInterfaceTypeDetails asTypeDetails = getASClassDetails(asEntityId);

    // AS class was probably deleted, so nothing to do.
    if (asTypeDetails == null) {
        return;
    }

    // Verify that the ActionScript class is enabled for remoting
    if (!isRemotingClass(javaType, asTypeDetails)) {
        return;
    }

    List<String> javaFieldNames = new ArrayList<String>();
    for (FieldMetadata javaField : javaTypeDetails.getDeclaredFields()) {
        javaFieldNames.add(javaField.getFieldName().getSymbolName());
    }

    List<String> javaPropertyNames = new ArrayList<String>();
    MemberDetails memberDetails = scanForMemberDetails(javaTypeDetails);
    for (MethodMetadata method : MemberFindingUtils.getMethods(memberDetails)) {
        if (BeanInfoUtils.isAccessorMethod(method)) {
            javaPropertyNames.add(StringUtils
                    .uncapitalize(BeanInfoUtils.getPropertyNameForJavaBeanMethod(method).getSymbolName()));
        }
    }

    // TODO Next two fors refactored: it's ok ?
    ClassOrInterfaceTypeDetailsBuilder mutableTypeDetailsBuilder = new ClassOrInterfaceTypeDetailsBuilder(
            javaTypeDetails);

    // TODO - don't currently handle changing of field types because there
    // is no updateField() method on
    // MutablePhysicalTypeDetails
    // TODO - we don't currently create new JavaTypes that don't exist
    // because there is no simple "create entity"
    // operation for us to access

    // Add new fields - here we compare directly against property names
    // instead of fields so that we don't
    // mistakenly add fields that
    // might be ITD-only like version and id
    List<FieldMetadataBuilder> fields = new ArrayList<FieldMetadataBuilder>();
    for (ASFieldMetadata asField : asTypeDetails.getDeclaredFields()) {
        String fieldName = asField.getFieldName().getSymbolName();
        if (!javaPropertyNames.contains(fieldName)) {
            fields.add(new FieldMetadataBuilder(
                    ActionScriptMappingUtils.toFieldMetadata(javaEntityId, asField, true)));
        }
        processedFields.add(fieldName);
    }

    // TODO - how should we handle fields that don't exist in the
    // ActionScript object? For now we will just
    // remove...should
    // add some way to turn this off later.

    // Remove missing fields - here we are careful to only remove things for
    // wich there is an actual field in the
    // Java source, so the user
    // can't accidentally remove ITD-required fields like version and id
    for (String javaFieldName : javaFieldNames) {
        if (!processedFields.contains(javaFieldName)) {
            for (FieldMetadataBuilder fieldMetadata : fields) {
                if (fieldMetadata.getFieldName().getSymbolName().equals(javaFieldName)) {
                    fields.remove(fieldMetadata);
                }
            }
        }
    }

    fields.addAll(mutableTypeDetailsBuilder.getDeclaredFields());
    mutableTypeDetailsBuilder.setDeclaredFields(fields);
    getTypeManagementService().createOrUpdateTypeOnDisk(mutableTypeDetailsBuilder.build());

}

From source file:org.gvnix.flex.FlexScaffoldMetadata.java

public FlexScaffoldMetadata(String identifier, JavaType aspectName,
        PhysicalTypeMetadata governorPhysicalTypeMetadata, FlexScaffoldAnnotationValues annotationValues,
        JpaActiveRecordMetadata entityMetadata, Set<FinderMetadataDetails> dynamicFinderMethods,
        PersistenceMemberLocator persistenceMemberLocator) {

    super(identifier, aspectName, governorPhysicalTypeMetadata);

    Validate.isTrue(isValid(identifier),
            "Metadata identification string '" + identifier + "' does not appear to be a valid");
    Validate.notNull(entityMetadata, "Entity metadata required");

    if (!isValid()) {
        return;//from   w w  w . j  ava2s  . c o m
    }

    this.entityMetadata = entityMetadata;
    this.entity = annotationValues.getEntity();
    this.entityReference = StringUtils.uncapitalize(this.entity.getSimpleTypeName());
    this.persistenceMemberLocator = persistenceMemberLocator;

    this.builder.addMethod(getCreateMethod());
    this.builder.addMethod(getShowMethod());
    this.builder.addMethod(getListMethod());
    this.builder.addMethod(getListPagedMethod());
    this.builder.addMethod(getUpdateMethod());
    this.builder.addMethod(getRemoveMethod());

    this.itdTypeDetails = this.builder.build();

    new ItdSourceFileComposer(this.itdTypeDetails);
}

From source file:org.gvnix.service.roo.addon.addon.ws.export.WSExportValidationServiceImpl.java

/**
 * Add GvNIXWebFault with attributes to exception java type in project.
 * <ul>/*from  w ww.j av a 2s  .  c o m*/
 * <li>name: from uncapitalized java type simple type name</li>
 * <li>targetNamespace: from input parameter</li>
 * <li>faultBean: from java type fully qualified type name</li>
 * </ul>
 * 
 * @param targetNamespace Target namespace to add as annotation attribute
 * @param type Type to add annotation
 */
protected void addGvNixWebFaultAnnotation(String targetNamespace, JavaType type) {

    // Annotation attributes: name, target namespace and fault bean
    List<AnnotationAttributeValue<?>> attrs = new ArrayList<AnnotationAttributeValue<?>>();
    attrs.add(new StringAttributeValue(new JavaSymbolName("name"),
            StringUtils.uncapitalize(type.getSimpleTypeName())));
    attrs.add(new StringAttributeValue(new JavaSymbolName("targetNamespace"), targetNamespace));
    attrs.add(new StringAttributeValue(new JavaSymbolName("faultBean"), type.getFullyQualifiedTypeName()));

    // Add gvNIX web fault annotation to exception
    annotationsService.addJavaTypeAnnotation(type, GvNIXWebFault.class.getName(), attrs, false);
}

From source file:org.gvnix.service.roo.addon.addon.ws.export.WSExportValidationServiceImpl.java

/**
 * Add @GvNIXXmlElement annotation with attributes to java type.
 * <ul>//from ww w.j  a va 2s . c  o  m
 * <li>name attribute value from java type simple name</li>
 * <li>namespace attribute value from java type package</li>
 * <li>elementList attribute from all not transient fields (Java and AJs)</li>
 * <li>exported attribute is always false</li>
 * <li>xmlTypeName from java simple type, if not empty</li>
 * </ul>
 * 
 * @param javaType To get attributes for gvNIX annotation
 * @param typeName Type name to add annotation
 */
protected void addGvNixXmlElementAnnotation(JavaType javaType, JavaType typeName) {

    List<AnnotationAttributeValue<?>> attrs = new ArrayList<AnnotationAttributeValue<?>>();

    // name attribute value from java type simple name
    StringAttributeValue name = new StringAttributeValue(new JavaSymbolName("name"),
            StringUtils.uncapitalize(javaType.getSimpleTypeName()));
    attrs.add(name);

    // namespace attribute value from java type package
    StringAttributeValue namespace = new StringAttributeValue(new JavaSymbolName("namespace"),
            wSConfigService.convertPackageToTargetNamespace(javaType.getPackage().toString()));
    attrs.add(namespace);

    // Create attribute list with all (Java & AJs) no transient fields
    List<FieldMetadata> fields = javaParserService.getFieldsInAll(typeName);
    List<StringAttributeValue> values = new ArrayList<StringAttributeValue>();
    for (FieldMetadata field : fields) {

        // Transient fields can't have JAXB annotations (b.e. entityManager)
        if (field.getModifier() != Modifier.TRANSIENT) {

            // Create an attribute list with fields
            StringAttributeValue value = new StringAttributeValue(new JavaSymbolName("ignored"),
                    field.getFieldName().getSymbolName());
            if (!values.contains(value)) {
                values.add(value);
            }
        }
    }
    ArrayAttributeValue<StringAttributeValue> elements = new ArrayAttributeValue<StringAttributeValue>(
            new JavaSymbolName("elementList"), values);

    attrs.add(elements);

    // xmlTypeName from java type simple type, if not empty
    if (elements != null && !elements.getValue().isEmpty()) {

        StringAttributeValue xmlTypeName = new StringAttributeValue(new JavaSymbolName("xmlTypeName"),
                javaType.getSimpleTypeName());
        attrs.add(xmlTypeName);

    } else {

        StringAttributeValue xmlTypeName = new StringAttributeValue(new JavaSymbolName("xmlTypeName"), "");
        attrs.add(xmlTypeName);
    }

    // exported attribute is always false (when code first)
    BooleanAttributeValue exported = new BooleanAttributeValue(new JavaSymbolName("exported"), false);
    attrs.add(exported);

    annotationsService.addJavaTypeAnnotation(typeName, GvNIXXmlElement.class.getName(), attrs, false);
}

From source file:org.gvnix.web.datatables.util.DatatablesUtils.java

/**
 * Get Date formatter by field name//  w w w  .jav a 2s.c om
 * <p/>
 * If no pattern found, try standard Roo key
 * {@code uncapitalize( ENTITY ) + "_" + lower_case( FIELD ) + "_date_format"}
 * 
 * @param datePatterns Contains field name and related data pattern
 * @param entityClass Entity class to which the field belong to
 * @param fieldName Field to search pattern
 * @return
 */
private static SimpleDateFormat getDateFormatter(Map<String, Object> datePatterns,
        Map<String, SimpleDateFormat> dateFormatters, Class<?> entityClass, String fieldName) {

    SimpleDateFormat result = null;
    String lowerCaseFieldName = fieldName.toLowerCase();
    result = dateFormatters.get(lowerCaseFieldName);
    if (result != null) {
        return result;
    } else if (dateFormatters.containsKey(lowerCaseFieldName)) {
        return null;
    }

    // Get pattern by field name
    String pattern = (String) datePatterns.get(lowerCaseFieldName);
    if (StringUtils.isEmpty(pattern)) {
        // Try to get the name of entity class (without javassit suffix)
        String baseClass = StringUtils.substringBefore(entityClass.getSimpleName(), "$");// );"_$");
        // try to get pattern by Roo key
        String rooKey = StringUtils.uncapitalize(baseClass).concat("_").concat(lowerCaseFieldName)
                .concat("_date_format");

        pattern = (String) datePatterns.get(rooKey);
    }
    if (!StringUtils.isEmpty(pattern)) {
        result = new SimpleDateFormat(pattern);
    }
    dateFormatters.put(lowerCaseFieldName, result);
    return result;
}

From source file:org.gvnix.web.datatables.util.impl.DatatablesUtilsBeanImpl.java

/**
 * Get Date formatter by field name//from  ww w . j a  v  a2  s . c o m
 * <p/>
 * If no pattern found, try standard Roo key
 * {@code uncapitalize( ENTITY ) + "_" + lower_case( FIELD ) + "_date_format"}
 * 
 * @param datePatterns Contains field name and related data pattern
 * @param entityClass Entity class to which the field belong to
 * @param fieldName Field to search pattern
 * @return
 */
private SimpleDateFormat getDateFormatter(Map<String, Object> datePatterns,
        Map<String, SimpleDateFormat> dateFormatters, Class<?> entityClass, String fieldName) {

    SimpleDateFormat result = null;
    String lowerCaseFieldName = fieldName.toLowerCase();
    result = dateFormatters.get(lowerCaseFieldName);
    if (result != null) {
        return result;
    } else if (dateFormatters.containsKey(lowerCaseFieldName)) {
        return null;
    }

    // Get pattern by field name
    String pattern = (String) datePatterns.get(lowerCaseFieldName);
    if (StringUtils.isEmpty(pattern)) {
        // Try to get the name of entity class (without javassit suffix)
        String baseClass = StringUtils.substringBefore(entityClass.getSimpleName(), "$");// );"_$");
        // try to get pattern by Roo key
        String rooKey = StringUtils.uncapitalize(baseClass).concat("_").concat(lowerCaseFieldName)
                .concat("_date_format");

        pattern = (String) datePatterns.get(rooKey);
    }
    if (!StringUtils.isEmpty(pattern)) {
        result = new SimpleDateFormat(pattern);
    }
    dateFormatters.put(lowerCaseFieldName, result);
    return result;
}

From source file:org.gvnix.web.exception.handler.roo.addon.addon.WebExceptionHandlerOperationsImpl.java

/**
 * Returns the exception view name checking if exists in the file
 * webmvc-config.xml file./*from  w w w .  jav a  2 s  . com*/
 * 
 * @param exceptionName to create the view.
 * @param root {@link Element} with the values off webmvc-config.xml
 * @return
 */
private String getExceptionViewName(String exceptionName) {

    // View name for this Exception.
    int index = exceptionName.lastIndexOf('.');
    String exceptionViewName = exceptionName;

    if (index >= 0) {
        exceptionViewName = exceptionName.substring(index + 1);
    }
    exceptionViewName = StringUtils.uncapitalize(exceptionViewName);

    boolean exceptionNameExists = true;

    int exceptionCounter = 2;

    String tmpExceptionViewName = exceptionViewName;

    while (exceptionNameExists) {

        exceptionNameExists = fileManager
                .exists(pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
                        "WEB-INF/views/" + tmpExceptionViewName + JSPX_EXTENSION));

        if (exceptionNameExists) {
            tmpExceptionViewName = exceptionViewName.concat(Integer.toString(exceptionCounter++));
        }
    }

    return tmpExceptionViewName;
}

From source file:org.gvnix.web.exception.handler.roo.addon.addon.WebExceptionHandlerOperationsImpl.java

/**
 * Creates a view for the new Handled Exception.
 * //from  ww  w  .ja  v  a 2 s. co  m
 * @param exceptionName Name of the Exception to handle.
 * @param exceptionTitle Title of the exception view.
 * @param exceptionDescription Description to show in the view.
 * @param exceptionViewName Name of the .jspx view.
 */
private void createNewExceptionView(String exceptionName, String exceptionTitle, String exceptionDescription,
        String exceptionViewName) {

    String exceptionNameUncapitalize = StringUtils.uncapitalize(exceptionName);

    Map<String, String> params = new HashMap<String, String>(10);
    // Parameters
    params.put("error.uncaughtexception.title", ERROR + exceptionNameUncapitalize + TITLE);
    params.put("error.uncaughtexception.problemdescription",
            ERROR + exceptionNameUncapitalize + PROBLEM_DESCRIPTION);

    String exceptionFilename = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/views/" + exceptionViewName + JSPX_EXTENSION);
    String template;
    try {

        InputStream templateInputStream = FileUtils.getInputStream(getClass(), ITD_TEMPLATE);

        InputStreamReader readerFile = new InputStreamReader(templateInputStream);

        template = IOUtils.toString(readerFile);

    } catch (IOException ioe) {
        throw new IllegalStateException("Unable load ITD jspx template", ioe);
    }

    template = replaceParams(template, params);

    // Output the ITD if there is actual content involved
    // (if there is no content, we continue on to the deletion phase
    // at the bottom of this conditional block)

    Validate.isTrue(template.length() > 0, "The template doesn't exists.");

    MutableFile mutableFile = null;
    if (fileManager.exists(exceptionFilename)) {
        File newFile = new File(exceptionFilename);
        String existing = null;
        try {
            existing = IOUtils.toString(new FileReader(newFile));
        } catch (IOException ignoreAndJustOverwriteIt) {
            LOGGER.finest("Problems writting ".concat(newFile.getAbsolutePath()));
        }

        if (!template.equals(existing)) {
            mutableFile = fileManager.updateFile(exceptionFilename);
        }

    } else {
        mutableFile = fileManager.createFile(exceptionFilename);
        Validate.notNull(mutableFile, "Could not create ITD file '" + exceptionFilename + "'");
    }

    try {
        if (mutableFile != null) {
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = IOUtils.toInputStream(template);
                outputStream = mutableFile.getOutputStream();
                IOUtils.copy(inputStream, outputStream);
            } finally {
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
            }
        }
    } catch (IOException ioe) {
        throw new IllegalStateException("Could not output '" + mutableFile.getCanonicalPath() + "'", ioe);
    }
}