@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);
    }
  }
Пример #2
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);
  }
 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);
 }
Пример #5
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);
  }
Пример #6
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());
  }
Пример #7
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;
  }
  /**
   * 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());
    }
  }
Пример #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);
      }
    }
  }
  @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);
  }
Пример #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);
   }
 }
  @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);
  }
Пример #14
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);
  }
Пример #15
0
 public boolean isManageEmailAvailable() {
   return projectOperations.isProjectAvailable()
       && fileManager.exists(getApplicationContextPath());
 }
Пример #16
0
 private boolean hasDotGit() {
   return fileManager.exists(pathResolver.getFocusedIdentifier(Path.ROOT, Constants.DOT_GIT));
 }
  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;
  }