Java 类javax.persistence.PersistenceUnit 实例源码

项目:marathonv5    文件:DataAppLoader.java   
/**
 * @param args the command line arguments
 */
@PersistenceUnit
public static void main(String[] args) {
    System.out.println("Creating entity information...");
    EntityManager entityManager = Persistence.createEntityManagerFactory("DataAppLibraryPULocal").createEntityManager();
    EntityTransaction et = entityManager.getTransaction();
    et.begin();
    loadDiscountRate(entityManager);
    loadRegion(entityManager);
    loadRole(entityManager);
    loadTransmission(entityManager);
    loadProductType(entityManager);
    loadEngine(entityManager);
    loadProduct(entityManager);
    et.commit();


    EntityManager specialEntityManager = new InitialLoadEntityManagerProxy(entityManager);
    SalesSimulator simulator = new SalesSimulator(specialEntityManager);
    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    cal.clear();
    cal.set(year-1, 0, 1, 0, 0, 0); // go back to begining of year, 3 years ago
    System.out.println("Creating historical data...");
    System.out.println("        This may take 5 to 15min depending on machine speed.");
    simulator.run(cal.getTime(), new Date());

    entityManager.close();
}
项目:aries-jpa    文件:PersistenceAnnotatedType.java   
private <X> AnnotatedField<X> decorateUnit(AnnotatedField<X> field) {
    final PersistenceUnit persistenceUnit = field.getAnnotation(PersistenceUnit.class);
    final UniqueIdentifier identifier = UniqueIdentifierLitteral.random();

    Set<Annotation> templateQualifiers = new HashSet<>();
    templateQualifiers.add(ServiceLiteral.SERVICE);
    if (hasUnitName(persistenceUnit)) {
        templateQualifiers.add(new FilterLiteral("(osgi.unit.name=" + persistenceUnit.unitName() + ")"));
    }
    Bean<EntityManagerFactory> bean = manager.getExtension(OsgiExtension.class)
            .globalDependency(EntityManagerFactory.class, templateQualifiers);

    Set<Annotation> qualifiers = new HashSet<>();
    qualifiers.add(identifier);
    Bean<EntityManagerFactory> b = new SimpleBean<>(EntityManagerFactory.class, Dependent.class, Collections.singleton(EntityManagerFactory.class), qualifiers, () -> {
        CreationalContext<EntityManagerFactory> context = manager.createCreationalContext(bean);
        return (EntityManagerFactory) manager.getReference(bean, EntityManagerFactory.class, context);
    });
    beans.add(b);

    Set<Annotation> fieldAnnotations = new HashSet<>();
    fieldAnnotations.add(InjectLiteral.INJECT);
    fieldAnnotations.add(identifier);
    return new SyntheticAnnotatedField<>(field, fieldAnnotations);
}
项目:jspare-container    文件:PersistenceUnitInjectStrategy.java   
@Override
public void inject(Object result, Field field) {
  try {

    String unitName = field.getAnnotation(PersistenceUnit.class).unitName();
    if (StringUtils.isEmpty(unitName))
      unitName = PersistenceUnitProvider.DEFAULT_DS;

    if(!field.getType().equals(EntityManagerFactory.class)){

      log.error("Failed to create PersistenceUnit, type of field is not a EntityManagerFactory");
      return;
    }

    EntityManagerFactory emf = provider.getProvider();

    field.setAccessible(true);
    field.set(result, emf);
  } catch (Exception e) {

    log.error("Failed to create PersistenceUnit", e);
  }
}
项目:tomee    文件:LocalClientTest.java   
public void setUp() throws OpenEJBException, NamingException, IOException {
    //avoid linkage error on mac, only used for tests so don't need to add it in Core
    JULLoggerFactory.class.getName();

    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();

    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));

    final AppModule app = new AppModule(this.getClass().getClassLoader(), "test-app");

    final Persistence persistence = new Persistence(new org.apache.openejb.jee.jpa.unit.PersistenceUnit("foo-unit"));
    app.addPersistenceModule(new PersistenceModule("root", persistence));

    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new StatelessBean(SuperBean.class));
    app.getEjbModules().add(new EjbModule(ejbJar));

    final ClientModule clientModule = new ClientModule(null, app.getClassLoader(), app.getJarLocation(), null, null);
    clientModule.getLocalClients().add(this.getClass().getName());

    app.getClientModules().add(clientModule);

    assembler.createApplication(config.configureApplication(app));
}
项目:lightmare    文件:BeanDeployer.java   
/**
 * Retrieves and caches {@link Field}s with injection
 *
 * @param field
 * @throws IOException
 */
