Пример #1
0
  public Database getDatabase(final boolean evictCache) {
    if (!evictCache && cachedIntrospections.contains(lastDatabase)) {
      for (final Database database : cachedIntrospections) {
        if (database.equals(lastDatabase)) {
          return lastDatabase;
        }
      }
    }
    if (evictCache && cachedIntrospections.contains(lastDatabase)) {
      cachedIntrospections.remove(lastDatabase);
    }

    final String dbreXmlPath = getDbreXmlPath();
    if (StringUtils.isBlank(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 (final Exception e) {
      throw new IllegalStateException(e);
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
  }
  @Override
  public void layout(
      final String name,
      final Dimension height,
      final Dimension width,
      final Orientation orientation) {
    final Document document = newDocumentBuilder().newDocument();

    final Element layoutElem = document.createElement("LinearLayout");
    layoutElem.setAttribute("xmlns:android", ANDROID_NS);
    layoutElem.setAttribute("android:layout_height", height.value());
    layoutElem.setAttribute("android:layout_width", width.value());
    layoutElem.setAttribute("android:orientation", orientation.value());
    document.appendChild(layoutElem);

    final String layoutPath =
        pathResolver.getFocusedIdentifier(Path.ROOT, LAYOUT_PATH + SEP + name + XML_EXTENSION);
    if (fileManager.exists(layoutPath)) {
      LOGGER.severe("Layout '" + name + "' already exists");
      return;
    }
    final MutableFile file = fileManager.createFile(layoutPath);
    final OutputStream output = file.getOutputStream();
    XmlUtils.writeFormattedXml(output, document);
    try {
      output.close();
    } catch (IOException e) {
      LOGGER.severe("Error closing stream: " + e.getMessage());
      return;
    }
    //        fileManager.createOrUpdateTextFileIfRequired(layoutPath,
    //                XmlUtils.nodeToString(document), true);
  }
 /**
  * Deletes the given ITD, either now or later.
  *
  * @param metadataId the ITD's metadata ID
  * @param itdFilename the ITD's filename
  * @param reason the reason for deletion; ignored if now is <code>false</code>
  * @param now whether to delete the ITD immediately; <code>false</code> schedules it for later
  *     deletion; this is preferable when it's possible that the ITD might need to be re-created in
  *     the meantime (e.g. because some ancestor metadata has changed to that effect), otherwise
  *     there will be spurious console messages about the ITD being deleted and created
  */
 private void deleteItd(
     final String metadataId, final String itdFilename, final String reason, final boolean now) {
   if (now) {
     fileManager.delete(itdFilename, reason);
   } else {
     fileManager.createOrUpdateTextFileIfRequired(itdFilename, "", false);
   }
   itdDiscoveryService.removeItdTypeDetails(metadataId);
   // TODO do we need to notify downstream dependencies that this ITD has gone away?
 }
Пример #4
0
  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);
    }
  }
