Пример #1
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;
  }