private void retriveConnection(Field field) throws IOException {

    PersistenceContext context = field.getAnnotation(PersistenceContext.class);
    Resource resource = field.getAnnotation(Resource.class);
    PersistenceUnit unit = field.getAnnotation(PersistenceUnit.class);
    EJB ejbAnnot = field.getAnnotation(EJB.class);
    if (ObjectUtils.notNull(context)) {
        identifyConnections(context, field);
        addAccessibleField(field);
    } else if (ObjectUtils.notNull(resource)) {
        metaData.setTransactionField(field);
        addAccessibleField(field);
    } else if (ObjectUtils.notNull(unit)) {
        addUnitField(field);
        addAccessibleField(field);
    } else if (ObjectUtils.notNull(ejbAnnot)) {
        // caches EJB annotated fields
        cacheInjectFields(field);
        addAccessibleField(field);
    }
}
项目:marathonv5    文件:DataAppLoader.java   
/**
 * @param args the command line arguments
 */
@PersistenceUnit
public static void main(String[] args) {
    System.out.println("Creating entity information...");
    EntityManager entityManager = Persistence.createEntityManagerFactory("DataAppLibraryPULocal").createEntityManager();
    EntityTransaction et = entityManager.getTransaction();
    et.begin();
    loadDiscountRate(entityManager);
    loadRegion(entityManager);
    loadRole(entityManager);
    loadTransmission(entityManager);
    loadProductType(entityManager);
    loadEngine(entityManager);
    loadProduct(entityManager);
    et.commit();


    EntityManager specialEntityManager = new InitialLoadEntityManagerProxy(entityManager);
    SalesSimulator simulator = new SalesSimulator(specialEntityManager);
    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    cal.clear();
    cal.set(year-1, 0, 1, 0, 0, 0); // go back to begining of year, 3 years ago
    System.out.println("Creating historical data...");
    System.out.println("        This may take 5 to 15min depending on machine speed.");
    simulator.run(cal.getTime(), new Date());

    entityManager.close();
}
项目:aries-jpa    文件:AnnotationScannerTest.java   
@Test
public void getPUAnnotatedMembersTest() {
    AnnotationScanner scanner = new AnnotationScanner();
    List<AccessibleObject> members = scanner.getJpaAnnotatedMembers(TestClass.class, PersistenceUnit.class);
    Assert.assertEquals(1, members.size());
    AccessibleObject member = members.get(0);
    Assert.assertEquals(Method.class, member.getClass());
    Method method = (Method)member;
    Assert.assertEquals("setEmf", method.getName());
}
项目:aries-jpa    文件:AnnotationScannerTest.java   
/**
 * When using a factory the class can be an interface. We need to make sure this does not cause a NPE
 */
@Test
public void getFactoryTest() {
    AnnotationScanner scanner = new AnnotationScanner();
    List<AccessibleObject> members = scanner.getJpaAnnotatedMembers(TestInterface.class, PersistenceUnit.class);
    Assert.assertEquals(0, members.size());
}
项目:aries-jpa    文件:JpaExtension.java   
public <T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> event, BeanManager manager) {
    boolean hasPersistenceField = false;
    for (AnnotatedField<? super T> field : event.getAnnotatedType().getFields()) {
        if (field.isAnnotationPresent(PersistenceContext.class)
                || field.isAnnotationPresent(PersistenceUnit.class)) {
            hasPersistenceField = true;
            break;
        }
    }
    if (hasPersistenceField) {
        PersistenceAnnotatedType<T> pat = new PersistenceAnnotatedType<T>(manager, event.getAnnotatedType());
        beans.addAll(pat.getProducers());
        event.setAnnotatedType(pat);
    }
}
项目:aries-jpa    文件:PersistenceAnnotatedType.java   
public PersistenceAnnotatedType(BeanManager manager, AnnotatedType<T> delegate) {
    super(delegate);
    this.manager = manager;
    this.fields = new HashSet<>();
    for (AnnotatedField<? super T> field : delegate.getFields()) {
        if (field.isAnnotationPresent(PersistenceContext.class)) {
            field = decorateContext(field);
        } else if (field.isAnnotationPresent(PersistenceUnit.class)) {
            field = decorateUnit(field);
        }
        this.fields.add(field);
    }
}
项目:spring4-understanding    文件:PersistenceAnnotationBeanPostProcessor.java   
public PersistenceElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) {
    super(member, pd);
    PersistenceContext pc = ae.getAnnotation(PersistenceContext.class);
    PersistenceUnit pu = ae.getAnnotation(PersistenceUnit.class);
    Class<?> resourceType = EntityManager.class;
    if (pc != null) {
        if (pu != null) {
            throw new IllegalStateException("Member may only be annotated with either " +
                    "@PersistenceContext or @PersistenceUnit, not both: " + member);
        }
        Properties properties = null;
        PersistenceProperty[] pps = pc.properties();
        if (!ObjectUtils.isEmpty(pps)) {
            properties = new Properties();
            for (PersistenceProperty pp : pps) {
                properties.setProperty(pp.name(), pp.value());
            }
        }
        this.unitName = pc.unitName();
        this.type = pc.type();
        this.synchronizedWithTransaction = (synchronizationAttribute == null ||
                "SYNCHRONIZED".equals(ReflectionUtils.invokeMethod(synchronizationAttribute, pc).toString()));
        this.properties = properties;
    }
    else {
        resourceType = EntityManagerFactory.class;
        this.unitName = pu.unitName();
    }
    checkResourceType(resourceType);
}
项目:spring4-understanding    文件:PersistenceInjectionTests.java   
@PersistenceUnit
public void setEmf(EntityManagerFactory emf) {
    if (this.emf != null) {
        throw new IllegalStateException("Already called");
    }
    this.emf = emf;
}
项目:unitils    文件:JpaModule.java   
/**
 * Injects the JPA <code>EntityManagerFactory</code> into all fields and methods that are
 * annotated with <code>javax.persistence.PersistenceUnit</code>
 *
 * @param testObject The test object, not null
 */
