use of org.springframework.roo.classpath.details.annotations.StringAttributeValue in project spring-roo by spring-projects.
the class RepositoryJpaCustomImplMetadataProviderImpl method buildFieldNamesMap.
/**
* Build a Map<String, String> with field names and "path" field names
* and adds it to the typesFieldMaps Map.
*
* @param entity
* @param projection
* @param entityProjectionAnnotation
* @param typesFieldMaps
*/
private void buildFieldNamesMap(JavaType entity, JavaType projection, AnnotationMetadata entityProjectionAnnotation, Map<JavaType, List<Pair<String, String>>> typesFieldMaps) {
List<Pair<String, String>> projectionFieldNames = new ArrayList<Pair<String, String>>();
if (!typesFieldMaps.containsKey(projection)) {
AnnotationAttributeValue<?> projectionFields = entityProjectionAnnotation.getAttribute("fields");
if (projectionFields != null) {
@SuppressWarnings("unchecked") List<StringAttributeValue> values = (List<StringAttributeValue>) projectionFields.getValue();
// Get entity name as a variable name for building constructor expression
String entityVariableName = StringUtils.uncapitalize(entity.getSimpleTypeName());
for (StringAttributeValue field : values) {
String[] splittedByDot = StringUtils.split(field.getValue(), ".");
StringBuffer propertyName = new StringBuffer();
for (int i = 0; i < splittedByDot.length; i++) {
if (i == 0) {
propertyName.append(splittedByDot[i]);
} else {
propertyName.append(StringUtils.capitalize(splittedByDot[i]));
}
}
String pathName = entityVariableName.concat(".").concat(field.getValue());
projectionFieldNames.add(Pair.of(propertyName.toString(), pathName));
typesFieldMaps.put(projection, projectionFieldNames);
}
}
}
}
use of org.springframework.roo.classpath.details.annotations.StringAttributeValue in project spring-roo by spring-projects.
the class DbreMetadata method getManyToManyOwningSideField.
private FieldMetadataBuilder getManyToManyOwningSideField(final JavaSymbolName fieldName, final Table joinTable, final Table inverseSideTable, final CascadeAction onUpdate, final CascadeAction onDelete) {
final JavaType element = DbreTypeUtils.findTypeForTable(managedEntities, inverseSideTable);
Validate.notNull(element, "Attempted to create many-to-many owning-side field '%s' in '%s' %s", fieldName, destination.getFullyQualifiedTypeName(), getErrorMsg(inverseSideTable.getFullyQualifiedTableName()));
final List<JavaType> params = Arrays.asList(element);
final JavaType fieldType = new JavaType(SET.getFullyQualifiedTypeName(), 0, DataType.TYPE, null, params);
// Add annotations to field
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
// Add @ManyToMany annotation
final AnnotationMetadataBuilder manyToManyBuilder = new AnnotationMetadataBuilder(MANY_TO_MANY);
annotations.add(manyToManyBuilder);
// Add @JoinTable annotation
final AnnotationMetadataBuilder joinTableBuilder = new AnnotationMetadataBuilder(JOIN_TABLE);
final List<AnnotationAttributeValue<?>> joinTableAnnotationAttributes = new ArrayList<AnnotationAttributeValue<?>>();
joinTableAnnotationAttributes.add(new StringAttributeValue(new JavaSymbolName(NAME), joinTable.getName()));
final Iterator<ForeignKey> iter = joinTable.getImportedKeys().iterator();
// Add "joinColumns" attribute containing nested @JoinColumn annotations
final List<NestedAnnotationAttributeValue> joinColumnArrayValues = new ArrayList<NestedAnnotationAttributeValue>();
final Set<Reference> firstKeyReferences = iter.next().getReferences();
for (final Reference reference : firstKeyReferences) {
final AnnotationMetadataBuilder joinColumnBuilder = getJoinColumnAnnotation(reference, firstKeyReferences.size() > 1);
joinColumnArrayValues.add(new NestedAnnotationAttributeValue(new JavaSymbolName(VALUE), joinColumnBuilder.build()));
}
joinTableAnnotationAttributes.add(new ArrayAttributeValue<NestedAnnotationAttributeValue>(new JavaSymbolName("joinColumns"), joinColumnArrayValues));
// Add "inverseJoinColumns" attribute containing nested @JoinColumn
// annotations
final List<NestedAnnotationAttributeValue> inverseJoinColumnArrayValues = new ArrayList<NestedAnnotationAttributeValue>();
final Set<Reference> lastKeyReferences = iter.next().getReferences();
for (final Reference reference : lastKeyReferences) {
final AnnotationMetadataBuilder joinColumnBuilder = getJoinColumnAnnotation(reference, lastKeyReferences.size() > 1);
inverseJoinColumnArrayValues.add(new NestedAnnotationAttributeValue(new JavaSymbolName(VALUE), joinColumnBuilder.build()));
}
joinTableAnnotationAttributes.add(new ArrayAttributeValue<NestedAnnotationAttributeValue>(new JavaSymbolName("inverseJoinColumns"), inverseJoinColumnArrayValues));
// Add attributes to a @JoinTable annotation builder
joinTableBuilder.setAttributes(joinTableAnnotationAttributes);
annotations.add(joinTableBuilder);
return new FieldMetadataBuilder(getId(), Modifier.PRIVATE, annotations, fieldName, fieldType);
}
use of org.springframework.roo.classpath.details.annotations.StringAttributeValue in project spring-roo by spring-projects.
the class DtoOperationsImpl method createProjection.
@Override
public void createProjection(JavaType entity, JavaType name, String fields, String suffix, String formatExpression, String formatMessage) {
Validate.notNull(name, "Use --class to select the name of the Projection.");
// TODO: Validate fields for excluding entity collection, transient and
// static fields from operations (already doing when comming from commands).
// Set focus on projection module
projectOperations.setModule(projectOperations.getPomFromModuleName(name.getModule()));
// Add springlets-context dependency
projectOperations.addDependency(name.getModule(), SPRINGLETS_CONTEXT_DEPENDENCY);
projectOperations.addProperty("", SPRINGLETS_VERSION_PROPERTY);
Map<String, FieldMetadata> fieldsToAdd = new LinkedHashMap<String, FieldMetadata>();
boolean onlyMainEntityFields = true;
if (fields != null) {
onlyMainEntityFields = false;
// Check that id field has been included. If not, include it.
fields = checkAndAddIdField(entity, fields);
fieldsToAdd = buildFieldsFromString(fields, entity);
} else {
List<FieldMetadata> allFields = memberDetailsScanner.getMemberDetails(this.getClass().getName(), typeLocationService.getTypeDetails(entity)).getFields();
for (FieldMetadata field : allFields) {
// Add only valid fields
if (isFieldValidForProjection(field)) {
fieldsToAdd.put(field.getFieldName().getSymbolName(), field);
}
}
}
// Create projection
final String declaredByMetadataId = PhysicalTypeIdentifier.createIdentifier(name, LogicalPath.getInstance(Path.SRC_MAIN_JAVA, name.getModule()));
final ClassOrInterfaceTypeDetailsBuilder projectionBuilder = new ClassOrInterfaceTypeDetailsBuilder(declaredByMetadataId, Modifier.PUBLIC, name, PhysicalTypeCategory.CLASS);
// Add fields to projection
addFieldsToProjection(projectionBuilder, fieldsToAdd);
// @RooJavaBean, @RooToString and @RooEquals
AnnotationMetadataBuilder rooJavaBeanAnnotation = new AnnotationMetadataBuilder(RooJavaType.ROO_JAVA_BEAN);
rooJavaBeanAnnotation.addBooleanAttribute("settersByDefault", false);
projectionBuilder.addAnnotation(rooJavaBeanAnnotation);
AnnotationMetadataBuilder rooToStringAnnotation = new AnnotationMetadataBuilder(RooJavaType.ROO_TO_STRING);
AnnotationMetadataBuilder rooEqualsAnnotation = new AnnotationMetadataBuilder(RooJavaType.ROO_EQUALS);
projectionBuilder.addAnnotation(rooToStringAnnotation);
projectionBuilder.addAnnotation(rooEqualsAnnotation);
// Add @RooEntityProjection
AnnotationMetadataBuilder projectionAnnotation = new AnnotationMetadataBuilder(RooJavaType.ROO_ENTITY_PROJECTION);
projectionAnnotation.addClassAttribute("entity", entity);
List<StringAttributeValue> fieldNames = new ArrayList<StringAttributeValue>();
if (onlyMainEntityFields) {
// Should add all entity fields
for (FieldMetadata field : fieldsToAdd.values()) {
fieldNames.add(new StringAttributeValue(new JavaSymbolName("fields"), field.getFieldName().getSymbolName()));
}
} else {
// --fields option has been completed and validated, so build annotation 'fields'
// param from selected fields
String[] fieldsFromCommand = StringUtils.split(fields, ",");
for (int i = 0; i < fieldsFromCommand.length; i++) {
fieldNames.add(new StringAttributeValue(new JavaSymbolName("fields"), fieldsFromCommand[i]));
}
}
projectionAnnotation.addAttribute(new ArrayAttributeValue<StringAttributeValue>(new JavaSymbolName("fields"), fieldNames));
// Check for each attribute individually
if (StringUtils.isNotBlank(formatExpression)) {
projectionAnnotation.addStringAttribute("formatExpression", formatExpression);
}
if (StringUtils.isNotBlank(formatMessage)) {
projectionAnnotation.addStringAttribute("formatMessage", formatMessage);
}
projectionBuilder.addAnnotation(projectionAnnotation);
// Build and save changes to disk
typeManagementService.createOrUpdateTypeOnDisk(projectionBuilder.build());
}
use of org.springframework.roo.classpath.details.annotations.StringAttributeValue in project spring-roo by spring-projects.
the class AutoPopulationUtils method populate.
/**
* Introspects the target {@link Object} for its declared fields, locating
* all {@link AutoPopulate} annotated fields. For each field, an attempt
* will be made to locate the value from the passed
* {@link AnnotationMetadata}. The annotation value will be converted into
* the required field type, or silently skipped if this is not possible (eg
* the user edited source code and made a formatting error). As such it is
* important that the caller.
*
* @param target to put values into (mandatory, cannot be null)
* @param annotation to obtain values from (can be null, for convenience of
* the caller)
*/
public static void populate(final Object target, final AnnotationMetadata annotation) {
Validate.notNull(target, "Target required");
if (annotation == null) {
return;
}
List<Field> fields = cachedIntrospections.get(target.getClass());
if (fields == null) {
// Go and cache them
fields = new ArrayList<Field>();
for (final Field field : target.getClass().getDeclaredFields()) {
// Determine if this field even contains the necessary
// annotation
final AutoPopulate ap = field.getAnnotation(AutoPopulate.class);
if (ap == null) {
continue;
}
// Determine attribute name we should be looking for in the
// annotation
String attribute = ap.value();
if ("".equals(ap.value())) {
attribute = field.getName();
}
// Ensure field is accessible
if (!field.isAccessible()) {
field.setAccessible(true);
}
final JavaSymbolName attributeName = new JavaSymbolName(attribute);
// Store the info
fields.add(field);
attributeNameForEachField.put(field, attributeName);
}
cachedIntrospections.put(target.getClass(), fields);
}
for (final Field field : fields) {
// Lookup whether this attribute name was provided
final JavaSymbolName attributeName = attributeNameForEachField.get(field);
if (attributeName == null) {
throw new IllegalStateException("Expected cached attribute name lookup");
}
if (annotation.getAttributeNames().contains(attributeName)) {
// Get the value
final AnnotationAttributeValue<?> value = annotation.getAttribute(attributeName);
// Assign the value to the target object
try {
final Class<?> fieldType = field.getType();
if (value instanceof BooleanAttributeValue && (fieldType.equals(Boolean.class) || fieldType.equals(Boolean.TYPE))) {
field.set(target, value.getValue());
} else if (value instanceof CharAttributeValue && (fieldType.equals(Character.class) || fieldType.equals(Character.TYPE))) {
field.set(target, value.getValue());
} else if (value instanceof ClassAttributeValue && fieldType.equals(JavaType.class)) {
field.set(target, value.getValue());
} else if (value instanceof DoubleAttributeValue && (fieldType.equals(Double.class) || fieldType.equals(Double.TYPE))) {
field.set(target, value.getValue());
} else if (value instanceof EnumAttributeValue && Enum.class.isAssignableFrom(fieldType)) {
field.set(target, ((EnumAttributeValue) value).getAsEnum(target));
} else if (value instanceof IntegerAttributeValue && (fieldType.equals(Integer.class) || fieldType.equals(Integer.TYPE))) {
field.set(target, value.getValue());
} else if (value instanceof LongAttributeValue && (fieldType.equals(Long.class) || fieldType.equals(Long.TYPE))) {
field.set(target, value.getValue());
} else if (value instanceof StringAttributeValue && fieldType.equals(String.class)) {
field.set(target, value.getValue());
} else if (value instanceof StringAttributeValue && fieldType.getComponentType() != null && fieldType.getComponentType().equals(String.class)) {
// ROO-618
final Object newValue = Array.newInstance(String.class, 1);
Array.set(newValue, 0, value.getValue());
field.set(target, newValue);
} else if (value instanceof ArrayAttributeValue<?> && fieldType.isArray()) {
// The field is a string array, the attribute is an
// array, so let's hope it's a string array
final ArrayAttributeValue<?> castValue = (ArrayAttributeValue<?>) value;
final List<String> result = new ArrayList<String>();
final List<JavaType> result1 = new ArrayList<JavaType>();
for (final AnnotationAttributeValue<?> val : castValue.getValue()) {
// For now we'll only support arrays of strings
if (fieldType.getComponentType().equals(String.class) && val instanceof StringAttributeValue) {
final StringAttributeValue stringValue = (StringAttributeValue) val;
result.add(stringValue.getValue());
} else if (fieldType.getComponentType().equals(JavaType.class) && val instanceof ClassAttributeValue) {
final ClassAttributeValue classValue = (ClassAttributeValue) val;
result1.add(classValue.getValue());
}
}
if (result.size() > 0) {
// We had at least one string array, so we change
// the field
field.set(target, result.toArray(new String[] {}));
}
if (result1.size() > 0) {
// We had at least one string array, so we change
// the field
field.set(target, result1.toArray(new JavaType[] {}));
}
}
// If not in the above list, it's unsupported so we silently
// skip
} catch (final Throwable ignoreFailures) {
}
}
}
}
use of org.springframework.roo.classpath.details.annotations.StringAttributeValue in project spring-roo by spring-projects.
the class FieldDetails method decorateAnnotationsList.
public void decorateAnnotationsList(final List<AnnotationMetadataBuilder> annotations) {
Validate.notNull(annotations);
if (notNull) {
annotations.add(new AnnotationMetadataBuilder(NOT_NULL));
}
if (nullRequired) {
annotations.add(new AnnotationMetadataBuilder(NULL));
}
AnnotationMetadataBuilder columnBuilder = null;
if (column != null) {
final List<AnnotationAttributeValue<?>> attrs = new ArrayList<AnnotationAttributeValue<?>>();
attrs.add(new StringAttributeValue(new JavaSymbolName("name"), column));
columnBuilder = new AnnotationMetadataBuilder(COLUMN, attrs);
}
if (unique) {
if (columnBuilder != null) {
columnBuilder.addBooleanAttribute("unique", true);
} else {
final List<AnnotationAttributeValue<?>> attrs = new ArrayList<AnnotationAttributeValue<?>>();
attrs.add(new BooleanAttributeValue(new JavaSymbolName("unique"), true));
columnBuilder = new AnnotationMetadataBuilder(COLUMN, attrs);
}
}
if (value != null) {
final List<AnnotationAttributeValue<?>> attrs = new ArrayList<AnnotationAttributeValue<?>>();
attrs.add(new StringAttributeValue(new JavaSymbolName("value"), value));
annotations.add(new AnnotationMetadataBuilder(VALUE, attrs));
}
if (fieldName.getSymbolName().equals("created")) {
if (columnBuilder == null) {
columnBuilder = new AnnotationMetadataBuilder(COLUMN);
}
columnBuilder.addBooleanAttribute("updatable", false);
}
if (columnBuilder != null) {
annotations.add(columnBuilder);
}
}
Aggregations