/**
   * determine if management console can display the second level cache entries
   *
   * @param pu
   * @return false if a custom AvailableSettings.CACHE_REGION_PREFIX property is specified. true if
   *     the scoped persistence unit name is used to prefix cache entries.
   */
  @Override
  public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName(PersistenceUnitMetadata pu) {
    String cacheRegionPrefix =
        pu.getProperties().getProperty(AvailableSettings.CACHE_REGION_PREFIX);

    return cacheRegionPrefix == null || cacheRegionPrefix.equals(pu.getScopedPersistenceUnitName());
  }
 @SuppressWarnings("deprecation")
 @Override
 public void addProviderProperties(Map properties, PersistenceUnitMetadata pu) {
   putPropertyIfAbsent(pu, properties, Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
   putPropertyIfAbsent(
       pu,
       properties,
       org.hibernate.ejb.AvailableSettings.SCANNER,
       HibernateAnnotationScanner.class.getName());
   properties.put(AvailableSettings.APP_CLASSLOADER, pu.getClassLoader());
   putPropertyIfAbsent(pu, properties, AvailableSettings.JTA_PLATFORM, appServerJtaPlatform);
   properties.remove(
       AvailableSettings
           .TRANSACTION_MANAGER_STRATEGY); // remove legacy way of specifying TX manager (conflicts
   // with JTA_PLATFORM)
   putPropertyIfAbsent(
       pu,
       properties,
       org.hibernate.ejb.AvailableSettings.ENTITY_MANAGER_FACTORY_NAME,
       pu.getScopedPersistenceUnitName());
   putPropertyIfAbsent(
       pu, properties, AvailableSettings.SESSION_FACTORY_NAME, pu.getScopedPersistenceUnitName());
   if (!pu.getProperties().containsKey(AvailableSettings.SESSION_FACTORY_NAME)) {
     putPropertyIfAbsent(
         pu, properties, AvailableSettings.SESSION_FACTORY_NAME_IS_JNDI, Boolean.FALSE);
   }
 }
 @Override
 public void start(StartContext context) throws StartException {
   try {
     JPA_LOGGER.startingService("Persistence Unit", pu.getScopedPersistenceUnitName());
     pu.setJtaDataSource(jtaDataSource.getOptionalValue());
     pu.setNonJtaDataSource(nonJtaDataSource.getOptionalValue());
     this.entityManagerFactory = createContainerEntityManagerFactory();
   } finally {
     pu.setTempClassLoaderFactory(
         null); // release the temp classloader factory (only needed when creating the EMF)
   }
 }
 @Override
 public void stop(StopContext context) {
   JPA_LOGGER.stoppingService("Persistence Unit", pu.getScopedPersistenceUnitName());
   if (entityManagerFactory != null) {
     WritableServiceBasedNamingStore.pushOwner(
         context.getController().getServiceContainer().subTarget());
     try {
       entityManagerFactory.close();
     } finally {
       entityManagerFactory = null;
       pu.setTempClassLoaderFactory(null);
       WritableServiceBasedNamingStore.popOwner();
     }
   }
 }
예제 #5
0
 private InjectionSource getPersistenceUnitBindingSource(
     final DeploymentUnit deploymentUnit, final String unitName)
     throws DeploymentUnitProcessingException {
   final String searchName;
   if (isEmpty(unitName)) {
     searchName = null;
   } else {
     searchName = unitName;
   }
   final PersistenceUnitMetadata pu =
       PersistenceUnitSearch.resolvePersistenceUnitSupplier(deploymentUnit, searchName);
   String scopedPuName = pu.getScopedPersistenceUnitName();
   ServiceName puServiceName = getPuServiceName(scopedPuName);
   return new PersistenceUnitInjectionSource(
       puServiceName, deploymentUnit, EntityManagerFactory.class.getName(), pu);
 }
 @Override
 public void start(StartContext context) throws StartException {
   try {
     JPA_LOGGER.startingService("Persistence Unit", pu.getScopedPersistenceUnitName());
     pu.setTempClassLoaderFactory(new TempClassLoaderFactoryImpl(classLoader));
     pu.setJtaDataSource(jtaDataSource.getOptionalValue());
     pu.setNonJtaDataSource(nonJtaDataSource.getOptionalValue());
     WritableServiceBasedNamingStore.pushOwner(
         context.getController().getServiceContainer().subTarget());
     this.entityManagerFactory = createContainerEntityManagerFactory();
   } finally {
     pu.setTempClassLoaderFactory(
         null); // release the temp classloader factory (only needed when creating the EMF)
     WritableServiceBasedNamingStore.popOwner();
   }
 }
 @Override
 public void stop(StopContext context) {
   JPA_LOGGER.stoppingService("Persistence Unit", pu.getScopedPersistenceUnitName());
   if (entityManagerFactory != null) {
     entityManagerFactory.close();
     entityManagerFactory = null;
   }
 }
 /**
  * Create EE container entity manager factory
  *
  * @return EntityManagerFactory
  */
 private EntityManagerFactory createContainerEntityManagerFactory() {
   persistenceProviderAdaptor.beforeCreateContainerEntityManagerFactory(pu);
   try {
     return persistenceProvider.createContainerEntityManagerFactory(pu, properties.getValue());
   } finally {
     try {
       persistenceProviderAdaptor.afterCreateContainerEntityManagerFactory(pu);
     } finally {
       pu.setAnnotationIndex(
           null); // close reference to Annotation Index (only needed during call to
                  // createContainerEntityManagerFactory)
       pu.setTempClassLoaderFactory(
           null); // close reference to temp classloader factory (only needed during call to
                  // createEntityManagerFactory)
     }
   }
 }
예제 #9
0
 private InjectionSource getPersistenceContextBindingSource(
     final DeploymentUnit deploymentUnit,
     final String unitName,
     PersistenceContextType type,
     Map properties)
     throws DeploymentUnitProcessingException {
   PersistenceUnitMetadata pu = getPersistenceUnit(deploymentUnit, unitName);
   String scopedPuName = pu.getScopedPersistenceUnitName();
   ServiceName puServiceName = getPuServiceName(scopedPuName);
   return new PersistenceContextInjectionSource(
       type,
       properties,
       puServiceName,
       deploymentUnit,
       scopedPuName,
       EntityManager.class.getName(),
       pu);
 }
  private InjectionSource getBindingSource(
      final DeploymentUnit deploymentUnit,
      final AnnotationInstance annotation,
      String injectionTypeName,
      final EEModuleClassDescription classDescription)
      throws DeploymentUnitProcessingException {
    PersistenceUnitMetadata pu = getPersistenceUnit(deploymentUnit, annotation, classDescription);
    if (pu == null) {
      return null;
    }
    String scopedPuName = pu.getScopedPersistenceUnitName();
    ServiceName puServiceName = getPuServiceName(scopedPuName);
    if (isPersistenceContext(annotation)) {
      if (pu.getTransactionType() == PersistenceUnitTransactionType.RESOURCE_LOCAL) {
        classDescription.setInvalid(MESSAGES.cannotInjectResourceLocalEntityManager());
        return null;
      }
      AnnotationValue pcType = annotation.value("type");
      PersistenceContextType type =
          (pcType == null || PersistenceContextType.TRANSACTION.name().equals(pcType.asString()))
              ? PersistenceContextType.TRANSACTION
              : PersistenceContextType.EXTENDED;

      Map properties;
      AnnotationValue value = annotation.value("properties");
      AnnotationInstance[] props = value != null ? value.asNestedArray() : null;
      if (props != null) {
        properties = new HashMap();
        for (int source = 0; source < props.length; source++) {
          properties.put(props[source].value("name"), props[source].value("value"));
        }
      } else {
        properties = null;
      }

      return new PersistenceContextInjectionSource(
          type, properties, puServiceName, deploymentUnit, scopedPuName, injectionTypeName, pu);
    } else {
      return new PersistenceUnitInjectionSource(
          puServiceName, deploymentUnit, injectionTypeName, pu);
    }
  }
 @Override
 public void addProviderDependencies(
     ServiceRegistry registry,
     ServiceTarget target,
     ServiceBuilder<?> builder,
     PersistenceUnitMetadata pu) {
   Properties properties = pu.getProperties();
   if (Boolean.parseBoolean(properties.getProperty(AvailableSettings.USE_SECOND_LEVEL_CACHE))) {
     HibernateSecondLevelCache.addSecondLevelCacheDependencies(registry, target, builder, pu);
   }
 }
    @Override
    public ManagedReference getReference() {
      PersistenceUnitService service =
          (PersistenceUnitService)
              deploymentUnit.getServiceRegistry().getRequiredService(puServiceName).getValue();
      EntityManagerFactory emf = service.getEntityManagerFactory();

      if (!ENTITY_MANAGER_FACTORY_CLASS.equals(
          injectionTypeName)) { // inject non-standard wrapped class (e.g.
                                // org.hibernate.SessionFactory)
        Class extensionClass;
        try {
          // make sure we can access the target class type
          extensionClass = pu.getClassLoader().loadClass(injectionTypeName);
        } catch (ClassNotFoundException e) {
          throw new RuntimeException(
              "couldn't load " + injectionTypeName + " from JPA modules classloader", e);
        }
        // TODO:  when/if jpa supports unwrap, change to
        //   Object targetValueToInject = emf.unwrap(extensionClass);
        // Until jpa supports unwrap on sessionfactory, only support hibernate

        Method getSessionFactory;
        try {
          getSessionFactory = emf.getClass().getMethod("getSessionFactory");
        } catch (NoSuchMethodException e) {
          throw new RuntimeException(
              "Can only inject from a Hibernate EntityManagerFactoryImpl", e);
        }

        Object targetValueToInject = null;
        try {
          targetValueToInject = getSessionFactory.invoke(emf, new Object[0]);
        } catch (IllegalAccessException e) {
          throw new RuntimeException(
              "Couldn't get Hibernate session factory from entity manager", e);
        } catch (InvocationTargetException e) {
          throw new RuntimeException(
              "Couldn't get Hibernate session factory from entity manager", e);
        }
        return new ValueManagedReference(new ImmediateValue<Object>(targetValueToInject));
      }

      return new ValueManagedReference(new ImmediateValue<Object>(emf));
    }
 private void putPropertyIfAbsent(
     PersistenceUnitMetadata pu, Map properties, String property, Object value) {
   if (!pu.getProperties().containsKey(property)) {
     properties.put(property, value);
   }
 }
  public static PersistenceUnitMetadataHolder parse(final XMLStreamReader reader)
      throws XMLStreamException {

    reader.require(START_DOCUMENT, null, null); // check for a bogus document and throw error

    // Read until the first start element
    Version version = null;
    while (reader.hasNext() && reader.next() != START_ELEMENT) {
      if (reader.getEventType() == DTD) {
        final String dtdLocation = readDTDLocation(reader);
        if (dtdLocation != null) {
          version = Version.forLocation(dtdLocation);
        }
      }
    }
    final String schemaLocation = readSchemaLocation(reader);
    if (schemaLocation != null) {
      version = Version.forLocation(schemaLocation);
    }
    if (version == null || Version.UNKNOWN.equals(version)) {
      // Look at the version attribute
      String versionString = null;
      final int count = reader.getAttributeCount();
      for (int i = 0; i < count; i++) {
        final String attributeNamespace = reader.getAttributeNamespace(i);
        if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
          continue;
        }
        final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
        if (attribute == Attribute.VERSION) {
          versionString = reader.getAttributeValue(i);
        }
      }
      if ("1.0".equals(versionString)) {
        version = Version.JPA_1_0;
      } else if ("1".equals(versionString)) {
        version = Version.JPA_1_0;
      } else if ("2.0".equals(versionString)) {
        version = Version.JPA_2_0;
      } else if ("2".equals(versionString)) {
        version = Version.JPA_2_0;
      } else {
        version = Version.JPA_2_0;
      }
    }

    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      final String attributeNamespace = reader.getAttributeNamespace(i);
      if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case VERSION:
          // log.info("version = " + value);
          // TODO:  handle version
          break;
        default:
          throw unexpectedAttribute(reader, i);
      }
    }
    final List<PersistenceUnitMetadata> PUs = new ArrayList<PersistenceUnitMetadata>();
    // until the ending PERSISTENCE tag
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      final Element element = Element.forName(reader.getLocalName());
      switch (element) {
        case PERSISTENCEUNIT:
          PersistenceUnitMetadata pu = parsePU(reader, version);
          PUs.add(pu);
          JPA_LOGGER.readingPersistenceXml(pu.getPersistenceUnitName());
          break;

        default:
          throw unexpectedElement(reader);
      }
    }
    PersistenceUnitMetadataHolder result =
        new PersistenceUnitMetadataHolder().setPersistenceUnits(PUs);
    if (JPA_LOGGER.isTraceEnabled()) JPA_LOGGER.trace(result.toString());

    return result;
  }
 /**
  * Returns the Persistence Unit service name used for creation or lookup. The service name
  * contains the unique fully scoped persistence unit name
  *
  * @param pu persistence unit definition
  * @return
  */
 public static ServiceName getPUServiceName(PersistenceUnitMetadata pu) {
   return JPAServiceNames.getPUServiceName(pu.getScopedPersistenceUnitName());
 }
 @Override
 public String getScopedPersistenceUnitName() {
   return pu.getScopedPersistenceUnitName();
 }
  /**
   * Parse the persistence unit definitions based on persistence_2_0.xsd.
   *
   * @param reader
   * @return
   * @throws XMLStreamException
   */
  private static PersistenceUnitMetadata parsePU(XMLStreamReader reader, Version version)
      throws XMLStreamException {
    PersistenceUnitMetadata pu = new PersistenceUnitMetadataImpl();
    List<String> classes = new ArrayList<String>(1);
    List<String> jarfiles = new ArrayList<String>(1);
    List<String> mappingFiles = new ArrayList<String>(1);
    Properties properties = new Properties();

    // set defaults
    pu.setTransactionType(PersistenceUnitTransactionType.JTA);
    pu.setValidationMode(ValidationMode.AUTO);
    pu.setSharedCacheMode(SharedCacheMode.UNSPECIFIED);
    pu.setPersistenceProviderClassName(
        "org.hibernate.ejb.HibernatePersistence"); // TODO: move to domain.xml?
    if (version.equals(Version.JPA_1_0)) {
      pu.setPersistenceXMLSchemaVersion("1.0");
    } else {
      pu.setPersistenceXMLSchemaVersion("2.0");
    }

    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
      final String value = reader.getAttributeValue(i);
      if (traceEnabled) {
        JPA_LOGGER.tracef("parse persistence.xml: attribute value(%d) = %s", i, value);
      }
      final String attributeNamespace = reader.getAttributeNamespace(i);
      if (attributeNamespace != null && !attributeNamespace.isEmpty()) {
        continue;
      }
      final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case NAME:
          pu.setPersistenceUnitName(value);
          break;
        case TRANSACTIONTYPE:
          if (value.equalsIgnoreCase("RESOURCE_LOCAL"))
            pu.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
          break;
        default:
          throw unexpectedAttribute(reader, i);
      }
    }

    // until the ending PERSISTENCEUNIT tag
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
      final Element element = Element.forName(reader.getLocalName());
      if (traceEnabled) {
        JPA_LOGGER.tracef("parse persistence.xml: element=%s", element.getLocalName());
      }
      switch (element) {
        case CLASS:
          classes.add(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case DESCRIPTION:
          final String description = Util.resolveSystemProperty(reader.getElementText());
          break;

        case EXCLUDEUNLISTEDCLASSES:
          String text = Util.resolveSystemProperty(reader.getElementText());
          if (text == null || text.isEmpty()) {
            // the spec has examples where an empty
            // exclude-unlisted-classes element has the same
            // effect as setting it to true
            pu.setExcludeUnlistedClasses(true);
          } else {
            pu.setExcludeUnlistedClasses(Boolean.valueOf(text));
          }
          break;

        case JARFILE:
          String file = Util.resolveSystemProperty(reader.getElementText());
          jarfiles.add(file);
          break;

        case JTADATASOURCE:
          pu.setJtaDataSourceName(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case NONJTADATASOURCE:
          pu.setNonJtaDataSourceName(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case MAPPINGFILE:
          mappingFiles.add(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case PROPERTIES:
          parseProperties(reader, properties);
          break;

        case PROVIDER:
          pu.setPersistenceProviderClassName(Util.resolveSystemProperty(reader.getElementText()));
          break;

        case SHAREDCACHEMODE:
          String cm = Util.resolveSystemProperty(reader.getElementText());
          pu.setSharedCacheMode(SharedCacheMode.valueOf(cm));
          break;

        case VALIDATIONMODE:
          String validationMode = Util.resolveSystemProperty(reader.getElementText());
          pu.setValidationMode(ValidationMode.valueOf(validationMode));
          break;

        default:
          throw unexpectedElement(reader);
      }
    }
    if (traceEnabled) {
      JPA_LOGGER.trace("parse persistence.xml: reached ending persistence-unit tag");
    }
    pu.setManagedClassNames(classes);
    pu.setJarFiles(jarfiles);
    pu.setMappingFiles(mappingFiles);
    pu.setProperties(properties);
    return pu;
  }