public void injectEntityManagerFactory(Object testObject, Object target) {
    Set<Field> fields = getFieldsAnnotatedWith(target.getClass(), PersistenceUnit.class);
    Set<Method> methods = getMethodsAnnotatedWith(target.getClass(), PersistenceUnit.class);
    if (fields.isEmpty() && methods.isEmpty()) {
        // Jump out to make sure that we don't try to instantiate the EntityManagerFactory
        return;
    }

    EntityManagerFactory entityManagerFactory = getPersistenceUnit(testObject);
    setFieldAndSetterValue(target, fields, methods, entityManagerFactory);
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@Test
public void testClassWithMultiplePersistenceUnitFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf1");
    emf1Field.annotate(PersistenceUnit.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf2");
    emf2Field.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("Only single field is allowed"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@Test
public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    emf1Field.annotate(PersistenceContext.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emf2Field.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("either @PersistenceUnit or @PersistenceContext"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@Test
public void testClassWithPersistenceUnitFieldOfWrongType() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "emf");
    emField.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("annotated with @PersistenceUnit is not of type EntityManagerFactory"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@Test
public void testClassWithPersistenceUnitWithoutUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emField.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("JpaUnitException expected");
    } catch (final JpaUnitException e) {

        // THEN
        assertThat(e.getMessage(), containsString("No Persistence"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@Test
public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
    final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut);

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
    verify(listener).testStarted(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));

    verify(listener).testFinished(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
项目:jpa-unit    文件:JpaUnitRunnerTest.java   
@Test
public void testClassWithMultiplePersistenceUnitFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf1");
    emf1Field.annotate(PersistenceUnit.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf2");
    emf2Field.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("Only single field is allowed"));
}
项目:jpa-unit    文件:JpaUnitRunnerTest.java   
@Test
public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    emf1Field.annotate(PersistenceContext.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emf2Field.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("either @PersistenceUnit or @PersistenceContext"));
}
项目:jpa-unit    文件:JpaUnitRunnerTest.java   
@Test
public void testClassWithPersistenceUnitFieldOfWrongType() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "emf");
    emField.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(),
            containsString("annotated with @PersistenceUnit is not of type EntityManagerFactory"));
}
项目:jpa-unit    文件:JpaUnitRunnerTest.java   
@Test
public void testClassWithPersistenceUnitWithoutUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emField.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(JpaUnitException.class));
    assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