Пример #5
0
  private Properties getConnectionPropertiesFromDataNucleusConfiguration() {
    final String persistenceXmlPath =
        projectOperations
            .getPathResolver()
            .getFocusedIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
    if (!fileManager.exists(persistenceXmlPath)) {
      throw new IllegalStateException("Failed to find " + persistenceXmlPath);
    }

    final FileDetails fileDetails = fileManager.readFile(persistenceXmlPath);
    Document document = null;
    try {
      final InputStream is = new BufferedInputStream(new FileInputStream(fileDetails.getFile()));
      final DocumentBuilder builder = XmlUtils.getDocumentBuilder();
      builder.setErrorHandler(null);
      document = builder.parse(is);
    } catch (final Exception e) {
      throw new IllegalStateException(e);
    }

    final List<Element> propertyElements =
        XmlUtils.findElements(
            "/persistence/persistence-unit/properties/property", document.getDocumentElement());
    Validate.notEmpty(
        propertyElements, "Failed to find property elements in " + persistenceXmlPath);
    final Properties properties = new Properties();

    for (final Element propertyElement : propertyElements) {
      final String key = propertyElement.getAttribute("name");
      final String value = propertyElement.getAttribute("value");
      if ("datanucleus.ConnectionDriverName".equals(key)) {
        properties.put("database.driverClassName", value);
      }
      if ("datanucleus.ConnectionURL".equals(key)) {
        properties.put("database.url", value);
      }
      if ("datanucleus.ConnectionUserName".equals(key)) {
        properties.put("database.username", value);
      }
      if ("datanucleus.ConnectionPassword".equals(key)) {
        properties.put("database.password", value);
      }

      if (properties.size() == 4) {
        // All required properties have been found so ignore rest of
        // elements
        break;
      }
    }
    return properties;
  }
  @Override
  public void setup() {
    if (!fileManager.exists(
        projectOperations
            .getPathResolver()
            .getFocusedIdentifier(SRC_MAIN_WEBAPP, "WEB-INF/web.xml"))) {
      webMvcOperations.installAllWebMvcArtifacts();
    }

    final Element configuration = XmlUtils.getConfiguration(getClass());

    for (Element propertyElement :
        XmlUtils.findElements("/configuration/batch/properties/*", configuration)) {
      projectOperations.addProperty(
          projectOperations.getFocusedModuleName(), new Property(propertyElement));
    }

    final List<Dependency> dependencies = new ArrayList<Dependency>();
    for (final Element dependencyElement :
        XmlUtils.findElements("/configuration/batch/dependencies/*", configuration)) {
      dependencies.add(new Dependency(dependencyElement));
    }
    projectOperations.removeDependencies(projectOperations.getFocusedModuleName(), dependencies);
    metadataService.evict(
        ProjectMetadata.getProjectIdentifier(projectOperations.getFocusedModuleName()));
    projectOperations.addDependencies(projectOperations.getFocusedModuleName(), dependencies);

    final String webConfigFile =
        pathResolver.getFocusedIdentifier(Path.SRC_MAIN_WEBAPP, WEBMVC_CONFIG_XML);
    Validate.isTrue(fileManager.exists(webConfigFile), "Aborting: Unable to find " + webConfigFile);
    InputStream webMvcConfigInputStream = null;
    try {
      webMvcConfigInputStream = fileManager.getInputStream(webConfigFile);
      Validate.notNull(
          webMvcConfigInputStream, "Aborting: Unable to acquire webmvc-config.xml file");
      final Document webMvcConfig = XmlUtils.readXml(webMvcConfigInputStream);
      final Element root = webMvcConfig.getDocumentElement();
      if (XmlUtils.findFirstElement("/beans/bean[@class='" + REST_MVC_CONFIG + "']", root)
          == null) {
        final Element config = webMvcConfig.createElement("bean");
        config.setAttribute("class", REST_MVC_CONFIG);
        root.appendChild(config);

        fileManager.createOrUpdateTextFileIfRequired(
            webConfigFile, XmlUtils.nodeToString(webMvcConfig), true);
      }
    } finally {
      IOUtils.closeQuietly(webMvcConfigInputStream);
    }
  }
  /**
   * Deletes the given {@link JavaType} for the given reason
   *
   * @param javaType the type to be deleted (required)
   * @param reason the reason for deletion (can be blank)
   */
  private void deleteJavaType(final JavaType javaType, final String reason) {
    final PhysicalTypeMetadata governorPhysicalTypeMetadata = getPhysicalTypeMetadata(javaType);
    if (governorPhysicalTypeMetadata != null) {
      final String filePath = governorPhysicalTypeMetadata.getPhysicalLocationCanonicalPath();
      if (fileManager.exists(filePath)) {
        fileManager.delete(filePath, reason);
        shell.flash(
            Level.FINE,
            "Deleted " + javaType.getFullyQualifiedTypeName(),
            DbreDatabaseListenerImpl.class.getName());
      }

      shell.flash(Level.FINE, "", DbreDatabaseListenerImpl.class.getName());
    }
  }
  @Override
  public void resourceString(
      final JavaType type, final String name, final JavaSymbolName fieldName, final String value) {

    final ClassOrInterfaceTypeDetails typeDetails = typeLocationService.getTypeDetails(type);
    Validate.notNull(typeDetails, "The type specified, '" + type + "' doesn't exist");

    final DocumentBuilder builder = newDocumentBuilder();
    final String valuesPath =
        pathResolver.getFocusedIdentifier(Path.ROOT, VALUES_PATH + SEP + STRINGS + XML_EXTENSION);

    InputStream inputStream = null;
    Document document = null;
    try {
      inputStream = fileManager.getInputStream(valuesPath);
      document = builder.parse(inputStream);
    } catch (final Exception e) {
      LOGGER.severe("Error reading resource XML: " + e.getMessage());
    } finally {
      IOUtils.closeQuietly(inputStream);
    }

    if (document != null) {
      final Element root = document.getDocumentElement();

      final Element stringElem = XmlUtils.createTextElement(document, "string", value);
      final String id = StringUtils.isEmpty(name) ? fieldName.getSymbolName() : name;
      stringElem.setAttribute("name", id);
      root.appendChild(stringElem);

      fileManager.createOrUpdateTextFileIfRequired(
          valuesPath, XmlUtils.nodeToString(document), true);
    }

    final String physicalTypeIdentifier = typeDetails.getDeclaredByMetadataId();

    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    final AnnotationMetadataBuilder annotationBuilder = new AnnotationMetadataBuilder(ROO_STRING);
    if (!StringUtils.isEmpty(name)) {
      annotationBuilder.addStringAttribute("value", name);
    }
    annotations.add(annotationBuilder);

    final FieldMetadataBuilder fieldBuilder =
        new FieldMetadataBuilder(physicalTypeIdentifier, 0, annotations, fieldName, STRING);
    typeManagementService.addField(fieldBuilder.build());
  }
