/** * Locates the entity manager field that should be used. * * <p>If a parent is defined, it must provide the field. * * <p>We generally expect the field to be named "entityManager" and be of type * javax.persistence.EntityManager. We also require it to be public or protected, and annotated * with @PersistenceContext. If there is an existing field which doesn't meet these latter * requirements, we add an underscore prefix to the "entityManager" name and try again, until such * time as we come up with a unique name that either meets the requirements or the name is not * used and we will create it. * * @return the entity manager field (never returns null) */ public FieldMetadata getEntityManagerField() { if (parent != null) { // The parent is required to guarantee this is available return parent.getEntityManagerField(); } // Need to locate it ourself int index = -1; while (true) { // Compute the required field name index++; final JavaSymbolName fieldSymbolName = new JavaSymbolName(StringUtils.repeat("_", index) + "entityManager"); final FieldMetadata candidate = governorTypeDetails.getField(fieldSymbolName); if (candidate != null) { // Verify if candidate is suitable if (!Modifier.isPublic(candidate.getModifier()) && !Modifier.isProtected(candidate.getModifier()) && (Modifier.TRANSIENT != candidate.getModifier())) { // Candidate is not public and not protected and not simply a transient field (in which // case subclasses // will see the inherited field), so any subsequent subclasses won't be able to see it. // Give up! continue; } if (!candidate.getFieldType().equals(ENTITY_MANAGER)) { // Candidate isn't an EntityManager, so give up continue; } if (MemberFindingUtils.getAnnotationOfType(candidate.getAnnotations(), PERSISTENCE_CONTEXT) == null) { // Candidate doesn't have a PersistenceContext annotation, so give up continue; } // If we got this far, we found a valid candidate return candidate; } // Candidate not found, so let's create one final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); final AnnotationMetadataBuilder annotationBuilder = new AnnotationMetadataBuilder(PERSISTENCE_CONTEXT); if (StringUtils.hasText(crudAnnotationValues.getPersistenceUnit())) { annotationBuilder.addStringAttribute("unitName", crudAnnotationValues.getPersistenceUnit()); } annotations.add(annotationBuilder); final FieldMetadataBuilder fieldBuilder = new FieldMetadataBuilder( getId(), Modifier.TRANSIENT, annotations, fieldSymbolName, ENTITY_MANAGER); return fieldBuilder.build(); } }
public void configureTemplateMessage(final String from, final String subject) { final String contextPath = getApplicationContextPath(); final Document document = XmlUtils.readXml(fileManager.getInputStream(contextPath)); final Element root = document.getDocumentElement(); final Map<String, String> props = new HashMap<String, String>(); if (StringUtils.hasText(from) || StringUtils.hasText(subject)) { Element smmBean = getSimpleMailMessageBean(root); if (smmBean == null) { smmBean = document.createElement("bean"); smmBean.setAttribute("class", "org.springframework.mail.SimpleMailMessage"); smmBean.setAttribute("id", "templateMessage"); } if (StringUtils.hasText(from)) { Element smmProperty = XmlUtils.findFirstElement("//property[@name='from']", smmBean); if (smmProperty != null) { smmBean.removeChild(smmProperty); } smmProperty = document.createElement("property"); smmProperty.setAttribute("value", "${email.from}"); smmProperty.setAttribute("name", "from"); smmBean.appendChild(smmProperty); props.put("email.from", from); } if (StringUtils.hasText(subject)) { Element smmProperty = XmlUtils.findFirstElement("//property[@name='subject']", smmBean); if (smmProperty != null) { smmBean.removeChild(smmProperty); } smmProperty = document.createElement("property"); smmProperty.setAttribute("value", "${email.subject}"); smmProperty.setAttribute("name", "subject"); smmBean.appendChild(smmProperty); props.put("email.subject", subject); } root.appendChild(smmBean); DomUtils.removeTextNodes(root); fileManager.createOrUpdateTextFileIfRequired( contextPath, XmlUtils.nodeToString(document), false); } if (props.size() > 0) { propFileOperations.addProperties( Path.SPRING_CONFIG_ROOT, "email.properties", props, true, true); } }
/** @return a test for the find (by ID) method, if available and requested (may return null) */ private MethodMetadataBuilder getFindMethodTest( final MemberTypeAdditions findMethod, final MethodMetadata identifierAccessorMethod) { if (!annotationValues.isFind() || findMethod == null || identifierAccessorMethod == null) { // User does not want this method return null; } // Prepare method signature JavaSymbolName methodName = new JavaSymbolName("test" + StringUtils.capitalize(findMethod.getMethodName())); if (governorHasMethod(methodName)) { return null; } builder.getImportRegistrationResolver().addImport(identifierAccessorMethod.getReturnType()); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(TEST)); final String entityName = annotationValues.getEntity().getSimpleTypeName(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine( entityName + " obj = dod." + dataOnDemandMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to initialize correctly\", obj);"); bodyBuilder.appendFormalLine( identifierAccessorMethod.getReturnType().getSimpleTypeName() + " id = obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to provide an identifier\", id);"); bodyBuilder.appendFormalLine("obj = " + findMethod.getMethodCall() + ";"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Find method for '" + entityName + "' illegally returned null for id '\" + id + \"'\", obj);"); bodyBuilder.appendFormalLine( "Assert.assertEquals(\"Find method for '" + entityName + "' returned the incorrect identifier\", id, obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "());"); findMethod.copyAdditionsTo(builder, governorTypeDetails); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder; }
private String getDateTimeFormat() { String format = "DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_SHORT)"; if (annotations == null || annotations.isEmpty()) { return format; } String style = ""; AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(annotations, DATE_TIME_FORMAT); if (annotation != null) { AnnotationAttributeValue<?> attr = annotation.getAttribute(new JavaSymbolName("style")); if (attr != null) { style = (String) attr.getValue(); } } if (StringUtils.hasText(style)) { if (style.equals("S")) { format = "DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_TIME_SHORT)"; } else if (style.equals("M")) { format = "DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_TIME_MEDIUM)"; } else if (style.equals("F")) { format = "DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_TIME_FULL)"; } else if (style.equals("S-")) { format = "DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_SHORT)"; } else if (style.equals("M-")) { format = "DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_MEDIUM)"; } else if (style.equals("F-")) { format = "DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_FULL)"; } } return format; }
public Database getDatabase(final boolean evictCache) { if (!evictCache && cachedIntrospections.contains(lastDatabase)) { for (Database database : cachedIntrospections) { if (database.equals(lastDatabase)) { return lastDatabase; } } } if (evictCache && cachedIntrospections.contains(lastDatabase)) { cachedIntrospections.remove(lastDatabase); } String dbreXmlPath = getDbreXmlPath(); if (!StringUtils.hasText(dbreXmlPath) || !fileManager.exists(dbreXmlPath)) { return null; } Database database = null; InputStream inputStream = null; try { inputStream = fileManager.getInputStream(dbreXmlPath); database = DatabaseXmlUtils.readDatabase(inputStream); cacheDatabase(database); return database; } catch (Exception e) { throw new IllegalStateException(e); } finally { IOUtils.closeQuietly(inputStream); } }
/** * Asserts that the given XML node contains the expected content * * @param expectedLines the expected lines of XML (required); separate each line with "\n" * regardless of the platform * @param actualNode the actual XML node (required) * @throws AssertionError if they are not equal */ protected final void assertXmlEquals(final String expectedXml, final Node actualNode) { // Replace the dummy line terminator with the platform-specific one that // will be applied by XmlUtils.nodeToString. final String normalisedXml = expectedXml.replace("\n", StringUtils.LINE_SEPARATOR); // Trim trailing whitespace as XmlUtils.nodeToString appends an extra newline. final String actualXml = StringUtils.trimTrailingWhitespace(XmlUtils.nodeToString(actualNode)); assertEquals(normalisedXml, actualXml); }
/** @return a test for the find all method, if available and requested (may return null) */ private MethodMetadataBuilder getFindAllMethodTest( final MemberTypeAdditions findAllMethod, final MemberTypeAdditions countMethod) { if (!annotationValues.isFindAll() || findAllMethod == null || countMethod == null) { // User does not want this method, or core dependencies are missing return null; } // Prepare method signature JavaSymbolName methodName = new JavaSymbolName("test" + StringUtils.capitalize(findAllMethod.getMethodName())); if (governorHasMethod(methodName)) { return null; } builder.getImportRegistrationResolver().addImport(LIST); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(TEST)); final String entityName = annotationValues.getEntity().getSimpleTypeName(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to initialize correctly\", dod." + dataOnDemandMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "());"); bodyBuilder.appendFormalLine("long count = " + countMethod.getMethodCall() + ";"); bodyBuilder.appendFormalLine( "Assert.assertTrue(\"Too expensive to perform a find all test for '" + entityName + "', as there are \" + count + \" entries; set the findAllMaximum to exceed this value or set findAll=false on the integration test annotation to disable the test\", count < " + annotationValues.getFindAllMaximum() + ");"); bodyBuilder.appendFormalLine( "List<" + entityName + "> result = " + findAllMethod.getMethodCall() + ";"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Find all method for '" + entityName + "' illegally returned null\", result);"); bodyBuilder.appendFormalLine( "Assert.assertTrue(\"Find all method for '" + entityName + "' failed to return any data\", result.size() > 0);"); findAllMethod.copyAdditionsTo(builder, governorTypeDetails); countMethod.copyAdditionsTo(builder, governorTypeDetails); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder; }
private MethodMetadataBuilder getIdMethod( String declaredById, JavaType targetType, MethodMetadata idAccessor) { InvocableMemberBodyBuilder invocableMemberBodyBuilder = InvocableMemberBodyBuilder.getInstance(); invocableMemberBodyBuilder.append( "return " + StringUtils.uncapitalize(targetType.getSimpleTypeName()) + "." + idAccessor.getMethodName() + "();"); MethodMetadataBuilder getIdMethod = new MethodMetadataBuilder( declaredById, Modifier.PUBLIC, new JavaSymbolName("getId"), GwtUtils.convertPrimitiveType(idAccessor.getReturnType(), true), invocableMemberBodyBuilder); getIdMethod.addParameter(StringUtils.uncapitalize(targetType.getSimpleTypeName()), targetType); return getIdMethod; }
/** * Constructor * * @param metadataId (required) * @param aspectName (required) * @param governorPhysicalTypeMetadata (required) * @param parent can be <code>null</code> * @param projectMetadata (required) * @param crudAnnotationValues the CRUD-related annotation values (required) * @param plural the plural form of the entity (required) * @param identifierField the entity's identifier field (required) * @param entityName the JPA entity name (required) */ public JpaActiveRecordMetadata( final String metadataId, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final JpaActiveRecordMetadata parent, final JpaCrudAnnotationValues crudAnnotationValues, final String plural, final FieldMetadata identifierField, final String entityName, final boolean isGaeEnabled) { super(metadataId, aspectName, governorPhysicalTypeMetadata); Assert.isTrue( isValid(metadataId), "Metadata identification string '" + metadataId + "' does not appear to be a valid"); Assert.notNull(crudAnnotationValues, "CRUD-related annotation values required"); Assert.notNull(identifierField, "Identifier required for '" + metadataId + "'"); Assert.hasText(entityName, "Entity name required for '" + metadataId + "'"); Assert.hasText(plural, "Plural required for '" + metadataId + "'"); if (!isValid()) { return; } this.crudAnnotationValues = crudAnnotationValues; this.entityName = entityName; this.identifierField = identifierField; this.isGaeEnabled = isGaeEnabled; this.parent = parent; this.plural = StringUtils.capitalize(plural); // Determine the entity's "entityManager" field, which is guaranteed to be accessible to the // ITD. builder.addField(getEntityManagerField()); // Add helper methods builder.addMethod(getPersistMethod()); builder.addMethod(getRemoveMethod()); builder.addMethod(getFlushMethod()); builder.addMethod(getClearMethod()); builder.addMethod(getMergeMethod()); // Add static methods builder.addMethod(getEntityManagerMethod()); builder.addMethod(getCountMethod()); builder.addMethod(getFindAllMethod()); builder.addMethod(getFindMethod()); builder.addMethod(getFindEntriesMethod()); builder.putCustomData(CustomDataKeys.DYNAMIC_FINDER_NAMES, getDynamicFinders()); // Create a representation of the desired output ITD itdTypeDetails = builder.build(); }
private MethodMetadataBuilder getVersionMethod( String declaredById, JavaType targetType, MethodMetadata versionAccessor) { InvocableMemberBodyBuilder invocableMemberBodyBuilder = InvocableMemberBodyBuilder.getInstance(); invocableMemberBodyBuilder.append( "return " + StringUtils.uncapitalize(targetType.getSimpleTypeName()) + "." + versionAccessor.getMethodName() + "();"); MethodMetadataBuilder getIdMethodBuilder = new MethodMetadataBuilder( declaredById, Modifier.PUBLIC, new JavaSymbolName("getVersion"), JavaType.OBJECT, invocableMemberBodyBuilder); getIdMethodBuilder.addParameter( StringUtils.uncapitalize(targetType.getSimpleTypeName()), targetType); return getIdMethodBuilder; }
/** @return a test for the find entries method, if available and requested (may return null) */ private MethodMetadataBuilder getFindEntriesMethodTest( final MemberTypeAdditions countMethod, final MemberTypeAdditions findEntriesMethod) { if (!annotationValues.isFindEntries() || countMethod == null || findEntriesMethod == null) { // User does not want this method, or core dependencies are missing return null; } // Prepare method signature JavaSymbolName methodName = new JavaSymbolName("test" + StringUtils.capitalize(findEntriesMethod.getMethodName())); if (governorHasMethod(methodName)) { return null; } builder.getImportRegistrationResolver().addImport(LIST); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(TEST)); final String entityName = annotationValues.getEntity().getSimpleTypeName(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to initialize correctly\", dod." + dataOnDemandMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "());"); bodyBuilder.appendFormalLine("long count = " + countMethod.getMethodCall() + ";"); bodyBuilder.appendFormalLine("if (count > 20) count = 20;"); bodyBuilder.appendFormalLine("int firstResult = 0;"); bodyBuilder.appendFormalLine("int maxResults = (int) count;"); bodyBuilder.appendFormalLine( "List<" + entityName + "> result = " + findEntriesMethod.getMethodCall() + ";"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Find entries method for '" + entityName + "' illegally returned null\", result);"); bodyBuilder.appendFormalLine( "Assert.assertEquals(\"Find entries method for '" + entityName + "' returned an incorrect number of entries\", count, result.size());"); findEntriesMethod.copyAdditionsTo(builder, governorTypeDetails); countMethod.copyAdditionsTo(builder, governorTypeDetails); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder; }
public boolean supportsSchema(final boolean displayAddOns) throws RuntimeException { Connection connection = null; try { connection = getConnection(displayAddOns); DatabaseMetaData databaseMetaData = connection.getMetaData(); String schemaTerm = databaseMetaData.getSchemaTerm(); return StringUtils.hasText(schemaTerm) && schemaTerm.equalsIgnoreCase("schema"); } catch (Exception e) { throw new IllegalStateException(e); } finally { connectionProvider.closeConnection(connection); } }
private void addTransactionalAnnotation( final List<AnnotationMetadataBuilder> annotations, final boolean isPersistMethod) { final AnnotationMetadataBuilder transactionalBuilder = new AnnotationMetadataBuilder(TRANSACTIONAL); if (StringUtils.hasText(crudAnnotationValues.getTransactionManager())) { transactionalBuilder.addStringAttribute( "value", crudAnnotationValues.getTransactionManager()); } if (isGaeEnabled && isPersistMethod) { transactionalBuilder.addEnumAttribute( "propagation", new EnumDetails(PROPAGATION, new JavaSymbolName("REQUIRES_NEW"))); } annotations.add(transactionalBuilder); }
@Test public void testGetInstance() { // Set up final String coordinates = StringUtils.arrayToDelimitedString( new String[] {GROUP_ID, ARTIFACT_ID, VERSION}, MavenUtils.COORDINATE_SEPARATOR); // Invoke final GAV gav = GAV.getInstance(coordinates); // Check assertEquals(GROUP_ID, gav.getGroupId()); assertEquals(ARTIFACT_ID, gav.getArtifactId()); assertEquals(VERSION, gav.getVersion()); }
public void createModule( final JavaPackage topLevelPackage, final String name, final GAV parent, final PackagingType packagingType) { Assert.isTrue(isCreateModuleAvailable(), "Cannot create modules at this time"); final String moduleName = StringUtils.defaultIfEmpty(name, topLevelPackage.getLastElement()); final GAV module = new GAV(topLevelPackage.getFullyQualifiedPackageName(), moduleName, parent.getVersion()); final ProjectMetadata project = getProjectMetadata(); // TODO create or update "modules" element of parent module's POM // Create the new module's directory, named by its artifactId (Maven standard practice) fileManager.createDirectory(moduleName); // Focus the new module so that artifacts created below go to the correct path(s) focus(module); packagingType.createArtifacts(topLevelPackage, name, "${java.version}", parent); }
/** @return a test for the count method, if available and requested (may return null) */ private MethodMetadataBuilder getCountMethodTest(final MemberTypeAdditions countMethod) { if (!annotationValues.isCount() || countMethod == null) { // User does not want this method return null; } // Prepare method signature JavaSymbolName methodName = new JavaSymbolName("test" + StringUtils.capitalize(countMethod.getMethodName())); if (governorHasMethod(methodName)) { return null; } List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(TEST)); final String entityName = annotationValues.getEntity().getSimpleTypeName(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to initialize correctly\", dod." + dataOnDemandMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "());"); bodyBuilder.appendFormalLine("long count = " + countMethod.getMethodCall() + ";"); bodyBuilder.appendFormalLine( "Assert.assertTrue(\"Counter for '" + entityName + "' incorrectly reported there were no entries\", count > 0);"); countMethod.copyAdditionsTo(builder, governorTypeDetails); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder; }
private Connection getConnection(final boolean displayAddOns) { final String dbProps = "database.properties"; final String jndiDataSource = getJndiDataSourceName(); if (StringUtils.hasText(jndiDataSource)) { Map<String, String> props = propFileOperations.getProperties( Path.SPRING_CONFIG_ROOT.getModulePathId(projectOperations.getFocusedModuleName()), "jndi.properties"); return connectionProvider.getConnectionViaJndiDataSource( jndiDataSource, props, displayAddOns); } else if (fileManager.exists( projectOperations .getPathResolver() .getFocusedIdentifier(Path.SPRING_CONFIG_ROOT, dbProps))) { Map<String, String> props = propFileOperations.getProperties( Path.SPRING_CONFIG_ROOT.getModulePathId(projectOperations.getFocusedModuleName()), dbProps); return connectionProvider.getConnection(props, displayAddOns); } Properties connectionProperties = getConnectionPropertiesFromDataNucleusConfiguration(); return connectionProvider.getConnection(connectionProperties, displayAddOns); }
/** @return a test for the persist method, if available and requested (may return null) */ private MethodMetadataBuilder getRemoveMethodTest( final MemberTypeAdditions removeMethod, final MemberTypeAdditions findMethod, final MemberTypeAdditions flushMethod, final MethodMetadata identifierAccessorMethod) { if (!annotationValues.isRemove() || removeMethod == null || findMethod == null || identifierAccessorMethod == null) { // User does not want this method or one of its core dependencies return null; } // Prepare method signature JavaSymbolName methodName = new JavaSymbolName("test" + StringUtils.capitalize(removeMethod.getMethodName())); if (governorHasMethod(methodName)) { return null; } builder.getImportRegistrationResolver().addImport(identifierAccessorMethod.getReturnType()); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(TEST)); if (isGaeSupported) { AnnotationMetadataBuilder transactionalBuilder = new AnnotationMetadataBuilder(TRANSACTIONAL); if (StringUtils.hasText(transactionManager) && !"transactionManager".equals(transactionManager)) { transactionalBuilder.addStringAttribute("value", transactionManager); } transactionalBuilder.addEnumAttribute( "propagation", new EnumDetails(PROPAGATION, new JavaSymbolName("SUPPORTS"))); annotations.add(transactionalBuilder); } final String entityName = annotationValues.getEntity().getSimpleTypeName(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine( entityName + " obj = dod." + dataOnDemandMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to initialize correctly\", obj);"); bodyBuilder.appendFormalLine( identifierAccessorMethod.getReturnType().getSimpleTypeName() + " id = obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to provide an identifier\", id);"); bodyBuilder.appendFormalLine("obj = " + findMethod.getMethodCall() + ";"); bodyBuilder.appendFormalLine(removeMethod.getMethodCall() + ";"); if (flushMethod != null) { bodyBuilder.appendFormalLine(flushMethod.getMethodCall() + ";"); flushMethod.copyAdditionsTo(builder, governorTypeDetails); } bodyBuilder.appendFormalLine( "Assert.assertNull(\"Failed to remove '" + entityName + "' with identifier '\" + id + \"'\", " + findMethod.getMethodCall() + ");"); removeMethod.copyAdditionsTo(builder, governorTypeDetails); findMethod.copyAdditionsTo(builder, governorTypeDetails); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder; }
/** * Obtains the "toString" method for this type, if available. * * <p>If the user provided a non-default name for "toString", that method will be returned. * * @return the "toString" method declared on this type or that will be introduced (or null if * undeclared and not introduced) */ public MethodMetadata getToStringMethod() { // Compute the relevant toString method name JavaSymbolName methodName = new JavaSymbolName("toString"); if (!this.toStringMethod.equals("")) { methodName = new JavaSymbolName(this.toStringMethod); } // See if the type itself declared the method MethodMetadata result = MemberFindingUtils.getDeclaredMethod(governorTypeDetails, methodName, null); if (result != null) { return result; } // Decide whether we need to produce the toString method if (this.toStringMethod.equals("")) { return null; } InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine("StringBuilder sb = new StringBuilder();"); /** Key: field name, Value: accessor name */ Map<String, String> map = new LinkedHashMap<String, String>(); /** Field names */ List<String> order = new ArrayList<String>(); Set<String> excludeFieldsSet = new LinkedHashSet<String>(); if (excludeFields != null && excludeFields.length > 0) { Collections.addAll(excludeFieldsSet, excludeFields); } for (MethodMetadata accessor : locatedAccessors) { String accessorName = accessor.getMethodName().getSymbolName(); String fieldName = BeanInfoUtils.getPropertyNameForJavaBeanMethod(accessor).getSymbolName(); if (!excludeFieldsSet.contains(StringUtils.uncapitalize(fieldName)) && !map.containsKey(fieldName)) { String accessorText = accessorName + "()"; if (accessor.getReturnType().isCommonCollectionType()) { accessorText = accessorName + "() == null ? \"null\" : " + accessorName + "().size()"; } else if (accessor.getReturnType().isArray()) { accessorText = "java.util.Arrays.toString(" + accessorName + "())"; } else if (Calendar.class .getName() .equals(accessor.getReturnType().getFullyQualifiedTypeName())) { accessorText = accessorName + "() == null ? \"null\" : " + accessorName + "().getTime()"; } map.put(fieldName, accessorText); order.add(fieldName); } } if (!order.isEmpty()) { int index = 0; int size = map.keySet().size(); for (String fieldName : order) { index++; String accessorText = map.get(fieldName); StringBuilder string = new StringBuilder(); string .append("sb.append(\"") .append(fieldName) .append(": \").append(") .append(accessorText) .append(")"); if (index < size) { string.append(".append(\", \")"); } string.append(";"); bodyBuilder.appendFormalLine(string.toString()); } bodyBuilder.appendFormalLine("return sb.toString();"); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, STRING, bodyBuilder); result = methodBuilder.build(); } return result; }
/** @return a test for the merge method, if available and requested (may return null) */ private MethodMetadataBuilder getMergeMethodTest( final MemberTypeAdditions mergeMethod, final MemberTypeAdditions findMethod, final MemberTypeAdditions flushMethod, final MethodMetadata versionAccessorMethod, final MethodMetadata identifierAccessorMethod) { if (!annotationValues.isMerge() || mergeMethod == null || versionAccessorMethod == null || findMethod == null || identifierAccessorMethod == null) { // User does not want this method, or core dependencies are missing return null; } // Prepare method signature JavaSymbolName methodName = new JavaSymbolName("test" + StringUtils.capitalize(mergeMethod.getMethodName()) + "Update"); if (governorHasMethod(methodName)) { return null; } JavaType versionType = versionAccessorMethod.getReturnType(); builder .getImportRegistrationResolver() .addImports(identifierAccessorMethod.getReturnType(), versionType); List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(TEST)); String entityName = annotationValues.getEntity().getSimpleTypeName(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine( entityName + " obj = dod." + dataOnDemandMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to initialize correctly\", obj);"); bodyBuilder.appendFormalLine( identifierAccessorMethod.getReturnType().getSimpleTypeName() + " id = obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "();"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to provide an identifier\", id);"); bodyBuilder.appendFormalLine("obj = " + findMethod.getMethodCall() + ";"); bodyBuilder.appendFormalLine( "boolean modified = dod." + dataOnDemandMetadata.getModifyMethod().getMethodName().getSymbolName() + "(obj);"); bodyBuilder.appendFormalLine( versionAccessorMethod.getReturnType().getSimpleTypeName() + " currentVersion = obj." + versionAccessorMethod.getMethodName().getSymbolName() + "();"); String castStr = entityHasSuperclass ? "(" + entityName + ")" : ""; bodyBuilder.appendFormalLine( entityName + " merged = " + castStr + mergeMethod.getMethodCall() + ";"); if (flushMethod != null) { bodyBuilder.appendFormalLine(flushMethod.getMethodCall() + ";"); flushMethod.copyAdditionsTo(builder, governorTypeDetails); } bodyBuilder.appendFormalLine( "Assert.assertEquals(\"Identifier of merged object not the same as identifier of original object\", merged." + identifierAccessorMethod.getMethodName().getSymbolName() + "(), id);"); if (JdkJavaType.isDateField(versionType)) { bodyBuilder.appendFormalLine( "Assert.assertTrue(\"Version for '" + entityName + "' failed to increment on merge and flush directive\", (currentVersion != null && obj." + versionAccessorMethod.getMethodName().getSymbolName() + "().after(currentVersion)) || !modified);"); } else { bodyBuilder.appendFormalLine( "Assert.assertTrue(\"Version for '" + entityName + "' failed to increment on merge and flush directive\", (currentVersion != null && obj." + versionAccessorMethod.getMethodName().getSymbolName() + "() > currentVersion) || !modified);"); } mergeMethod.copyAdditionsTo(builder, governorTypeDetails); findMethod.copyAdditionsTo(builder, governorTypeDetails); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder; }
/** @return a test for the persist method, if available and requested (may return null) */ private MethodMetadataBuilder getPersistMethodTest( final MemberTypeAdditions persistMethod, final MemberTypeAdditions flushMethod, final MethodMetadata identifierAccessorMethod) { if (!annotationValues.isPersist() || persistMethod == null || identifierAccessorMethod == null) { // User does not want this method return null; } // Prepare method signature JavaSymbolName methodName = new JavaSymbolName("test" + StringUtils.capitalize(persistMethod.getMethodName())); if (governorHasMethod(methodName)) { return null; } List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(TEST)); final String entityName = annotationValues.getEntity().getSimpleTypeName(); InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to initialize correctly\", dod." + dataOnDemandMetadata.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "());"); bodyBuilder.appendFormalLine( entityName + " obj = dod." + dataOnDemandMetadata.getNewTransientEntityMethod().getMethodName().getSymbolName() + "(Integer.MAX_VALUE);"); bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Data on demand for '" + entityName + "' failed to provide a new transient entity\", obj);"); if (!hasEmbeddedIdentifier) { bodyBuilder.appendFormalLine( "Assert.assertNull(\"Expected '" + entityName + "' identifier to be null\", obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "());"); } bodyBuilder.appendFormalLine(persistMethod.getMethodCall() + ";"); if (flushMethod != null) { bodyBuilder.appendFormalLine(flushMethod.getMethodCall() + ";"); flushMethod.copyAdditionsTo(builder, governorTypeDetails); } bodyBuilder.appendFormalLine( "Assert.assertNotNull(\"Expected '" + entityName + "' identifier to no longer be null\", obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "());"); persistMethod.copyAdditionsTo(builder, governorTypeDetails); MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, bodyBuilder); methodBuilder.setAnnotations(annotations); return methodBuilder; }
String getSetValuePickerMethodName() { return "set" + StringUtils.capitalize(getName()) + "PickerValues"; }
public MetadataItem get(String metadataIdentificationString) { ProjectMetadata projectMetadata = projectOperations.getProjectMetadata(); if (projectMetadata == null) { return null; } ClassOrInterfaceTypeDetails proxy = getGovernor(metadataIdentificationString); if (proxy == null) { return null; } AnnotationMetadata proxyAnnotation = GwtUtils.getFirstAnnotation(proxy, GwtUtils.PROXY_ANNOTATIONS); if (proxyAnnotation == null) { return null; } String locatorType = GwtUtils.getStringValue(proxyAnnotation.getAttribute("locator")); if (!StringUtils.hasText(locatorType)) { return null; } ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy); if (entity == null) { return null; } MethodMetadata idAccessor = persistenceMemberLocator.getIdentifierAccessor(entity.getName()); MethodMetadata versionAccessor = persistenceMemberLocator.getVersionAccessor(entity.getName()); if (idAccessor == null || versionAccessor == null) { return null; } final JavaType idType = GwtUtils.convertPrimitiveType(idAccessor.getReturnType(), true); String locatorIdentifier = PhysicalTypeIdentifier.createIdentifier(new JavaType(locatorType)); ClassOrInterfaceTypeDetailsBuilder locatorBuilder = new ClassOrInterfaceTypeDetailsBuilder(locatorIdentifier); AnnotationMetadataBuilder annotationMetadataBuilder = new AnnotationMetadataBuilder(RooJavaType.ROO_GWT_LOCATOR); annotationMetadataBuilder.addStringAttribute( "value", entity.getName().getFullyQualifiedTypeName()); locatorBuilder.addAnnotation(annotationMetadataBuilder); annotationMetadataBuilder = new AnnotationMetadataBuilder(SpringJavaType.COMPONENT); locatorBuilder.addAnnotation(annotationMetadataBuilder); locatorBuilder.setName(new JavaType(locatorType)); locatorBuilder.setModifier(Modifier.PUBLIC); locatorBuilder.setPhysicalTypeCategory(PhysicalTypeCategory.CLASS); locatorBuilder.addExtendsTypes( new JavaType( GwtUtils.LOCATOR.getFullyQualifiedTypeName(), 0, DataType.TYPE, null, Arrays.asList(entity.getName(), idType))); locatorBuilder.addMethod(getCreateMethod(locatorIdentifier, entity.getName())); locatorBuilder.addMethod( getFindMethod(locatorBuilder, locatorIdentifier, entity.getName(), idType)); locatorBuilder.addMethod(getDomainTypeMethod(locatorIdentifier, entity.getName())); locatorBuilder.addMethod(getIdMethod(locatorIdentifier, entity.getName(), idAccessor)); locatorBuilder.addMethod(getIdTypeMethod(locatorIdentifier, entity.getName(), idType)); locatorBuilder.addMethod( getVersionMethod(locatorIdentifier, entity.getName(), versionAccessor)); typeManagementService.createOrUpdateTypeOnDisk(locatorBuilder.build()); return null; }
private String getJpaQuery( List<Token> tokens, String simpleTypeName, JavaSymbolName finderName, String plural, String entityName) { String typeName = StringUtils.hasText(entityName) ? entityName : simpleTypeName; StringBuilder builder = new StringBuilder(); builder.append("SELECT o FROM ").append(typeName); builder.append(" AS o WHERE "); FieldToken lastFieldToken = null; boolean isNewField = true; boolean isFieldApplied = false; for (Token token : tokens) { if (token instanceof ReservedToken) { String reservedToken = token.getValue(); if (lastFieldToken == null) continue; String fieldName = lastFieldToken.getField().getFieldName().getSymbolName(); boolean setField = true; if (!lastFieldToken.getField().getFieldType().isCommonCollectionType()) { if (isNewField) { if (reservedToken.equalsIgnoreCase("Like")) { builder.append("LOWER(").append("o.").append(fieldName).append(')'); } else { builder.append("o.").append(fieldName); } isNewField = false; isFieldApplied = false; } if (reservedToken.equalsIgnoreCase("And")) { if (!isFieldApplied) { builder.append(" = :").append(fieldName); isFieldApplied = true; } builder.append(" AND "); setField = false; } else if (reservedToken.equalsIgnoreCase("Or")) { if (!isFieldApplied) { builder.append(" = :").append(fieldName); isFieldApplied = true; } builder.append(" OR "); setField = false; } else if (reservedToken.equalsIgnoreCase("Between")) { builder .append(" BETWEEN ") .append(":min") .append( lastFieldToken.getField().getFieldName().getSymbolNameCapitalisedFirstLetter()) .append(" AND ") .append(":max") .append( lastFieldToken.getField().getFieldName().getSymbolNameCapitalisedFirstLetter()) .append(" "); setField = false; isFieldApplied = true; } else if (reservedToken.equalsIgnoreCase("Like")) { builder.append(" LIKE "); setField = true; } else if (reservedToken.equalsIgnoreCase("IsNotNull")) { builder.append(" IS NOT NULL "); setField = false; isFieldApplied = true; } else if (reservedToken.equalsIgnoreCase("IsNull")) { builder.append(" IS NULL "); setField = false; isFieldApplied = true; } else if (reservedToken.equalsIgnoreCase("Not")) { builder.append(" IS NOT "); } else if (reservedToken.equalsIgnoreCase("NotEquals")) { builder.append(" != "); } else if (reservedToken.equalsIgnoreCase("LessThan")) { builder.append(" < "); } else if (reservedToken.equalsIgnoreCase("LessThanEquals")) { builder.append(" <= "); } else if (reservedToken.equalsIgnoreCase("GreaterThan")) { builder.append(" > "); } else if (reservedToken.equalsIgnoreCase("GreaterThanEquals")) { builder.append(" >= "); } else if (reservedToken.equalsIgnoreCase("Equals")) { builder.append(" = "); } if (setField) { if (builder.toString().endsWith("LIKE ")) { builder.append("LOWER(:").append(fieldName).append(") "); } else { builder.append(':').append(fieldName).append(' '); } isFieldApplied = true; } } } else { lastFieldToken = (FieldToken) token; isNewField = true; } } if (isNewField) { if (lastFieldToken != null && !lastFieldToken.getField().getFieldType().isCommonCollectionType()) { builder.append("o.").append(lastFieldToken.getField().getFieldName().getSymbolName()); } isFieldApplied = false; } if (!isFieldApplied) { if (lastFieldToken != null && !lastFieldToken.getField().getFieldType().isCommonCollectionType()) { builder.append(" = :").append(lastFieldToken.getField().getFieldName().getSymbolName()); } } return builder.toString().trim(); }
public String buildUiXml( final String templateContents, final String destFile, final List<MethodMetadata> proxyMethods) { FileReader fileReader = null; try { DocumentBuilder builder = XmlUtils.getDocumentBuilder(); builder.setEntityResolver( new EntityResolver() { public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException, IOException { if (systemId.equals("http://dl.google.com/gwt/DTD/xhtml.ent")) { return new InputSource( FileUtils.getInputStream(GwtScaffoldMetadata.class, "templates/xhtml.ent")); } // Use the default behaviour return null; } }); InputSource source = new InputSource(); source.setCharacterStream(new StringReader(templateContents)); Document templateDocument = builder.parse(source); if (!new File(destFile).exists()) { return transformXml(templateDocument); } source = new InputSource(); fileReader = new FileReader(destFile); source.setCharacterStream(fileReader); Document existingDocument = builder.parse(source); // Look for the element holder denoted by the 'debugId' attribute first Element existingHoldingElement = XmlUtils.findFirstElement( "//*[@debugId='" + "boundElementHolder" + "']", existingDocument.getDocumentElement()); Element templateHoldingElement = XmlUtils.findFirstElement( "//*[@debugId='" + "boundElementHolder" + "']", templateDocument.getDocumentElement()); // If holding element isn't found then the holding element is either not widget based or using // the old convention of 'id' so look for the element holder with an 'id' attribute if (existingHoldingElement == null) { existingHoldingElement = XmlUtils.findFirstElement( "//*[@id='" + "boundElementHolder" + "']", existingDocument.getDocumentElement()); } if (templateHoldingElement == null) { templateHoldingElement = XmlUtils.findFirstElement( "//*[@id='" + "boundElementHolder" + "']", templateDocument.getDocumentElement()); } if (existingHoldingElement != null) { Map<String, Element> templateElementMap = new LinkedHashMap<String, Element>(); for (Element element : XmlUtils.findElements("//*[@id]", templateHoldingElement)) { templateElementMap.put(element.getAttribute("id"), element); } Map<String, Element> existingElementMap = new LinkedHashMap<String, Element>(); for (Element element : XmlUtils.findElements("//*[@id]", existingHoldingElement)) { existingElementMap.put(element.getAttribute("id"), element); } if (existingElementMap.keySet().containsAll(templateElementMap.values())) { return transformXml(existingDocument); } List<Element> elementsToAdd = new ArrayList<Element>(); for (Map.Entry<String, Element> entry : templateElementMap.entrySet()) { if (!existingElementMap.keySet().contains(entry.getKey())) { elementsToAdd.add(entry.getValue()); } } List<Element> elementsToRemove = new ArrayList<Element>(); for (Map.Entry<String, Element> entry : existingElementMap.entrySet()) { if (!templateElementMap.keySet().contains(entry.getKey())) { elementsToRemove.add(entry.getValue()); } } for (Element element : elementsToAdd) { Node importedNode = existingDocument.importNode(element, true); existingHoldingElement.appendChild(importedNode); } for (Element element : elementsToRemove) { existingHoldingElement.removeChild(element); } if (elementsToAdd.size() > 0) { List<Element> sortedElements = new ArrayList<Element>(); for (MethodMetadata method : proxyMethods) { String propertyName = StringUtils.uncapitalize( BeanInfoUtils.getPropertyNameForJavaBeanMethod(method).getSymbolName()); Element element = XmlUtils.findFirstElement( "//*[@id='" + propertyName + "']", existingHoldingElement); if (element != null) { sortedElements.add(element); } } for (Element el : sortedElements) { if (el.getParentNode() != null && el.getParentNode().equals(existingHoldingElement)) { existingHoldingElement.removeChild(el); } } for (Element el : sortedElements) { existingHoldingElement.appendChild(el); } } return transformXml(existingDocument); } return transformXml(templateDocument); } catch (Exception e) { throw new IllegalStateException(e); } finally { IOUtils.closeQuietly(fileReader); } }
/** Adds the JUnit and Spring type level annotations if needed */ private void addRequiredIntegrationTestClassIntroductions(final JavaType dodGovernor) { // Add an @RunWith(SpringJunit4ClassRunner) annotation to the type, if // the user did not define it on the governor directly if (MemberFindingUtils.getAnnotationOfType(governorTypeDetails.getAnnotations(), RUN_WITH) == null) { AnnotationMetadataBuilder runWithBuilder = new AnnotationMetadataBuilder(RUN_WITH); runWithBuilder.addClassAttribute( "value", "org.springframework.test.context.junit4.SpringJUnit4ClassRunner"); builder.addAnnotation(runWithBuilder); } // Add an @ContextConfiguration("classpath:/applicationContext.xml") // annotation to the type, if the user did not define it on the governor // directly if (MemberFindingUtils.getAnnotationOfType( governorTypeDetails.getAnnotations(), CONTEXT_CONFIGURATION) == null) { AnnotationMetadataBuilder contextConfigurationBuilder = new AnnotationMetadataBuilder(CONTEXT_CONFIGURATION); contextConfigurationBuilder.addStringAttribute( "locations", "classpath:/META-INF/spring/applicationContext*.xml"); builder.addAnnotation(contextConfigurationBuilder); } // Add an @Transactional, if the user did not define it on the governor // directly if (annotationValues.isTransactional() && MemberFindingUtils.getAnnotationOfType( governorTypeDetails.getAnnotations(), TRANSACTIONAL) == null) { AnnotationMetadataBuilder transactionalBuilder = new AnnotationMetadataBuilder(TRANSACTIONAL); if (StringUtils.hasText(transactionManager) && !"transactionManager".equals(transactionManager)) { transactionalBuilder.addStringAttribute("value", transactionManager); } builder.addAnnotation(transactionalBuilder); } // Add the data on demand field if the user did not define it on the // governor directly FieldMetadata field = governorTypeDetails.getField(new JavaSymbolName("dod")); if (field != null) { Assert.isTrue( field.getFieldType().equals(dodGovernor), "Field 'dod' on '" + destination.getFullyQualifiedTypeName() + "' must be of type '" + dodGovernor.getFullyQualifiedTypeName() + "'"); Assert.notNull( MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), AUTOWIRED), "Field 'dod' on '" + destination.getFullyQualifiedTypeName() + "' must be annotated with @Autowired"); } else { // Add the field via the ITD List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); annotations.add(new AnnotationMetadataBuilder(AUTOWIRED)); FieldMetadataBuilder fieldBuilder = new FieldMetadataBuilder( getId(), Modifier.PRIVATE, annotations, new JavaSymbolName("dod"), dodGovernor); builder.addField(fieldBuilder); } builder.getImportRegistrationResolver().addImport(ASSERT); }
public void installEmail( final String hostServer, final MailProtocol protocol, final String port, final String encoding, final String username, final String password) { Assert.hasText(hostServer, "Host server name required"); final String contextPath = getApplicationContextPath(); final Document document = XmlUtils.readXml(fileManager.getInputStream(contextPath)); final Element root = document.getDocumentElement(); boolean installDependencies = true; final Map<String, String> props = new HashMap<String, String>(); Element mailBean = XmlUtils.findFirstElement( "/beans/bean[@class = 'org.springframework.mail.javamail.JavaMailSenderImpl']", root); if (mailBean != null) { root.removeChild(mailBean); installDependencies = false; } mailBean = document.createElement("bean"); mailBean.setAttribute("class", "org.springframework.mail.javamail.JavaMailSenderImpl"); mailBean.setAttribute("id", "mailSender"); final Element property = document.createElement("property"); property.setAttribute("name", "host"); property.setAttribute("value", "${email.host}"); mailBean.appendChild(property); root.appendChild(mailBean); props.put("email.host", hostServer); if (protocol != null) { final Element pElement = document.createElement("property"); pElement.setAttribute("value", "${email.protocol}"); pElement.setAttribute("name", "protocol"); mailBean.appendChild(pElement); props.put("email.protocol", protocol.getProtocol()); } if (StringUtils.hasText(port)) { final Element pElement = document.createElement("property"); pElement.setAttribute("name", "port"); pElement.setAttribute("value", "${email.port}"); mailBean.appendChild(pElement); props.put("email.port", port); } if (StringUtils.hasText(encoding)) { final Element pElement = document.createElement("property"); pElement.setAttribute("name", "defaultEncoding"); pElement.setAttribute("value", "${email.encoding}"); mailBean.appendChild(pElement); props.put("email.encoding", encoding); } if (StringUtils.hasText(username)) { final Element pElement = document.createElement("property"); pElement.setAttribute("name", "username"); pElement.setAttribute("value", "${email.username}"); mailBean.appendChild(pElement); props.put("email.username", username); } if (StringUtils.hasText(password)) { final Element pElement = document.createElement("property"); pElement.setAttribute("name", "password"); pElement.setAttribute("value", "${email.password}"); mailBean.appendChild(pElement); props.put("email.password", password); if (SMTP.equals(protocol)) { final Element javaMailProperties = document.createElement("property"); javaMailProperties.setAttribute("name", "javaMailProperties"); final Element securityProps = document.createElement("props"); javaMailProperties.appendChild(securityProps); final Element prop = document.createElement("prop"); prop.setAttribute("key", "mail.smtp.auth"); prop.setTextContent("true"); securityProps.appendChild(prop); final Element prop2 = document.createElement("prop"); prop2.setAttribute("key", "mail.smtp.starttls.enable"); prop2.setTextContent("true"); securityProps.appendChild(prop2); mailBean.appendChild(javaMailProperties); } } DomUtils.removeTextNodes(root); fileManager.createOrUpdateTextFileIfRequired( contextPath, XmlUtils.nodeToString(document), false); if (installDependencies) { updateConfiguration(); } propFileOperations.addProperties( Path.SPRING_CONFIG_ROOT, "email.properties", props, true, true); }
/** * Generates the "send email" method to be added to the domain type * * @param mailSenderName the name of the MailSender field (required) * @param async whether to send the email asynchronously * @param targetClassMID the MID of the class to receive the method * @param mutableTypeDetails the type to which the method is being added (required) * @return a non-<code>null</code> method */ private MethodMetadata getSendMethod( final JavaSymbolName mailSenderName, final boolean async, final String targetClassMID, final ClassOrInterfaceTypeDetailsBuilder classOrInterfaceTypeDetailsBuilder) { final String contextPath = getApplicationContextPath(); final Document document = XmlUtils.readXml(fileManager.getInputStream(contextPath)); final Element root = document.getDocumentElement(); // Make a builder for the created method's body final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // Collect the types and names of the created method's parameters final PairList<AnnotatedJavaType, JavaSymbolName> parameters = new PairList<AnnotatedJavaType, JavaSymbolName>(); if (getSimpleMailMessageBean(root) == null) { // There's no SimpleMailMessage bean; use a local variable bodyBuilder.appendFormalLine( "org.springframework.mail.SimpleMailMessage " + LOCAL_MESSAGE_VARIABLE + " = new org.springframework.mail.SimpleMailMessage();"); // Set the from address parameters.add(STRING, new JavaSymbolName("mailFrom")); bodyBuilder.appendFormalLine(LOCAL_MESSAGE_VARIABLE + ".setFrom(mailFrom);"); // Set the subject parameters.add(STRING, new JavaSymbolName("subject")); bodyBuilder.appendFormalLine(LOCAL_MESSAGE_VARIABLE + ".setSubject(subject);"); } else { // A SimpleMailMessage bean exists; auto-wire it into the entity and use it as a template final List<AnnotationMetadataBuilder> smmAnnotations = Arrays.asList(new AnnotationMetadataBuilder(AUTOWIRED)); final FieldMetadataBuilder smmFieldBuilder = new FieldMetadataBuilder( targetClassMID, PRIVATE_TRANSIENT, smmAnnotations, new JavaSymbolName(TEMPLATE_MESSAGE_FIELD), SIMPLE_MAIL_MESSAGE); classOrInterfaceTypeDetailsBuilder.addField(smmFieldBuilder.build()); // Use the injected bean as a template (for thread safety) bodyBuilder.appendFormalLine( "org.springframework.mail.SimpleMailMessage " + LOCAL_MESSAGE_VARIABLE + " = new org.springframework.mail.SimpleMailMessage(" + TEMPLATE_MESSAGE_FIELD + ");"); } // Set the to address parameters.add(STRING, new JavaSymbolName("mailTo")); bodyBuilder.appendFormalLine(LOCAL_MESSAGE_VARIABLE + ".setTo(mailTo);"); // Set the message body parameters.add(STRING, new JavaSymbolName("message")); bodyBuilder.appendFormalLine(LOCAL_MESSAGE_VARIABLE + ".setText(message);"); bodyBuilder.newLine(); bodyBuilder.appendFormalLine(mailSenderName + ".send(" + LOCAL_MESSAGE_VARIABLE + ");"); final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( targetClassMID, Modifier.PUBLIC, new JavaSymbolName("sendMessage"), JavaType.VOID_PRIMITIVE, parameters.getKeys(), parameters.getValues(), bodyBuilder); if (async) { if (DomUtils.findFirstElementByName("task:annotation-driven", root) == null) { // Add asynchronous email support to the application if (!StringUtils.hasText(root.getAttribute("xmlns:task"))) { // Add the "task" namespace to the Spring config file root.setAttribute("xmlns:task", SPRING_TASK_NS); root.setAttribute( "xsi:schemaLocation", root.getAttribute("xsi:schemaLocation") + " " + SPRING_TASK_NS + " " + SPRING_TASK_XSD); } root.appendChild( new XmlElementBuilder("task:annotation-driven", document) .addAttribute("executor", "asyncExecutor") .addAttribute("mode", "aspectj") .build()); root.appendChild( new XmlElementBuilder("task:executor", document) .addAttribute("id", "asyncExecutor") .addAttribute("pool-size", "${executor.poolSize}") .build()); // Write out the new Spring config file fileManager.createOrUpdateTextFileIfRequired( contextPath, XmlUtils.nodeToString(document), false); // Update the email properties file propFileOperations.addPropertyIfNotExists( Path.SPRING_CONFIG_ROOT, "email.properties", "executor.poolSize", "10", true); } methodBuilder.addAnnotation(new AnnotationMetadataBuilder(ASYNC)); } return methodBuilder.build(); }
private TemplateDataDictionary buildDictionary(final GwtType type, final String moduleName) { Set<ClassOrInterfaceTypeDetails> proxies = typeLocationService.findClassesOrInterfaceDetailsWithAnnotation(RooJavaType.ROO_GWT_PROXY); TemplateDataDictionary dataDictionary = buildStandardDataDictionary(type, moduleName); switch (type) { case APP_ENTITY_TYPES_PROCESSOR: for (ClassOrInterfaceTypeDetails proxy : proxies) { if (!GwtUtils.scaffoldProxy(proxy)) { continue; } String proxySimpleName = proxy.getName().getSimpleTypeName(); ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy); if (entity != null) { String entitySimpleName = entity.getName().getSimpleTypeName(); dataDictionary.addSection("proxys").setVariable("proxy", proxySimpleName); String entity1 = new StringBuilder("\t\tif (") .append(proxySimpleName) .append(".class.equals(clazz)) {\n\t\t\tprocessor.handle") .append(entitySimpleName) .append("((") .append(proxySimpleName) .append(") null);\n\t\t\treturn;\n\t\t}") .toString(); dataDictionary.addSection("entities1").setVariable("entity", entity1); String entity2 = new StringBuilder("\t\tif (proxy instanceof ") .append(proxySimpleName) .append(") {\n\t\t\tprocessor.handle") .append(entitySimpleName) .append("((") .append(proxySimpleName) .append(") proxy);\n\t\t\treturn;\n\t\t}") .toString(); dataDictionary.addSection("entities2").setVariable("entity", entity2); String entity3 = new StringBuilder("\tpublic abstract void handle") .append(entitySimpleName) .append("(") .append(proxySimpleName) .append(" proxy);") .toString(); dataDictionary.addSection("entities3").setVariable("entity", entity3); addImport(dataDictionary, proxy.getName().getFullyQualifiedTypeName()); } } break; case MASTER_ACTIVITIES: for (ClassOrInterfaceTypeDetails proxy : proxies) { if (!GwtUtils.scaffoldProxy(proxy)) { continue; } String proxySimpleName = proxy.getName().getSimpleTypeName(); ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy); if (entity != null && !Modifier.isAbstract(entity.getModifier())) { String entitySimpleName = entity.getName().getSimpleTypeName(); TemplateDataDictionary section = dataDictionary.addSection("entities"); section.setVariable("entitySimpleName", entitySimpleName); section.setVariable("entityFullPath", proxySimpleName); addImport(dataDictionary, entitySimpleName, GwtType.LIST_ACTIVITY, moduleName); addImport(dataDictionary, proxy.getName().getFullyQualifiedTypeName()); addImport(dataDictionary, entitySimpleName, GwtType.LIST_VIEW, moduleName); addImport(dataDictionary, entitySimpleName, GwtType.MOBILE_LIST_VIEW, moduleName); } } break; case APP_REQUEST_FACTORY: for (ClassOrInterfaceTypeDetails proxy : proxies) { if (!GwtUtils.scaffoldProxy(proxy)) { continue; } ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy); if (entity != null && !Modifier.isAbstract(entity.getModifier())) { String entitySimpleName = entity.getName().getSimpleTypeName(); ClassOrInterfaceTypeDetails request = gwtTypeService.lookupRequestFromProxy(proxy); if (request != null) { String requestExpression = new StringBuilder("\t") .append(request.getName().getSimpleTypeName()) .append(" ") .append(StringUtils.uncapitalize(entitySimpleName)) .append("Request();") .toString(); dataDictionary.addSection("entities").setVariable("entity", requestExpression); addImport(dataDictionary, request.getName().getFullyQualifiedTypeName()); } } dataDictionary.setVariable( "sharedScaffoldPackage", GwtPath.SHARED_SCAFFOLD.packageName( projectOperations.getTopLevelPackage(moduleName))); } if (projectOperations.isFeatureInstalledInFocusedModule(FeatureNames.GAE)) { dataDictionary.showSection("gae"); } break; case LIST_PLACE_RENDERER: for (ClassOrInterfaceTypeDetails proxy : proxies) { if (!GwtUtils.scaffoldProxy(proxy)) { continue; } ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy); if (entity != null) { String entitySimpleName = entity.getName().getSimpleTypeName(); String proxySimpleName = proxy.getName().getSimpleTypeName(); TemplateDataDictionary section = dataDictionary.addSection("entities"); section.setVariable("entitySimpleName", entitySimpleName); section.setVariable("entityFullPath", proxySimpleName); addImport(dataDictionary, proxy.getName().getFullyQualifiedTypeName()); } } break; case DETAILS_ACTIVITIES: for (ClassOrInterfaceTypeDetails proxy : proxies) { if (!GwtUtils.scaffoldProxy(proxy)) { continue; } ClassOrInterfaceTypeDetails entity = gwtTypeService.lookupEntityFromProxy(proxy); if (entity != null) { String proxySimpleName = proxy.getName().getSimpleTypeName(); String entitySimpleName = entity.getName().getSimpleTypeName(); String entityExpression = new StringBuilder("\t\t\tpublic void handle") .append(entitySimpleName) .append("(") .append(proxySimpleName) .append(" proxy) {\n") .append("\t\t\t\tsetResult(new ") .append(entitySimpleName) .append( "ActivitiesMapper(requests, placeController).getActivity(proxyPlace));\n\t\t\t}") .toString(); dataDictionary.addSection("entities").setVariable("entity", entityExpression); addImport(dataDictionary, proxy.getName().getFullyQualifiedTypeName()); addImport( dataDictionary, GwtType.ACTIVITIES_MAPPER .getPath() .packageName(projectOperations.getTopLevelPackage(moduleName)) + "." + entitySimpleName + GwtType.ACTIVITIES_MAPPER.getSuffix()); } } break; case MOBILE_ACTIVITIES: // Do nothing break; } return dataDictionary; }
private TemplateDataDictionary buildMirrorDataDictionary( final GwtType type, final ClassOrInterfaceTypeDetails mirroredType, final ClassOrInterfaceTypeDetails proxy, final Map<GwtType, JavaType> mirrorTypeMap, final Map<JavaSymbolName, GwtProxyProperty> clientSideTypeMap, final String moduleName) { JavaType proxyType = proxy.getName(); JavaType javaType = mirrorTypeMap.get(type); TemplateDataDictionary dataDictionary = TemplateDictionary.create(); // Get my locator and JavaType entity = mirroredType.getName(); final String entityName = entity.getFullyQualifiedTypeName(); String metadataIdentificationString = mirroredType.getDeclaredByMetadataId(); final JavaType idType = persistenceMemberLocator.getIdentifierType(entity); Assert.notNull(idType, "Identifier type is not available for entity '" + entityName + "'"); final MethodParameter entityParameter = new MethodParameter(entity, "proxy"); ClassOrInterfaceTypeDetails request = gwtTypeService.lookupRequestFromProxy(proxy); MemberTypeAdditions persistMethodAdditions = layerService.getMemberTypeAdditions( metadataIdentificationString, CustomDataKeys.PERSIST_METHOD.name(), entity, idType, LAYER_POSITION, entityParameter); Assert.notNull( persistMethodAdditions, "Persist method is not available for entity '" + entityName + "'"); String persistMethodSignature = getRequestMethodCall(request, persistMethodAdditions); dataDictionary.setVariable("persistMethodSignature", persistMethodSignature); MemberTypeAdditions removeMethodAdditions = layerService.getMemberTypeAdditions( metadataIdentificationString, CustomDataKeys.REMOVE_METHOD.name(), entity, idType, LAYER_POSITION, entityParameter); Assert.notNull( removeMethodAdditions, "Remove method is not available for entity '" + entityName + "'"); String removeMethodSignature = getRequestMethodCall(request, removeMethodAdditions); dataDictionary.setVariable("removeMethodSignature", removeMethodSignature); MemberTypeAdditions countMethodAdditions = layerService.getMemberTypeAdditions( metadataIdentificationString, CustomDataKeys.COUNT_ALL_METHOD.name(), entity, idType, LAYER_POSITION); Assert.notNull( countMethodAdditions, "Count method is not available for entity '" + entityName + "'"); dataDictionary.setVariable("countEntitiesMethod", countMethodAdditions.getMethodName()); for (GwtType reference : type.getReferences()) { addReference(dataDictionary, reference, mirrorTypeMap); } addImport(dataDictionary, proxyType.getFullyQualifiedTypeName()); String pluralMetadataKey = PluralMetadata.createIdentifier( mirroredType.getName(), PhysicalTypeIdentifier.getPath(mirroredType.getDeclaredByMetadataId())); PluralMetadata pluralMetadata = (PluralMetadata) metadataService.get(pluralMetadataKey); String plural = pluralMetadata.getPlural(); final String simpleTypeName = mirroredType.getName().getSimpleTypeName(); final JavaPackage topLevelPackage = projectOperations.getTopLevelPackage(moduleName); dataDictionary.setVariable("className", javaType.getSimpleTypeName()); dataDictionary.setVariable("packageName", javaType.getPackage().getFullyQualifiedPackageName()); dataDictionary.setVariable("placePackage", GwtPath.SCAFFOLD_PLACE.packageName(topLevelPackage)); dataDictionary.setVariable( "scaffoldUiPackage", GwtPath.SCAFFOLD_UI.packageName(topLevelPackage)); dataDictionary.setVariable( "sharedScaffoldPackage", GwtPath.SHARED_SCAFFOLD.packageName(topLevelPackage)); dataDictionary.setVariable("uiPackage", GwtPath.MANAGED_UI.packageName(topLevelPackage)); dataDictionary.setVariable("name", simpleTypeName); dataDictionary.setVariable("pluralName", plural); dataDictionary.setVariable("nameUncapitalized", StringUtils.uncapitalize(simpleTypeName)); dataDictionary.setVariable("proxy", proxyType.getSimpleTypeName()); dataDictionary.setVariable("pluralName", plural); dataDictionary.setVariable( "proxyRenderer", GwtProxyProperty.getProxyRendererType(topLevelPackage, proxyType)); String proxyFields = null; GwtProxyProperty primaryProperty = null; GwtProxyProperty secondaryProperty = null; GwtProxyProperty dateProperty = null; Set<String> importSet = new HashSet<String>(); for (GwtProxyProperty gwtProxyProperty : clientSideTypeMap.values()) { // Determine if this is the primary property. if (primaryProperty == null) { // Choose the first available field. primaryProperty = gwtProxyProperty; } else if (gwtProxyProperty.isString() && !primaryProperty.isString()) { // Favor String properties over other types. secondaryProperty = primaryProperty; primaryProperty = gwtProxyProperty; } else if (secondaryProperty == null) { // Choose the next available property. secondaryProperty = gwtProxyProperty; } else if (gwtProxyProperty.isString() && !secondaryProperty.isString()) { // Favor String properties over other types. secondaryProperty = gwtProxyProperty; } // Determine if this is the first date property. if (dateProperty == null && gwtProxyProperty.isDate()) { dateProperty = gwtProxyProperty; } if (gwtProxyProperty.isProxy() || gwtProxyProperty.isCollectionOfProxy()) { if (proxyFields != null) { proxyFields += ", "; } else { proxyFields = ""; } proxyFields += "\"" + gwtProxyProperty.getName() + "\""; } dataDictionary.addSection("fields").setVariable("field", gwtProxyProperty.getName()); if (!isReadOnly(gwtProxyProperty.getName(), mirroredType)) { dataDictionary .addSection("editViewProps") .setVariable("prop", gwtProxyProperty.forEditView()); } TemplateDataDictionary propertiesSection = dataDictionary.addSection("properties"); propertiesSection.setVariable("prop", gwtProxyProperty.getName()); propertiesSection.setVariable( "propId", proxyType.getSimpleTypeName() + "_" + gwtProxyProperty.getName()); propertiesSection.setVariable("propGetter", gwtProxyProperty.getGetter()); propertiesSection.setVariable("propType", gwtProxyProperty.getType()); propertiesSection.setVariable("propFormatter", gwtProxyProperty.getFormatter()); propertiesSection.setVariable("propRenderer", gwtProxyProperty.getRenderer()); propertiesSection.setVariable("propReadable", gwtProxyProperty.getReadableName()); if (!isReadOnly(gwtProxyProperty.getName(), mirroredType)) { TemplateDataDictionary editableSection = dataDictionary.addSection("editableProperties"); editableSection.setVariable("prop", gwtProxyProperty.getName()); editableSection.setVariable( "propId", proxyType.getSimpleTypeName() + "_" + gwtProxyProperty.getName()); editableSection.setVariable("propGetter", gwtProxyProperty.getGetter()); editableSection.setVariable("propType", gwtProxyProperty.getType()); editableSection.setVariable("propFormatter", gwtProxyProperty.getFormatter()); editableSection.setVariable("propRenderer", gwtProxyProperty.getRenderer()); editableSection.setVariable("propBinder", gwtProxyProperty.getBinder()); editableSection.setVariable("propReadable", gwtProxyProperty.getReadableName()); } dataDictionary.setVariable("proxyRendererType", proxyType.getSimpleTypeName() + "Renderer"); if (gwtProxyProperty.isProxy() || gwtProxyProperty.isEnum() || gwtProxyProperty.isCollectionOfProxy()) { TemplateDataDictionary section = dataDictionary.addSection( gwtProxyProperty.isEnum() ? "setEnumValuePickers" : "setProxyValuePickers"); section.setVariable("setValuePicker", gwtProxyProperty.getSetValuePickerMethod()); section.setVariable("setValuePickerName", gwtProxyProperty.getSetValuePickerMethodName()); section.setVariable("valueType", gwtProxyProperty.getValueType().getSimpleTypeName()); section.setVariable("rendererType", gwtProxyProperty.getProxyRendererType()); if (gwtProxyProperty.isProxy() || gwtProxyProperty.isCollectionOfProxy()) { String propTypeName = StringUtils.uncapitalize( gwtProxyProperty.isCollectionOfProxy() ? gwtProxyProperty .getPropertyType() .getParameters() .get(0) .getSimpleTypeName() : gwtProxyProperty.getPropertyType().getSimpleTypeName()); propTypeName = propTypeName.substring(0, propTypeName.indexOf("Proxy")); section.setVariable("requestInterface", propTypeName + "Request"); section.setVariable( "findMethod", "find" + StringUtils.capitalize(propTypeName) + "Entries(0, 50)"); } maybeAddImport(dataDictionary, importSet, gwtProxyProperty.getPropertyType()); maybeAddImport(dataDictionary, importSet, gwtProxyProperty.getValueType()); if (gwtProxyProperty.isCollectionOfProxy()) { maybeAddImport( dataDictionary, importSet, gwtProxyProperty.getPropertyType().getParameters().get(0)); maybeAddImport(dataDictionary, importSet, gwtProxyProperty.getSetEditorType()); } } } dataDictionary.setVariable("proxyFields", proxyFields); // Add a section for the mobile properties. if (primaryProperty != null) { dataDictionary.setVariable("primaryProp", primaryProperty.getName()); dataDictionary.setVariable("primaryPropGetter", primaryProperty.getGetter()); dataDictionary.setVariable( "primaryPropBuilder", primaryProperty.forMobileListView("primaryRenderer")); TemplateDataDictionary section = dataDictionary.addSection("mobileProperties"); section.setVariable("prop", primaryProperty.getName()); section.setVariable("propGetter", primaryProperty.getGetter()); section.setVariable("propType", primaryProperty.getType()); section.setVariable("propRenderer", primaryProperty.getRenderer()); section.setVariable("propRendererName", "primaryRenderer"); } else { dataDictionary.setVariable("primaryProp", "id"); dataDictionary.setVariable("primaryPropGetter", "getId"); dataDictionary.setVariable("primaryPropBuilder", ""); } if (secondaryProperty != null) { dataDictionary.setVariable( "secondaryPropBuilder", secondaryProperty.forMobileListView("secondaryRenderer")); TemplateDataDictionary section = dataDictionary.addSection("mobileProperties"); section.setVariable("prop", secondaryProperty.getName()); section.setVariable("propGetter", secondaryProperty.getGetter()); section.setVariable("propType", secondaryProperty.getType()); section.setVariable("propRenderer", secondaryProperty.getRenderer()); section.setVariable("propRendererName", "secondaryRenderer"); } else { dataDictionary.setVariable("secondaryPropBuilder", ""); } if (dateProperty != null) { dataDictionary.setVariable("datePropBuilder", dateProperty.forMobileListView("dateRenderer")); TemplateDataDictionary section = dataDictionary.addSection("mobileProperties"); section.setVariable("prop", dateProperty.getName()); section.setVariable("propGetter", dateProperty.getGetter()); section.setVariable("propType", dateProperty.getType()); section.setVariable("propRenderer", dateProperty.getRenderer()); section.setVariable("propRendererName", "dateRenderer"); } else { dataDictionary.setVariable("datePropBuilder", ""); } return dataDictionary; }