项目:jpa-unit    文件:JpaUnitRunnerTest.java   
@Test
public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
    verify(listener).testStarted(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));

    verify(listener).testFinished(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
项目:jpa-unit    文件:JpaUnitRunnerTest.java   
@Test
public void testJpaUnitRunnerAndJpaUnitRuleFieldExcludeEachOther() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRunner(cut);
        fail("InitializationError expected");
    } catch (final InitializationError e) {
        // expected
        assertThat(e.getCauses().get(0).getMessage(), containsString("exclude each other"));
    }

}
项目:jpa-unit    文件:MetadataExtractorTest.java   
@Test
public void testPersistenceUnit() {

    // WHEN
    final AnnotationInspector<PersistenceUnit> ai = metadataExtractor.persistenceUnit();

    // THEN
    assertThat(ai, notNullValue());
}
项目:Tank    文件:EntityManagerProducer.java   
@Produces
@ConversationScoped
@PersistenceUnit
@Default
public EntityManagerFactory getEntityManagerFactory() {
    return emf;
}
项目:class-guard    文件:PersistenceAnnotationBeanPostProcessor.java   
public PersistenceElement(Member member, PropertyDescriptor pd) {
    super(member, pd);
    AnnotatedElement ae = (AnnotatedElement) member;
    PersistenceContext pc = ae.getAnnotation(PersistenceContext.class);
    PersistenceUnit pu = ae.getAnnotation(PersistenceUnit.class);
    Class<?> resourceType = EntityManager.class;
    if (pc != null) {
        if (pu != null) {
            throw new IllegalStateException("Member may only be annotated with either " +
                    "@PersistenceContext or @PersistenceUnit, not both: " + member);
        }
        Properties properties = null;
        PersistenceProperty[] pps = pc.properties();
        if (!ObjectUtils.isEmpty(pps)) {
            properties = new Properties();
            for (PersistenceProperty pp : pps) {
                properties.setProperty(pp.name(), pp.value());
            }
        }
        this.unitName = pc.unitName();
        this.type = pc.type();
        this.properties = properties;
    }
    else {
        resourceType = EntityManagerFactory.class;
        this.unitName = pu.unitName();
    }
    checkResourceType(resourceType);
}
项目:class-guard    文件:PersistenceInjectionTests.java   
@PersistenceUnit
public void setEmf(EntityManagerFactory emf) {
    if (this.emf != null) {
        throw new IllegalStateException("Already called");
    }
    this.emf = emf;
}
项目:spearal-jpa2    文件:SpearalExtension.java   
private void handleAnnotatedMember(AnnotatedMember<?> member) {
    if (member.isAnnotationPresent(PersistenceContext.class)) {
        PersistenceContext persistenceContext = member.getAnnotation(PersistenceContext.class);
        injectedPersistenceContexts.put(persistenceContext.unitName(), member);
    }
    if (member.isAnnotationPresent(PersistenceUnit.class)) {
        PersistenceUnit persistenceUnit = member.getAnnotation(PersistenceUnit.class);
        injectedPersistenceUnits.add(persistenceUnit.unitName());
    }
}
项目:spearal-jpa2    文件:SpearalExtension.java   
public void produceMissingPersistenceUnits(@Observes AfterTypeDiscovery event, BeanManager beanManager) {
    for (String unitName : injectedPersistenceUnits)
        injectedPersistenceContexts.remove(unitName);

    for (AnnotatedMember<?> member : injectedPersistenceContexts.values()) {

        if (!member.isAnnotationPresent(SpearalEnabled.class))
            continue;

        PersistenceContext persistenceContext = member.getAnnotation(PersistenceContext.class);

        try {
            final Set<Annotation> annotations = new HashSet<Annotation>(member.getAnnotations());
            Iterator<Annotation> ia = annotations.iterator();
            while (ia.hasNext()) {
                Annotation a = ia.next();
                if (a.annotationType().equals(PersistenceContext.class))
                    ia.remove();
            }
            PersistenceUnit persistenceUnit = new PersistenceUnitAnnotation(persistenceContext.name(), persistenceContext.unitName());

            annotations.add(persistenceUnit);

            final AnnotatedType<PersistenceUnitProducer> annotatedPU = new AnnotatedPersistenceUnitProducerType(annotations);

            event.addAnnotatedType(annotatedPU, "org.spearal.jpa2.PersistenceUnit." + persistenceContext.unitName());
        }
        catch (Exception e) {
            log.logp(Level.WARNING, SpearalExtension.class.getName(), "afterTypeDiscovery", "Could not setup PersistenceUnit integration {0}", new Object[] { persistenceContext.unitName() });
        }
    }
}
项目:hammock    文件:BasicJpaInjectionServices.java   
@Override
public ResourceReferenceFactory<EntityManagerFactory> registerPersistenceUnitInjectionPoint(InjectionPoint ip) {
    PersistenceUnit pc = ip.getAnnotated().getAnnotation(PersistenceUnit.class);
    if (pc == null) {
        throw new IllegalArgumentException("No @PersistenceUnit annotation found on EntityManagerFactory");
    }
    String name = pc.unitName();
    LOG.info("Creating EntityManagerFactoryReferenceFactory for unit " + name);
    return new EntityManagerFactoryReferenceFactory(name);
}
项目:tomee    文件:AnnotationDeployer.java   
public static void autoJpa(final EjbModule ejbModule) {
    final IAnnotationFinder finder = ejbModule.getFinder();
    if (ejbModule.getAppModule() != null) {
        for (final PersistenceModule pm : ejbModule.getAppModule().getPersistenceModules()) {
            for (final org.apache.openejb.jee.jpa.unit.PersistenceUnit pu : pm.getPersistence().getPersistenceUnit()) {
                if ((pu.isExcludeUnlistedClasses() == null || !pu.isExcludeUnlistedClasses())
                    && "true".equalsIgnoreCase(pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN))) {
                    doAutoJpa(finder, pu);
                }
            }
        }
    }
}
项目:tomee    文件:AnnotationDeployer.java   
public static void doAutoJpa(final IAnnotationFinder finder, final org.apache.openejb.jee.jpa.unit.PersistenceUnit pu) {
    final String packageName = pu.getProperties().getProperty(OPENEJB_JPA_AUTO_SCAN_PACKAGE);
    String[] packageNames = null;
    if (packageName != null) {
        packageNames = packageName.split(",");
    }

    // no need of meta currently since JPA providers doesn't support it
    final List<Class<?>> classes = new ArrayList<Class<?>>();
    classes.addAll(finder.findAnnotatedClasses(Entity.class));
    classes.addAll(finder.findAnnotatedClasses(Embeddable.class));
    classes.addAll(finder.findAnnotatedClasses(MappedSuperclass.class));
    classes.addAll(finder.findAnnotatedClasses(Converter.class));
    final List<String> existingClasses = pu.getClazz();
    for (final Class<?> clazz : classes) {
        final String name = clazz.getName();
        if (existingClasses.contains(name)) {
            continue;
        }

        if (packageNames == null) {
            pu.getClazz().add(name);
        } else {
            for (final String pack : packageNames) {
                if (name.startsWith(pack)) {
                    pu.getClazz().add(name);
                }
            }
        }
    }
    pu.setScanned(true);
}
项目:lightmare    文件:MetaData.java   
/**
 * Adds {@link javax.persistence.PersistenceUnit} annotated field to
 * {@link MetaData} for cache
 *
 * @param unitFields
 */