Пример #9
0
  public void setup() {
    if (hasDotGit()) {
      LOGGER.info("Git is already configured");
      return;
    }
    if (person == null) {
      person = new PersonIdent("Roo Git Add-On", "*****@*****.**");
    }
    try {
      final String repositoryPath = pathResolver.getFocusedIdentifier(Path.ROOT, Constants.DOT_GIT);
      final Repository repository =
          new FileRepositoryBuilder().readEnvironment().setGitDir(new File(repositoryPath)).build();
      repository.create();
    } catch (final Exception e) {
      throw new IllegalStateException("Could not initialize Git repository", e);
    }
    setConfig("user", "name", person.getName());
    setConfig("user", "email", person.getEmailAddress());

    setConfig("remote \"origin\"", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    setConfig("branch \"master\"", "remote", "origin");
    setConfig("branch \"master\"", "merge", "refs/heads/master");

    final String gitIgnore =
        pathResolver.getFocusedIdentifier(Path.ROOT, Constants.GITIGNORE_FILENAME);

    if (!fileManager.exists(gitIgnore)) {
      InputStream inputStream = null;
      OutputStream outputStream = null;
      try {
        inputStream = FileUtils.getInputStream(getClass(), "gitignore-template");
        outputStream = fileManager.createFile(gitIgnore).getOutputStream();
        IOUtils.copy(inputStream, outputStream);
      } catch (final IOException e) {
        throw new IllegalStateException(
            "Could not install " + Constants.GITIGNORE_FILENAME + " file in project", e);
      } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
      }
    }
  }
Пример #10
0
 private String getJndiDataSourceName() {
   final String contextPath =
       projectOperations
           .getPathResolver()
           .getFocusedIdentifier(Path.SPRING_CONFIG_ROOT, "applicationContext.xml");
   final Document appCtx = XmlUtils.readXml(fileManager.getInputStream(contextPath));
   final Element root = appCtx.getDocumentElement();
   final Element dataSourceJndi =
       XmlUtils.findFirstElement("/beans/jndi-lookup[@id = 'dataSource']", root);
   return dataSourceJndi != null ? dataSourceJndi.getAttribute("jndi-name") : null;
 }
Пример #11
0
  @Test
  public void testAddJasperReportsViewResolver() {
    String webMvcConfig = WEB_MVC_CONFIG;
    PathResolver pathResolver = projectOperations.getPathResolver();
    when(pathResolver.getIdentifier(
            LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), "WEB-INF/spring/webmvc-config.xml"))
        .thenReturn(webMvcConfig);
    StubMutableFile webMvcConfigFile =
        new StubMutableFile(new File(getClass().getResource(webMvcConfig).getFile()));
    when(fileManager.exists(webMvcConfig)).thenReturn(true);
    when(fileManager.updateFile(webMvcConfig)).thenReturn(webMvcConfigFile);

    // operations.addJasperReportsViewResolver();
    String output = webMvcConfigFile.getOutputAsString();
    assertThat(
        output,
        containsString(
            "<bean id=\"jasperReportsXmlViewResolver\" class=\"org.springframework.web.servlet.view.XmlViewResolver\" p:location=\"/WEB-INF/spring/jasper-views.xml\" p:order=\"0\" />"));
    assertThat(output, containsString("<import resource=\"jasper-views.xml\" />"));
  }
 @Override
 public boolean isInstalledInModule(String moduleName) {
   final String webConfigFile =
       pathResolver.getFocusedIdentifier(Path.SRC_MAIN_WEBAPP, WEBMVC_CONFIG_XML);
   if (!fileManager.exists(webConfigFile)) {
     return false;
   }
   InputStream webMvcConfigInputStream = null;
   try {
     webMvcConfigInputStream = fileManager.getInputStream(webConfigFile);
     if (webMvcConfigInputStream == null) {
       return false;
     }
     final Document webMvcConfig = XmlUtils.readXml(webMvcConfigInputStream);
     final Element root = webMvcConfig.getDocumentElement();
     return XmlUtils.findFirstElement("/beans/bean[@class='" + REST_MVC_CONFIG + "']", root)
         != null;
   } finally {
     IOUtils.closeQuietly(webMvcConfigInputStream);
   }
 }
Пример #13
0
 private String getDbreXmlPath() {
   for (String moduleName : projectOperations.getModuleNames()) {
     LogicalPath logicalPath = LogicalPath.getInstance(Path.SRC_MAIN_RESOURCES, moduleName);
     String dbreXmlPath = projectOperations.getPathResolver().getIdentifier(logicalPath, DBRE_XML);
     if (fileManager.exists(dbreXmlPath)) {
       return dbreXmlPath;
     }
   }
   return projectOperations
       .getPathResolver()
       .getFocusedIdentifier(Path.SRC_MAIN_RESOURCES, DBRE_XML);
 }
Пример #14
0
  public void setupService(
      final JavaType interfaceType, final JavaType classType, final JavaType domainType) {
    Assert.notNull(interfaceType, "Interface type required");
    Assert.notNull(classType, "Class type required");
    Assert.notNull(domainType, "Domain type required");

    String interfaceIdentifier =
        pathResolver.getFocusedCanonicalPath(Path.SRC_MAIN_JAVA, interfaceType);
    String classIdentifier = pathResolver.getFocusedCanonicalPath(Path.SRC_MAIN_JAVA, classType);

    if (fileManager.exists(interfaceIdentifier) || fileManager.exists(classIdentifier)) {
      return; // Type exists already - nothing to do
    }

    // First build interface type
    AnnotationMetadataBuilder interfaceAnnotationMetadata =
        new AnnotationMetadataBuilder(ROO_SERVICE);
    interfaceAnnotationMetadata.addAttribute(
        new ArrayAttributeValue<ClassAttributeValue>(
            new JavaSymbolName("domainTypes"),
            Arrays.asList(new ClassAttributeValue(new JavaSymbolName("foo"), domainType))));
    String interfaceMdId =
        PhysicalTypeIdentifier.createIdentifier(
            interfaceType, pathResolver.getPath(interfaceIdentifier));
    ClassOrInterfaceTypeDetailsBuilder interfaceTypeBuilder =
        new ClassOrInterfaceTypeDetailsBuilder(
            interfaceMdId, Modifier.PUBLIC, interfaceType, PhysicalTypeCategory.INTERFACE);
    interfaceTypeBuilder.addAnnotation(interfaceAnnotationMetadata.build());
    typeManagementService.createOrUpdateTypeOnDisk(interfaceTypeBuilder.build());

    // Second build the implementing class
    String classMdId =
        PhysicalTypeIdentifier.createIdentifier(classType, pathResolver.getPath(classIdentifier));
    ClassOrInterfaceTypeDetailsBuilder classTypeBuilder =
        new ClassOrInterfaceTypeDetailsBuilder(
            classMdId, Modifier.PUBLIC, classType, PhysicalTypeCategory.CLASS);
    classTypeBuilder.addImplementsType(interfaceType);
    typeManagementService.createOrUpdateTypeOnDisk(classTypeBuilder.build());
  }