public void addUnitFields(Collection<Field> unitFields) {

    if (CollectionUtils.validAll(connections, unitFields)) {
        String unitName;
        for (Field unitField : unitFields) {
            unitName = unitField.getAnnotation(PersistenceUnit.class).unitName();
            addUnitField(unitName, unitField);
        }
        // Caches connection EJB bean fields meta data
        this.unitFields = unitFields;
    }
}
项目:aries-jpa    文件:TestClass.java   
@PersistenceUnit(unitName="test2")
public void setEmf(EntityManagerFactory emf) {
    this.emf = emf;
}
项目:aries-jpa    文件:PersistenceAnnotatedType.java   
private boolean hasUnitName(PersistenceUnit pu) {
    return !pu.unitName().isEmpty();
}
项目:spring4-understanding    文件:PersistenceAnnotationBeanPostProcessor.java   
private InjectionMetadata buildPersistenceMetadata(final Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {
        final LinkedList<InjectionMetadata.InjectedElement> currElements =
                new LinkedList<InjectionMetadata.InjectedElement>();

        ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (field.isAnnotationPresent(PersistenceContext.class) ||
                        field.isAnnotationPresent(PersistenceUnit.class)) {
                    if (Modifier.isStatic(field.getModifiers())) {
                        throw new IllegalStateException("Persistence annotations are not supported on static fields");
                    }
                    currElements.add(new PersistenceElement(field, field, null));
                }
            }
        });

        ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
                if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                    return;
                }
                if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) ||
                        bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) &&
                        method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException("Persistence annotations are not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException("Persistence annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new PersistenceElement(method, bridgedMethod, pd));
                }
            }
        });

        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    }
    while (targetClass != null && targetClass != Object.class);

    return new InjectionMetadata(clazz, elements);
}
项目:spring4-understanding    文件:PersistenceInjectionTests.java   
@PersistenceUnit(unitName = "Person")
public void setEmf(EntityManagerFactory emf) {
    this.emf = emf;
}
项目:spring4-understanding    文件:PersistenceInjectionTests.java   
@PersistenceUnit
@SuppressWarnings("rawtypes")
public void setSomething(Comparable c) {
}
项目:spring4-understanding    文件:PersistenceInjectionTests.java   
@PersistenceUnit
public void setSomething() {
}