Пример #15
0
  private Connection getConnection(final boolean displayAddOns) {
    if (fileManager.exists(
        pathResolver.getFocusedIdentifier(Path.SPRING_CONFIG_ROOT, "database.properties"))) {
      Map<String, String> connectionProperties =
          propFileOperations.getProperties(
              Path.SPRING_CONFIG_ROOT.contextualize(projectOperations.getFocusedModuleName()),
              "database.properties");
      return connectionProvider.getConnection(connectionProperties, displayAddOns);
    }

    Properties connectionProperties = getConnectionPropertiesFromDataNucleusConfiguration();
    return connectionProvider.getConnection(connectionProperties, displayAddOns);
  }
 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);
 }
  @Override
  public void activity(
      final JavaType name,
      final String layout,
      final boolean main,
      final boolean noTitle,
      final boolean fullscreen) {
    if (noTitle) {
      Validate.isTrue(fullscreen == false, "Options 'noTitle' and 'fullscreen' are mutex");
    }
    if (fullscreen) {
      Validate.isTrue(noTitle == false, "Options 'noTitle' and 'fullscreen' are mutex");
    }

    if (!StringUtils.isEmpty(layout)) {
      final String layoutPath =
          pathResolver.getFocusedIdentifier(Path.ROOT, LAYOUT_PATH + SEP + layout + XML_EXTENSION);
      if (!fileManager.exists(layoutPath)) {
        LOGGER.info("Layout '" + layout + "' does not exist");
        layout(layout, Dimension.FILL_PARENT, Dimension.FILL_PARENT, Orientation.VERTICAL);
      }
    }

    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    final AnnotationMetadataBuilder activityAnnotationBuilder =
        new AnnotationMetadataBuilder(ROO_ACTIVITY);
    if (!StringUtils.isEmpty(layout)) {
      activityAnnotationBuilder.addStringAttribute("value", layout);
    }
    if (noTitle) {
      activityAnnotationBuilder.addBooleanAttribute(RooActivity.NO_TITLE_ATTRIBUTE, noTitle);
    }
    if (fullscreen) {
      activityAnnotationBuilder.addBooleanAttribute(RooActivity.FULLSCREEN_ATTRIBUTE, fullscreen);
    }
    annotations.add(activityAnnotationBuilder);

    jpaOperations.newEntity(name, false, ANDROID_ACTIVITY, annotations);

    androidTypeService.addActvity(
        projectOperations.getFocusedModuleName(), name.getFullyQualifiedTypeName(), main);
  }
  @Override
  public void fragment(final JavaType name, final String layout, final boolean support) {

    if (!StringUtils.isEmpty(layout)) {
      final String layoutPath =
          pathResolver.getFocusedIdentifier(Path.ROOT, LAYOUT_PATH + SEP + layout + XML_EXTENSION);
      if (!fileManager.exists(layoutPath)) {
        LOGGER.info("Layout '" + layout + "' does not exist");
        layout(layout, Dimension.FILL_PARENT, Dimension.FILL_PARENT, Orientation.VERTICAL);
      }
    }

    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    final AnnotationMetadataBuilder activityAnnotationBuilder =
        new AnnotationMetadataBuilder(ROO_FRAGMENT);
    if (!StringUtils.isEmpty(layout)) {
      activityAnnotationBuilder.addStringAttribute("value", layout);
    }
    annotations.add(activityAnnotationBuilder);

    jpaOperations.newEntity(
        name, false, support ? ANDROID_SUPPORT_FRAGMENT : ANDROID_FRAGMENT, annotations);
  }
Пример #19
0
  private Connection getConnection(final boolean displayAddOns) {
    final String dbProps = "database.properties";
    final String jndiDataSource = getJndiDataSourceName();
    if (StringUtils.isNotBlank(jndiDataSource)) {
      final 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))) {
      final Map<String, String> props =
          propFileOperations.getProperties(
              Path.SPRING_CONFIG_ROOT.getModulePathId(projectOperations.getFocusedModuleName()),
              dbProps);
      return connectionProvider.getConnection(props, displayAddOns);
    }

    final Properties connectionProperties = getConnectionPropertiesFromDataNucleusConfiguration();
    return connectionProvider.getConnection(connectionProperties, displayAddOns);
  }
Пример #20
0
 public void writeDatabase(final Database database) {
   final Document document = DatabaseXmlUtils.getDatabaseDocument(database);
   fileManager.createOrUpdateTextFileIfRequired(
       getDbreXmlPath(), XmlUtils.nodeToString(document), true);
 }
  @Override
  public void view(
      final JavaType type,
      final String viewName,
      final String identifier,
      final JavaSymbolName fieldName,
      final Dimension height,
      final Dimension width) {

    final ClassOrInterfaceTypeDetails typeDetails = typeLocationService.getTypeDetails(type);
    Validate.notNull(typeDetails, "The type specified, '" + type + "'doesn't exist");

    final JavaType viewType =
        new JavaType(viewName.contains(".") ? viewName : WIDGET_PACKAGE + "." + viewName);

    final String layout =
        RequestFactoryUtils.getStringAnnotationValue(typeDetails, ROO_ACTIVITY, "value", "");
    if (!StringUtils.isEmpty(layout)) {
      final DocumentBuilder builder = newDocumentBuilder();
      final String layoutPath =
          pathResolver.getFocusedIdentifier(Path.ROOT, LAYOUT_PATH + SEP + layout + XML_EXTENSION);

      InputStream inputStream = null;
      Document document = null;
      try {
        inputStream = fileManager.getInputStream(layoutPath);
        document = builder.parse(inputStream);
      } catch (final Exception e) {
        LOGGER.severe("Error reading layout XML: " + e.getMessage());
      } finally {
        IOUtils.closeQuietly(inputStream);
      }

      if (document != null) {
        final Element root = document.getDocumentElement();

        final Element viewElem = document.createElement(viewType.getSimpleTypeName());
        final String id = StringUtils.isEmpty(identifier) ? fieldName.getSymbolName() : identifier;
        viewElem.setAttribute("android:id", ID_PREFIX + id);
        viewElem.setAttribute("android:layout_height", height.value());
        viewElem.setAttribute("android:layout_width", width.value());
        root.appendChild(viewElem);

        fileManager.createOrUpdateTextFileIfRequired(
            layoutPath, XmlUtils.nodeToString(document), true);
      }
    }

    final String physicalTypeIdentifier = typeDetails.getDeclaredByMetadataId();

    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    final AnnotationMetadataBuilder annotationBuilder = new AnnotationMetadataBuilder(ROO_VIEW);
    if (!StringUtils.isEmpty(identifier)) {
      annotationBuilder.addStringAttribute("value", identifier);
    }
    annotations.add(annotationBuilder);

    final FieldMetadataBuilder fieldBuilder =
        new FieldMetadataBuilder(physicalTypeIdentifier, 0, annotations, fieldName, viewType);
    typeManagementService.addField(fieldBuilder.build());
  }
 public void createOrUpdateTypeOnDisk(final ClassOrInterfaceTypeDetails cid) {
   final String fileCanonicalPath =
       typeLocationService.getPhysicalTypeCanonicalPath(cid.getDeclaredByMetadataId());
   final String newContents = typeParsingService.getCompilationUnitContents(cid);
   fileManager.createOrUpdateTextFileIfRequired(fileCanonicalPath, newContents, true);
 }
Пример #23
0
  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);
  }
Пример #24
0
 public boolean isManageEmailAvailable() {
   return projectOperations.isProjectAvailable()
       && fileManager.exists(getApplicationContextPath());
 }
Пример #25
0
  /**
   * 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();
  }
  public final MetadataItem get(final String metadataIdentificationString) {
    Assert.isTrue(
        MetadataIdentificationUtils.getMetadataClass(metadataIdentificationString)
            .equals(MetadataIdentificationUtils.getMetadataClass(getProvidesType())),
        "Unexpected request for '"
            + metadataIdentificationString
            + "' to this provider (which uses '"
            + getProvidesType()
            + "'");

    // Remove the upstream dependencies for this instance (we'll be recreating them later, if
    // needed)
    metadataDependencyRegistry.deregisterDependencies(metadataIdentificationString);

    // Compute the identifier for the Physical Type Metadata we're correlated with
    String governorPhysicalTypeIdentifier =
        getGovernorPhysicalTypeIdentifier(metadataIdentificationString);

    // Obtain the physical type
    PhysicalTypeMetadata governorPhysicalTypeMetadata =
        (PhysicalTypeMetadata) metadataService.get(governorPhysicalTypeIdentifier);
    if (governorPhysicalTypeMetadata == null || !governorPhysicalTypeMetadata.isValid()) {
      // We can't get even basic information about the physical type, so abort (the ITD will be
      // deleted by ItdFileDeletionService)
      return null;
    }

    // Flag to indicate whether we'll even try to create this metadata
    boolean produceMetadata = false;

    // Determine if we should generate the metadata on the basis of it containing a trigger
    // annotation
    ClassOrInterfaceTypeDetails cid = null;
    if (governorPhysicalTypeMetadata.getMemberHoldingTypeDetails()
        instanceof ClassOrInterfaceTypeDetails) {
      cid =
          (ClassOrInterfaceTypeDetails) governorPhysicalTypeMetadata.getMemberHoldingTypeDetails();
      // Only create metadata if the type is annotated with one of the metadata triggers
      for (JavaType trigger : metadataTriggers) {
        if (cid.getAnnotation(trigger) != null) {
          produceMetadata = true;
          break;
        }
      }
    }

    // Fall back to ignoring trigger annotations
    if (ignoreTriggerAnnotations) {
      produceMetadata = true;
    }

    // Cancel production if the governor type details are required, but aren't available
    if (dependsOnGovernorTypeDetailAvailability && cid == null) {
      produceMetadata = false;
    }

    // Cancel production if the governor is not a class, and the subclass only wants to know about
    // classes
    if (cid != null
        && dependsOnGovernorBeingAClass
        && cid.getPhysicalTypeCategory() != PhysicalTypeCategory.CLASS) {
      produceMetadata = false;
    }

    String itdFilename = governorPhysicalTypeMetadata.getItdCanonicalPath(this);
    if (!produceMetadata && isGovernor(cid) && fileManager.exists(itdFilename)) {
      // We don't seem to want metadata anymore, yet the ITD physically exists, so get rid of it
      // This might be because the trigger annotation has been removed, the governor is missing a
      // class declaration, etc.
      deleteItd(
          metadataIdentificationString,
          itdFilename,
          "not required for governor " + cid.getName(),
          true);
      return null;
    }

    if (produceMetadata) {
      // This type contains an annotation we were configured to detect, or there is an ITD (which
      // may need deletion), so we need to produce the metadata
      JavaType aspectName = governorPhysicalTypeMetadata.getItdJavaType(this);
      ItdTypeDetailsProvidingMetadataItem metadata =
          getMetadata(
              metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, itdFilename);

      // There is no requirement to register a direct connection with the physical type and this
      // metadata because changes will
      // trickle down via the class-level notification registered by convention by
      // AbstractItdMetadataProvider subclasses (BPA 10 Dec 2010)

      if (metadata == null || !metadata.isValid()) {
        // The metadata couldn't be created properly
        deleteItd(metadataIdentificationString, itdFilename, "", false);
        return null;
      }

      // By this point we have a valid MetadataItem, but it might not contain any members for the
      // resulting ITD etc

      // Handle the management of the ITD file
      boolean deleteItdFile = false;
      ItdTypeDetails itdTypeDetails = metadata.getMemberHoldingTypeDetails();

      if (itdTypeDetails == null) {
        // The ITD has no members
        deleteItdFile = true;
      }

      if (!deleteItdFile) {
        // We have some members in the ITD, so decide if we're to write something to disk
        ItdSourceFileComposer itdSourceFileComposer =
            new ItdSourceFileComposer(metadata.getMemberHoldingTypeDetails());

        // Decide whether the get an ITD on-disk based on whether there is physical content to write
        if (itdSourceFileComposer.isContent()) {
          // We have content to write
          itdDiscoveryService.addItdTypeDetails(itdTypeDetails);
          String itd = itdSourceFileComposer.getOutput();
          fileManager.createOrUpdateTextFileIfRequired(itdFilename, itd, false);
        } else {
          // We don't have content to write
          deleteItdFile = true;
        }
      }

      if (deleteItdFile) {
        deleteItd(metadataIdentificationString, itdFilename, null, false);
      }

      // Eagerly notify that the metadata has been updated; this also registers the metadata hash
      // code in the superclass' cache to avoid
      // unnecessary subsequent notifications if it hasn't changed
      notifyIfRequired(metadata);

      return metadata;
    }
    return null;
  }
Пример #27
0
 private boolean hasDotGit() {
   return fileManager.exists(pathResolver.getFocusedIdentifier(Path.ROOT, Constants.DOT_GIT));
 }