Rename modules {org.springframework.*=>spring-*}
This renaming more intuitively expresses the relationship between
subprojects and the JAR artifacts they produce.
Tracking history across these renames is possible, but it requires
use of the --follow flag to `git log`, for example
$ git log spring-aop/src/main/java/org/springframework/aop/Advisor.java
will show history up until the renaming event, where
$ git log --follow spring-aop/src/main/java/org/springframework/aop/Advisor.java
will show history for all changes to the file, before and after the
renaming.
See http://chrisbeams.com/git-diff-across-renamed-directories
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import org.springframework.core.enums.ShortCodedLabeledEnum;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
*/
|
||||
public class Colour extends ShortCodedLabeledEnum {
|
||||
|
||||
public static final Colour RED = new Colour(0, "RED");
|
||||
public static final Colour BLUE = new Colour(1, "BLUE");
|
||||
public static final Colour GREEN = new Colour(2, "GREEN");
|
||||
public static final Colour PURPLE = new Colour(3, "PURPLE");
|
||||
|
||||
private Colour(int code, String label) {
|
||||
super(code, label);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
public interface INestedTestBean {
|
||||
|
||||
public String getCompany();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
public interface IOther {
|
||||
|
||||
void absquatulate();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Interface used for {@link org.springframework.beans.TestBean}.
|
||||
*
|
||||
* <p>Two methods are the same as on Person, but if this
|
||||
* extends person it breaks quite a few tests..
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public interface ITestBean {
|
||||
|
||||
int getAge();
|
||||
|
||||
void setAge(int age);
|
||||
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
ITestBean getSpouse();
|
||||
|
||||
void setSpouse(ITestBean spouse);
|
||||
|
||||
ITestBean[] getSpouses();
|
||||
|
||||
String[] getStringArray();
|
||||
|
||||
void setStringArray(String[] stringArray);
|
||||
|
||||
/**
|
||||
* Throws a given (non-null) exception.
|
||||
*/
|
||||
void exceptional(Throwable t) throws Throwable;
|
||||
|
||||
Object returnsThis();
|
||||
|
||||
INestedTestBean getDoctor();
|
||||
|
||||
INestedTestBean getLawyer();
|
||||
|
||||
IndexedTestBean getNestedIndexedBean();
|
||||
|
||||
/**
|
||||
* Increment the age by one.
|
||||
* @return the previous age
|
||||
*/
|
||||
int haveBirthday();
|
||||
|
||||
void unreliableFileOperation() throws IOException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.SortedMap;
|
||||
import java.util.SortedSet;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 11.11.2003
|
||||
*/
|
||||
public class IndexedTestBean {
|
||||
|
||||
private TestBean[] array;
|
||||
|
||||
private Collection collection;
|
||||
|
||||
private List list;
|
||||
|
||||
private Set set;
|
||||
|
||||
private SortedSet sortedSet;
|
||||
|
||||
private Map map;
|
||||
|
||||
private SortedMap sortedMap;
|
||||
|
||||
|
||||
public IndexedTestBean() {
|
||||
this(true);
|
||||
}
|
||||
|
||||
public IndexedTestBean(boolean populate) {
|
||||
if (populate) {
|
||||
populate();
|
||||
}
|
||||
}
|
||||
|
||||
public void populate() {
|
||||
TestBean tb0 = new TestBean("name0", 0);
|
||||
TestBean tb1 = new TestBean("name1", 0);
|
||||
TestBean tb2 = new TestBean("name2", 0);
|
||||
TestBean tb3 = new TestBean("name3", 0);
|
||||
TestBean tb4 = new TestBean("name4", 0);
|
||||
TestBean tb5 = new TestBean("name5", 0);
|
||||
TestBean tb6 = new TestBean("name6", 0);
|
||||
TestBean tb7 = new TestBean("name7", 0);
|
||||
TestBean tbX = new TestBean("nameX", 0);
|
||||
TestBean tbY = new TestBean("nameY", 0);
|
||||
this.array = new TestBean[] {tb0, tb1};
|
||||
this.list = new ArrayList();
|
||||
this.list.add(tb2);
|
||||
this.list.add(tb3);
|
||||
this.set = new TreeSet();
|
||||
this.set.add(tb6);
|
||||
this.set.add(tb7);
|
||||
this.map = new HashMap();
|
||||
this.map.put("key1", tb4);
|
||||
this.map.put("key2", tb5);
|
||||
this.map.put("key.3", tb5);
|
||||
List list = new ArrayList();
|
||||
list.add(tbX);
|
||||
list.add(tbY);
|
||||
this.map.put("key4", list);
|
||||
}
|
||||
|
||||
|
||||
public TestBean[] getArray() {
|
||||
return array;
|
||||
}
|
||||
|
||||
public void setArray(TestBean[] array) {
|
||||
this.array = array;
|
||||
}
|
||||
|
||||
public Collection getCollection() {
|
||||
return collection;
|
||||
}
|
||||
|
||||
public void setCollection(Collection collection) {
|
||||
this.collection = collection;
|
||||
}
|
||||
|
||||
public List getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public Set getSet() {
|
||||
return set;
|
||||
}
|
||||
|
||||
public void setSet(Set set) {
|
||||
this.set = set;
|
||||
}
|
||||
|
||||
public SortedSet getSortedSet() {
|
||||
return sortedSet;
|
||||
}
|
||||
|
||||
public void setSortedSet(SortedSet sortedSet) {
|
||||
this.sortedSet = sortedSet;
|
||||
}
|
||||
|
||||
public Map getMap() {
|
||||
return map;
|
||||
}
|
||||
|
||||
public void setMap(Map map) {
|
||||
this.map = map;
|
||||
}
|
||||
|
||||
public SortedMap getSortedMap() {
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
public void setSortedMap(SortedMap sortedMap) {
|
||||
this.sortedMap = sortedMap;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
/**
|
||||
* Simple nested test bean used for testing bean factories, AOP framework etc.
|
||||
*
|
||||
* @author Trevor D. Cook
|
||||
* @since 30.09.2003
|
||||
*/
|
||||
public class NestedTestBean implements INestedTestBean {
|
||||
|
||||
private String company = "";
|
||||
|
||||
public NestedTestBean() {
|
||||
}
|
||||
|
||||
public NestedTestBean(String company) {
|
||||
setCompany(company);
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = (company != null ? company : "");
|
||||
}
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof NestedTestBean)) {
|
||||
return false;
|
||||
}
|
||||
NestedTestBean ntb = (NestedTestBean) obj;
|
||||
return this.company.equals(ntb.company);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.company.hashCode();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "NestedTestBean: " + this.company;
|
||||
}
|
||||
|
||||
}
|
||||
437
spring-orm/src/test/java/org/springframework/beans/TestBean.java
Normal file
437
spring-orm/src/test/java/org/springframework/beans/TestBean.java
Normal file
@@ -0,0 +1,437 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanFactoryAware;
|
||||
import org.springframework.beans.factory.BeanNameAware;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
/**
|
||||
* Simple test bean used for testing bean factories, the AOP framework etc.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 15 April 2001
|
||||
*/
|
||||
public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable {
|
||||
|
||||
private String beanName;
|
||||
|
||||
private String country;
|
||||
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
private boolean postProcessed;
|
||||
|
||||
private String name;
|
||||
|
||||
private String sex;
|
||||
|
||||
private int age;
|
||||
|
||||
private boolean jedi;
|
||||
|
||||
private ITestBean[] spouses;
|
||||
|
||||
private String touchy;
|
||||
|
||||
private String[] stringArray;
|
||||
|
||||
private Integer[] someIntegerArray;
|
||||
|
||||
private Date date = new Date();
|
||||
|
||||
private Float myFloat = new Float(0.0);
|
||||
|
||||
private Collection friends = new LinkedList();
|
||||
|
||||
private Set someSet = new HashSet();
|
||||
|
||||
private Map someMap = new HashMap();
|
||||
|
||||
private List someList = new ArrayList();
|
||||
|
||||
private Properties someProperties = new Properties();
|
||||
|
||||
private INestedTestBean doctor = new NestedTestBean();
|
||||
|
||||
private INestedTestBean lawyer = new NestedTestBean();
|
||||
|
||||
private IndexedTestBean nestedIndexedBean;
|
||||
|
||||
private boolean destroyed;
|
||||
|
||||
private Number someNumber;
|
||||
|
||||
private Colour favouriteColour;
|
||||
|
||||
private Boolean someBoolean;
|
||||
|
||||
private List otherColours;
|
||||
|
||||
private List pets;
|
||||
|
||||
|
||||
public TestBean() {
|
||||
}
|
||||
|
||||
public TestBean(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public TestBean(ITestBean spouse) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
}
|
||||
|
||||
public TestBean(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public TestBean(ITestBean spouse, Properties someProperties) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
public TestBean(List someList) {
|
||||
this.someList = someList;
|
||||
}
|
||||
|
||||
public TestBean(Set someSet) {
|
||||
this.someSet = someSet;
|
||||
}
|
||||
|
||||
public TestBean(Map someMap) {
|
||||
this.someMap = someMap;
|
||||
}
|
||||
|
||||
public TestBean(Properties someProperties) {
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
public BeanFactory getBeanFactory() {
|
||||
return beanFactory;
|
||||
}
|
||||
|
||||
public void setPostProcessed(boolean postProcessed) {
|
||||
this.postProcessed = postProcessed;
|
||||
}
|
||||
|
||||
public boolean isPostProcessed() {
|
||||
return postProcessed;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSex() {
|
||||
return sex;
|
||||
}
|
||||
|
||||
public void setSex(String sex) {
|
||||
this.sex = sex;
|
||||
if (this.name == null) {
|
||||
this.name = sex;
|
||||
}
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public boolean isJedi() {
|
||||
return jedi;
|
||||
}
|
||||
|
||||
public void setJedi(boolean jedi) {
|
||||
this.jedi = jedi;
|
||||
}
|
||||
|
||||
public ITestBean getSpouse() {
|
||||
return (spouses != null ? spouses[0] : null);
|
||||
}
|
||||
|
||||
public void setSpouse(ITestBean spouse) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
}
|
||||
|
||||
public ITestBean[] getSpouses() {
|
||||
return spouses;
|
||||
}
|
||||
|
||||
public String getTouchy() {
|
||||
return touchy;
|
||||
}
|
||||
|
||||
public void setTouchy(String touchy) throws Exception {
|
||||
if (touchy.indexOf('.') != -1) {
|
||||
throw new Exception("Can't contain a .");
|
||||
}
|
||||
if (touchy.indexOf(',') != -1) {
|
||||
throw new NumberFormatException("Number format exception: contains a ,");
|
||||
}
|
||||
this.touchy = touchy;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String[] getStringArray() {
|
||||
return stringArray;
|
||||
}
|
||||
|
||||
public void setStringArray(String[] stringArray) {
|
||||
this.stringArray = stringArray;
|
||||
}
|
||||
|
||||
public Integer[] getSomeIntegerArray() {
|
||||
return someIntegerArray;
|
||||
}
|
||||
|
||||
public void setSomeIntegerArray(Integer[] someIntegerArray) {
|
||||
this.someIntegerArray = someIntegerArray;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public Float getMyFloat() {
|
||||
return myFloat;
|
||||
}
|
||||
|
||||
public void setMyFloat(Float myFloat) {
|
||||
this.myFloat = myFloat;
|
||||
}
|
||||
|
||||
public Collection getFriends() {
|
||||
return friends;
|
||||
}
|
||||
|
||||
public void setFriends(Collection friends) {
|
||||
this.friends = friends;
|
||||
}
|
||||
|
||||
public Set getSomeSet() {
|
||||
return someSet;
|
||||
}
|
||||
|
||||
public void setSomeSet(Set someSet) {
|
||||
this.someSet = someSet;
|
||||
}
|
||||
|
||||
public Map getSomeMap() {
|
||||
return someMap;
|
||||
}
|
||||
|
||||
public void setSomeMap(Map someMap) {
|
||||
this.someMap = someMap;
|
||||
}
|
||||
|
||||
public List getSomeList() {
|
||||
return someList;
|
||||
}
|
||||
|
||||
public void setSomeList(List someList) {
|
||||
this.someList = someList;
|
||||
}
|
||||
|
||||
public Properties getSomeProperties() {
|
||||
return someProperties;
|
||||
}
|
||||
|
||||
public void setSomeProperties(Properties someProperties) {
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
public INestedTestBean getDoctor() {
|
||||
return doctor;
|
||||
}
|
||||
|
||||
public void setDoctor(INestedTestBean doctor) {
|
||||
this.doctor = doctor;
|
||||
}
|
||||
|
||||
public INestedTestBean getLawyer() {
|
||||
return lawyer;
|
||||
}
|
||||
|
||||
public void setLawyer(INestedTestBean lawyer) {
|
||||
this.lawyer = lawyer;
|
||||
}
|
||||
|
||||
public Number getSomeNumber() {
|
||||
return someNumber;
|
||||
}
|
||||
|
||||
public void setSomeNumber(Number someNumber) {
|
||||
this.someNumber = someNumber;
|
||||
}
|
||||
|
||||
public Colour getFavouriteColour() {
|
||||
return favouriteColour;
|
||||
}
|
||||
|
||||
public void setFavouriteColour(Colour favouriteColour) {
|
||||
this.favouriteColour = favouriteColour;
|
||||
}
|
||||
|
||||
public Boolean getSomeBoolean() {
|
||||
return someBoolean;
|
||||
}
|
||||
|
||||
public void setSomeBoolean(Boolean someBoolean) {
|
||||
this.someBoolean = someBoolean;
|
||||
}
|
||||
|
||||
public IndexedTestBean getNestedIndexedBean() {
|
||||
return nestedIndexedBean;
|
||||
}
|
||||
|
||||
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
|
||||
this.nestedIndexedBean = nestedIndexedBean;
|
||||
}
|
||||
|
||||
public List getOtherColours() {
|
||||
return otherColours;
|
||||
}
|
||||
|
||||
public void setOtherColours(List otherColours) {
|
||||
this.otherColours = otherColours;
|
||||
}
|
||||
|
||||
public List getPets() {
|
||||
return pets;
|
||||
}
|
||||
|
||||
public void setPets(List pets) {
|
||||
this.pets = pets;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see org.springframework.beans.ITestBean#exceptional(Throwable)
|
||||
*/
|
||||
public void exceptional(Throwable t) throws Throwable {
|
||||
if (t != null) {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
public void unreliableFileOperation() throws IOException {
|
||||
throw new IOException();
|
||||
}
|
||||
/**
|
||||
* @see org.springframework.beans.ITestBean#returnsThis()
|
||||
*/
|
||||
public Object returnsThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.beans.IOther#absquatulate()
|
||||
*/
|
||||
public void absquatulate() {
|
||||
}
|
||||
|
||||
public int haveBirthday() {
|
||||
return age++;
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public boolean wasDestroyed() {
|
||||
return destroyed;
|
||||
}
|
||||
|
||||
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (other == null || !(other instanceof TestBean)) {
|
||||
return false;
|
||||
}
|
||||
TestBean tb2 = (TestBean) other;
|
||||
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.age;
|
||||
}
|
||||
|
||||
public int compareTo(Object other) {
|
||||
if (this.name != null && other instanceof TestBean) {
|
||||
return this.name.compareTo(((TestBean) other).getName());
|
||||
}
|
||||
else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans.factory.config;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class SimpleMapScope implements Scope, Serializable {
|
||||
|
||||
private final Map map = new HashMap();
|
||||
|
||||
private final List callbacks = new LinkedList();
|
||||
|
||||
|
||||
public SimpleMapScope() {
|
||||
}
|
||||
|
||||
public final Map getMap() {
|
||||
return this.map;
|
||||
}
|
||||
|
||||
|
||||
public Object get(String name, ObjectFactory objectFactory) {
|
||||
synchronized (this.map) {
|
||||
Object scopedObject = this.map.get(name);
|
||||
if (scopedObject == null) {
|
||||
scopedObject = objectFactory.getObject();
|
||||
this.map.put(name, scopedObject);
|
||||
}
|
||||
return scopedObject;
|
||||
}
|
||||
}
|
||||
|
||||
public Object remove(String name) {
|
||||
synchronized (this.map) {
|
||||
return this.map.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void registerDestructionCallback(String name, Runnable callback) {
|
||||
this.callbacks.add(callback);
|
||||
}
|
||||
|
||||
public Object resolveContextualObject(String key) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
for (Iterator it = this.callbacks.iterator(); it.hasNext();) {
|
||||
Runnable runnable = (Runnable) it.next();
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
|
||||
public String getConversationId() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.jndi;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import javax.naming.NamingException;
|
||||
|
||||
import org.springframework.core.CollectionFactory;
|
||||
import org.springframework.jndi.JndiTemplate;
|
||||
|
||||
/**
|
||||
* Simple extension of the JndiTemplate class that always returns
|
||||
* a given object. Very useful for testing. Effectively a mock object.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class ExpectedLookupTemplate extends JndiTemplate {
|
||||
|
||||
private final Map<String, Object> jndiObjects = new ConcurrentHashMap<String, Object>();
|
||||
|
||||
|
||||
/**
|
||||
* Construct a new JndiTemplate that will always return given objects
|
||||
* for given names. To be populated through <code>addObject</code> calls.
|
||||
* @see #addObject(String, Object)
|
||||
*/
|
||||
public ExpectedLookupTemplate() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a new JndiTemplate that will always return the
|
||||
* given object, but honour only requests for the given name.
|
||||
* @param name the name the client is expected to look up
|
||||
* @param object the object that will be returned
|
||||
*/
|
||||
public ExpectedLookupTemplate(String name, Object object) {
|
||||
addObject(name, object);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add the given object to the list of JNDI objects that this
|
||||
* template will expose.
|
||||
* @param name the name the client is expected to look up
|
||||
* @param object the object that will be returned
|
||||
*/
|
||||
public void addObject(String name, Object object) {
|
||||
this.jndiObjects.put(name, object);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* If the name is the expected name specified in the constructor,
|
||||
* return the object provided in the constructor. If the name is
|
||||
* unexpected, a respective NamingException gets thrown.
|
||||
*/
|
||||
public Object lookup(String name) throws NamingException {
|
||||
Object object = this.jndiObjects.get(name);
|
||||
if (object == null) {
|
||||
throw new NamingException("Unexpected JNDI name '" + name + "': expecting " + this.jndiObjects.keySet());
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.jndi;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import javax.naming.Binding;
|
||||
import javax.naming.Context;
|
||||
import javax.naming.Name;
|
||||
import javax.naming.NameClassPair;
|
||||
import javax.naming.NameNotFoundException;
|
||||
import javax.naming.NameParser;
|
||||
import javax.naming.NamingEnumeration;
|
||||
import javax.naming.NamingException;
|
||||
import javax.naming.OperationNotSupportedException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Simple implementation of a JNDI naming context.
|
||||
* Only supports binding plain Objects to String names.
|
||||
* Mainly for test environments, but also usable for standalone applications.
|
||||
*
|
||||
* <p>This class is not intended for direct usage by applications, although it
|
||||
* can be used for example to override JndiTemplate's <code>createInitialContext</code>
|
||||
* method in unit tests. Typically, SimpleNamingContextBuilder will be used to
|
||||
* set up a JVM-level JNDI environment.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @see org.springframework.mock.jndi.SimpleNamingContextBuilder
|
||||
* @see org.springframework.jndi.JndiTemplate#createInitialContext
|
||||
*/
|
||||
public class SimpleNamingContext implements Context {
|
||||
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final String root;
|
||||
|
||||
private final Hashtable<String, Object> boundObjects;
|
||||
|
||||
private final Hashtable<String, Object> environment = new Hashtable<String, Object>();
|
||||
|
||||
|
||||
/**
|
||||
* Create a new naming context.
|
||||
*/
|
||||
public SimpleNamingContext() {
|
||||
this("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new naming context with the given naming root.
|
||||
*/
|
||||
public SimpleNamingContext(String root) {
|
||||
this.root = root;
|
||||
this.boundObjects = new Hashtable<String, Object>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new naming context with the given naming root,
|
||||
* the given name/object map, and the JNDI environment entries.
|
||||
*/
|
||||
public SimpleNamingContext(String root, Hashtable<String, Object> boundObjects, Hashtable<String, Object> env) {
|
||||
this.root = root;
|
||||
this.boundObjects = boundObjects;
|
||||
if (env != null) {
|
||||
this.environment.putAll(env);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Actual implementations of Context methods follow
|
||||
|
||||
public NamingEnumeration<NameClassPair> list(String root) throws NamingException {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Listing name/class pairs under [" + root + "]");
|
||||
}
|
||||
return new NameClassPairEnumeration(this, root);
|
||||
}
|
||||
|
||||
public NamingEnumeration<Binding> listBindings(String root) throws NamingException {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Listing bindings under [" + root + "]");
|
||||
}
|
||||
return new BindingEnumeration(this, root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the object with the given name.
|
||||
* <p>Note: Not intended for direct use by applications.
|
||||
* Will be used by any standard InitialContext JNDI lookups.
|
||||
* @throws javax.naming.NameNotFoundException if the object could not be found
|
||||
*/
|
||||
public Object lookup(String lookupName) throws NameNotFoundException {
|
||||
String name = this.root + lookupName;
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Static JNDI lookup: [" + name + "]");
|
||||
}
|
||||
if ("".equals(name)) {
|
||||
return new SimpleNamingContext(this.root, this.boundObjects, this.environment);
|
||||
}
|
||||
Object found = this.boundObjects.get(name);
|
||||
if (found == null) {
|
||||
if (!name.endsWith("/")) {
|
||||
name = name + "/";
|
||||
}
|
||||
for (String boundName : this.boundObjects.keySet()) {
|
||||
if (boundName.startsWith(name)) {
|
||||
return new SimpleNamingContext(name, this.boundObjects, this.environment);
|
||||
}
|
||||
}
|
||||
throw new NameNotFoundException(
|
||||
"Name [" + this.root + lookupName + "] not bound; " + this.boundObjects.size() + " bindings: [" +
|
||||
StringUtils.collectionToDelimitedString(this.boundObjects.keySet(), ",") + "]");
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
public Object lookupLink(String name) throws NameNotFoundException {
|
||||
return lookup(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the given object to the given name.
|
||||
* Note: Not intended for direct use by applications
|
||||
* if setting up a JVM-level JNDI environment.
|
||||
* Use SimpleNamingContextBuilder to set up JNDI bindings then.
|
||||
* @see org.springframework.mock.jndi.SimpleNamingContextBuilder#bind
|
||||
*/
|
||||
public void bind(String name, Object obj) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Static JNDI binding: [" + this.root + name + "] = [" + obj + "]");
|
||||
}
|
||||
this.boundObjects.put(this.root + name, obj);
|
||||
}
|
||||
|
||||
public void unbind(String name) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Static JNDI remove: [" + this.root + name + "]");
|
||||
}
|
||||
this.boundObjects.remove(this.root + name);
|
||||
}
|
||||
|
||||
public void rebind(String name, Object obj) {
|
||||
bind(name, obj);
|
||||
}
|
||||
|
||||
public void rename(String oldName, String newName) throws NameNotFoundException {
|
||||
Object obj = lookup(oldName);
|
||||
unbind(oldName);
|
||||
bind(newName, obj);
|
||||
}
|
||||
|
||||
public Context createSubcontext(String name) {
|
||||
String subcontextName = this.root + name;
|
||||
if (!subcontextName.endsWith("/")) {
|
||||
subcontextName += "/";
|
||||
}
|
||||
Context subcontext = new SimpleNamingContext(subcontextName, this.boundObjects, this.environment);
|
||||
bind(name, subcontext);
|
||||
return subcontext;
|
||||
}
|
||||
|
||||
public void destroySubcontext(String name) {
|
||||
unbind(name);
|
||||
}
|
||||
|
||||
public String composeName(String name, String prefix) {
|
||||
return prefix + name;
|
||||
}
|
||||
|
||||
public Hashtable<String, Object> getEnvironment() {
|
||||
return this.environment;
|
||||
}
|
||||
|
||||
public Object addToEnvironment(String propName, Object propVal) {
|
||||
return this.environment.put(propName, propVal);
|
||||
}
|
||||
|
||||
public Object removeFromEnvironment(String propName) {
|
||||
return this.environment.remove(propName);
|
||||
}
|
||||
|
||||
public void close() {
|
||||
}
|
||||
|
||||
|
||||
// Unsupported methods follow: no support for javax.naming.Name
|
||||
|
||||
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public Object lookup(Name name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public Object lookupLink(Name name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public void bind(Name name, Object obj) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public void unbind(Name name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public void rebind(Name name, Object obj) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public void rename(Name oldName, Name newName) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public Context createSubcontext(Name name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public void destroySubcontext(Name name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public String getNameInNamespace() throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public NameParser getNameParser(Name name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public NameParser getNameParser(String name) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
public Name composeName(Name name, Name prefix) throws NamingException {
|
||||
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
|
||||
}
|
||||
|
||||
|
||||
private static abstract class AbstractNamingEnumeration<T> implements NamingEnumeration<T> {
|
||||
|
||||
private Iterator<T> iterator;
|
||||
|
||||
private AbstractNamingEnumeration(SimpleNamingContext context, String proot) throws NamingException {
|
||||
if (!"".equals(proot) && !proot.endsWith("/")) {
|
||||
proot = proot + "/";
|
||||
}
|
||||
String root = context.root + proot;
|
||||
Map<String, T> contents = new HashMap<String, T>();
|
||||
for (String boundName : context.boundObjects.keySet()) {
|
||||
if (boundName.startsWith(root)) {
|
||||
int startIndex = root.length();
|
||||
int endIndex = boundName.indexOf('/', startIndex);
|
||||
String strippedName =
|
||||
(endIndex != -1 ? boundName.substring(startIndex, endIndex) : boundName.substring(startIndex));
|
||||
if (!contents.containsKey(strippedName)) {
|
||||
try {
|
||||
contents.put(strippedName, createObject(strippedName, context.lookup(proot + strippedName)));
|
||||
}
|
||||
catch (NameNotFoundException ex) {
|
||||
// cannot happen
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (contents.size() == 0) {
|
||||
throw new NamingException("Invalid root: [" + context.root + proot + "]");
|
||||
}
|
||||
this.iterator = contents.values().iterator();
|
||||
}
|
||||
|
||||
protected abstract T createObject(String strippedName, Object obj);
|
||||
|
||||
public boolean hasMore() {
|
||||
return this.iterator.hasNext();
|
||||
}
|
||||
|
||||
public T next() {
|
||||
return this.iterator.next();
|
||||
}
|
||||
|
||||
public boolean hasMoreElements() {
|
||||
return this.iterator.hasNext();
|
||||
}
|
||||
|
||||
public T nextElement() {
|
||||
return this.iterator.next();
|
||||
}
|
||||
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class NameClassPairEnumeration extends AbstractNamingEnumeration<NameClassPair> {
|
||||
|
||||
private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException {
|
||||
super(context, root);
|
||||
}
|
||||
|
||||
protected NameClassPair createObject(String strippedName, Object obj) {
|
||||
return new NameClassPair(strippedName, obj.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class BindingEnumeration extends AbstractNamingEnumeration<Binding> {
|
||||
|
||||
private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException {
|
||||
super(context, root);
|
||||
}
|
||||
|
||||
protected Binding createObject(String strippedName, Object obj) {
|
||||
return new Binding(strippedName, obj);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.jndi;
|
||||
|
||||
import java.util.Hashtable;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.NamingException;
|
||||
import javax.naming.spi.InitialContextFactory;
|
||||
import javax.naming.spi.InitialContextFactoryBuilder;
|
||||
import javax.naming.spi.NamingManager;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* Simple implementation of a JNDI naming context builder.
|
||||
*
|
||||
* <p>Mainly targeted at test environments, where each test case can
|
||||
* configure JNDI appropriately, so that <code>new InitialContext()</code>
|
||||
* will expose the required objects. Also usable for standalone applications,
|
||||
* e.g. for binding a JDBC DataSource to a well-known JNDI location, to be
|
||||
* able to use traditional J2EE data access code outside of a J2EE container.
|
||||
*
|
||||
* <p>There are various choices for DataSource implementations:
|
||||
* <ul>
|
||||
* <li>SingleConnectionDataSource (using the same Connection for all getConnection calls);
|
||||
* <li>DriverManagerDataSource (creating a new Connection on each getConnection call);
|
||||
* <li>Apache's Jakarta Commons DBCP offers BasicDataSource (a real pool).
|
||||
* </ul>
|
||||
*
|
||||
* <p>Typical usage in bootstrap code:
|
||||
*
|
||||
* <pre class="code">
|
||||
* SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
|
||||
* DataSource ds = new DriverManagerDataSource(...);
|
||||
* builder.bind("java:comp/env/jdbc/myds", ds);
|
||||
* builder.activate();</pre>
|
||||
*
|
||||
* Note that it's impossible to activate multiple builders within the same JVM,
|
||||
* due to JNDI restrictions. Thus to configure a fresh builder repeatedly, use
|
||||
* the following code to get a reference to either an already activated builder
|
||||
* or a newly activated one:
|
||||
*
|
||||
* <pre class="code">
|
||||
* SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
|
||||
* DataSource ds = new DriverManagerDataSource(...);
|
||||
* builder.bind("java:comp/env/jdbc/myds", ds);</pre>
|
||||
*
|
||||
* Note that you <i>should not</i> call <code>activate()</code> on a builder from
|
||||
* this factory method, as there will already be an activated one in any case.
|
||||
*
|
||||
* <p>An instance of this class is only necessary at setup time.
|
||||
* An application does not need to keep a reference to it after activation.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
* @see #emptyActivatedContextBuilder()
|
||||
* @see #bind(String, Object)
|
||||
* @see #activate()
|
||||
* @see org.springframework.mock.jndi.SimpleNamingContext
|
||||
* @see org.springframework.jdbc.datasource.SingleConnectionDataSource
|
||||
* @see org.springframework.jdbc.datasource.DriverManagerDataSource
|
||||
* @see org.apache.commons.dbcp.BasicDataSource
|
||||
*/
|
||||
public class SimpleNamingContextBuilder implements InitialContextFactoryBuilder {
|
||||
|
||||
/** An instance of this class bound to JNDI */
|
||||
private static volatile SimpleNamingContextBuilder activated;
|
||||
|
||||
private static boolean initialized = false;
|
||||
|
||||
private static final Object initializationLock = new Object();
|
||||
|
||||
|
||||
/**
|
||||
* Checks if a SimpleNamingContextBuilder is active.
|
||||
* @return the current SimpleNamingContextBuilder instance,
|
||||
* or <code>null</code> if none
|
||||
*/
|
||||
public static SimpleNamingContextBuilder getCurrentContextBuilder() {
|
||||
return activated;
|
||||
}
|
||||
|
||||
/**
|
||||
* If no SimpleNamingContextBuilder is already configuring JNDI,
|
||||
* create and activate one. Otherwise take the existing activate
|
||||
* SimpleNamingContextBuilder, clear it and return it.
|
||||
* <p>This is mainly intended for test suites that want to
|
||||
* reinitialize JNDI bindings from scratch repeatedly.
|
||||
* @return an empty SimpleNamingContextBuilder that can be used
|
||||
* to control JNDI bindings
|
||||
*/
|
||||
public static SimpleNamingContextBuilder emptyActivatedContextBuilder() throws NamingException {
|
||||
if (activated != null) {
|
||||
// Clear already activated context builder.
|
||||
activated.clear();
|
||||
}
|
||||
else {
|
||||
// Create and activate new context builder.
|
||||
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
|
||||
// The activate() call will cause an assignment to the activated variable.
|
||||
builder.activate();
|
||||
}
|
||||
return activated;
|
||||
}
|
||||
|
||||
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final Hashtable<String,Object> boundObjects = new Hashtable<String,Object>();
|
||||
|
||||
|
||||
/**
|
||||
* Register the context builder by registering it with the JNDI NamingManager.
|
||||
* Note that once this has been done, <code>new InitialContext()</code> will always
|
||||
* return a context from this factory. Use the <code>emptyActivatedContextBuilder()</code>
|
||||
* static method to get an empty context (for example, in test methods).
|
||||
* @throws IllegalStateException if there's already a naming context builder
|
||||
* registered with the JNDI NamingManager
|
||||
*/
|
||||
public void activate() throws IllegalStateException, NamingException {
|
||||
logger.info("Activating simple JNDI environment");
|
||||
synchronized (initializationLock) {
|
||||
if (!initialized) {
|
||||
if (NamingManager.hasInitialContextFactoryBuilder()) {
|
||||
throw new IllegalStateException(
|
||||
"Cannot activate SimpleNamingContextBuilder: there is already a JNDI provider registered. " +
|
||||
"Note that JNDI is a JVM-wide service, shared at the JVM system class loader level, " +
|
||||
"with no reset option. As a consequence, a JNDI provider must only be registered once per JVM.");
|
||||
}
|
||||
NamingManager.setInitialContextFactoryBuilder(this);
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
activated = this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Temporarily deactivate this context builder. It will remain registered with
|
||||
* the JNDI NamingManager but will delegate to the standard JNDI InitialContextFactory
|
||||
* (if configured) instead of exposing its own bound objects.
|
||||
* <p>Call <code>activate()</code> again in order to expose this context builder's own
|
||||
* bound objects again. Such activate/deactivate sequences can be applied any number
|
||||
* of times (e.g. within a larger integration test suite running in the same VM).
|
||||
* @see #activate()
|
||||
*/
|
||||
public void deactivate() {
|
||||
logger.info("Deactivating simple JNDI environment");
|
||||
activated = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all bindings in this context builder, while keeping it active.
|
||||
*/
|
||||
public void clear() {
|
||||
this.boundObjects.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the given object under the given name, for all naming contexts
|
||||
* that this context builder will generate.
|
||||
* @param name the JNDI name of the object (e.g. "java:comp/env/jdbc/myds")
|
||||
* @param obj the object to bind (e.g. a DataSource implementation)
|
||||
*/
|
||||
public void bind(String name, Object obj) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Static JNDI binding: [" + name + "] = [" + obj + "]");
|
||||
}
|
||||
this.boundObjects.put(name, obj);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Simple InitialContextFactoryBuilder implementation,
|
||||
* creating a new SimpleNamingContext instance.
|
||||
* @see SimpleNamingContext
|
||||
*/
|
||||
public InitialContextFactory createInitialContextFactory(Hashtable<?,?> environment) {
|
||||
if (activated == null && environment != null) {
|
||||
Object icf = environment.get(Context.INITIAL_CONTEXT_FACTORY);
|
||||
if (icf != null) {
|
||||
Class<?> icfClass = null;
|
||||
if (icf instanceof Class) {
|
||||
icfClass = (Class<?>) icf;
|
||||
}
|
||||
else if (icf instanceof String) {
|
||||
icfClass = ClassUtils.resolveClassName((String) icf, getClass().getClassLoader());
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Invalid value type for environment key [" +
|
||||
Context.INITIAL_CONTEXT_FACTORY + "]: " + icf.getClass().getName());
|
||||
}
|
||||
if (!InitialContextFactory.class.isAssignableFrom(icfClass)) {
|
||||
throw new IllegalArgumentException(
|
||||
"Specified class does not implement [" + InitialContextFactory.class.getName() + "]: " + icf);
|
||||
}
|
||||
try {
|
||||
return (InitialContextFactory) icfClass.newInstance();
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
IllegalStateException ise =
|
||||
new IllegalStateException("Cannot instantiate specified InitialContextFactory: " + icf);
|
||||
ise.initCause(ex);
|
||||
throw ise;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Default case...
|
||||
return new InitialContextFactory() {
|
||||
@SuppressWarnings("unchecked")
|
||||
public Context getInitialContext(Hashtable<?,?> environment) {
|
||||
return new SimpleNamingContext("", boundObjects, (Hashtable<String, Object>) environment);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import javax.servlet.ServletInputStream;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Delegating implementation of {@link javax.servlet.ServletInputStream}.
|
||||
*
|
||||
* <p>Used by {@link org.springframework.mock.web.MockHttpServletRequest}; typically not directly
|
||||
* used for testing application controllers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
* @see org.springframework.mock.web.MockHttpServletRequest
|
||||
*/
|
||||
public class DelegatingServletInputStream extends ServletInputStream {
|
||||
|
||||
private final InputStream sourceStream;
|
||||
|
||||
|
||||
/**
|
||||
* Create a DelegatingServletInputStream for the given source stream.
|
||||
* @param sourceStream the source stream (never <code>null</code>)
|
||||
*/
|
||||
public DelegatingServletInputStream(InputStream sourceStream) {
|
||||
Assert.notNull(sourceStream, "Source InputStream must not be null");
|
||||
this.sourceStream = sourceStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying source stream (never <code>null</code>).
|
||||
*/
|
||||
public final InputStream getSourceStream() {
|
||||
return this.sourceStream;
|
||||
}
|
||||
|
||||
|
||||
public int read() throws IOException {
|
||||
return this.sourceStream.read();
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
super.close();
|
||||
this.sourceStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Delegating implementation of {@link javax.servlet.ServletOutputStream}.
|
||||
*
|
||||
* <p>Used by {@link org.springframework.mock.web.MockHttpServletResponse}; typically not directly
|
||||
* used for testing application controllers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
* @see org.springframework.mock.web.MockHttpServletResponse
|
||||
*/
|
||||
public class DelegatingServletOutputStream extends ServletOutputStream {
|
||||
|
||||
private final OutputStream targetStream;
|
||||
|
||||
|
||||
/**
|
||||
* Create a DelegatingServletOutputStream for the given target stream.
|
||||
* @param targetStream the target stream (never <code>null</code>)
|
||||
*/
|
||||
public DelegatingServletOutputStream(OutputStream targetStream) {
|
||||
Assert.notNull(targetStream, "Target OutputStream must not be null");
|
||||
this.targetStream = targetStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying target stream (never <code>null</code>).
|
||||
*/
|
||||
public final OutputStream getTargetStream() {
|
||||
return this.targetStream;
|
||||
}
|
||||
|
||||
|
||||
public void write(int b) throws IOException {
|
||||
this.targetStream.write(b);
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
super.flush();
|
||||
this.targetStream.flush();
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
super.close();
|
||||
this.targetStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* Internal helper class that serves as value holder for request headers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rick Evans
|
||||
* @since 2.0.1
|
||||
*/
|
||||
class HeaderValueHolder {
|
||||
|
||||
private final List<Object> values = new LinkedList<Object>();
|
||||
|
||||
|
||||
public void setValue(Object value) {
|
||||
this.values.clear();
|
||||
this.values.add(value);
|
||||
}
|
||||
|
||||
public void addValue(Object value) {
|
||||
this.values.add(value);
|
||||
}
|
||||
|
||||
public void addValues(Collection<?> values) {
|
||||
this.values.addAll(values);
|
||||
}
|
||||
|
||||
public void addValueArray(Object values) {
|
||||
CollectionUtils.mergeArrayIntoCollection(values, this.values);
|
||||
}
|
||||
|
||||
public List<Object> getValues() {
|
||||
return Collections.unmodifiableList(this.values);
|
||||
}
|
||||
|
||||
public List<String> getStringValues() {
|
||||
List<String> stringList = new ArrayList<String>(this.values.size());
|
||||
for (Object value : this.values) {
|
||||
stringList.add(value.toString());
|
||||
}
|
||||
return Collections.unmodifiableList(stringList);
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return (!this.values.isEmpty() ? this.values.get(0) : null);
|
||||
}
|
||||
|
||||
public String getStringValue() {
|
||||
return (!this.values.isEmpty() ? this.values.get(0).toString() : null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Find a HeaderValueHolder by name, ignoring casing.
|
||||
* @param headers the Map of header names to HeaderValueHolders
|
||||
* @param name the name of the desired header
|
||||
* @return the corresponding HeaderValueHolder,
|
||||
* or <code>null</code> if none found
|
||||
*/
|
||||
public static HeaderValueHolder getByName(Map<String, HeaderValueHolder> headers, String name) {
|
||||
Assert.notNull(name, "Header name must not be null");
|
||||
for (String headerName : headers.keySet()) {
|
||||
if (headerName.equalsIgnoreCase(name)) {
|
||||
return headers.get(headerName);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.FilterConfig} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; also useful for testing
|
||||
* custom {@link javax.servlet.Filter} implementations.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.0.3
|
||||
* @see org.springframework.mock.web.MockFilterConfig
|
||||
* @see org.springframework.mock.web.PassThroughFilterChain
|
||||
*/
|
||||
public class MockFilterChain implements FilterChain {
|
||||
|
||||
private ServletRequest request;
|
||||
|
||||
private ServletResponse response;
|
||||
|
||||
|
||||
/**
|
||||
* Records the request and response.
|
||||
*/
|
||||
public void doFilter(ServletRequest request, ServletResponse response) {
|
||||
Assert.notNull(request, "Request must not be null");
|
||||
Assert.notNull(response, "Response must not be null");
|
||||
if (this.request != null) {
|
||||
throw new IllegalStateException("This FilterChain has already been called!");
|
||||
}
|
||||
this.request = request;
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the request that {@link #doFilter} has been called with.
|
||||
*/
|
||||
public ServletRequest getRequest() {
|
||||
return this.request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the response that {@link #doFilter} has been called with.
|
||||
*/
|
||||
public ServletResponse getResponse() {
|
||||
return this.response;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.FilterConfig} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; also useful for testing
|
||||
* custom {@link javax.servlet.Filter} implementations.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
* @see org.springframework.mock.web.MockFilterChain
|
||||
* @see org.springframework.mock.web.PassThroughFilterChain
|
||||
*/
|
||||
public class MockFilterConfig implements FilterConfig {
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private final String filterName;
|
||||
|
||||
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockFilterConfig with a default {@link org.springframework.mock.web.MockServletContext}.
|
||||
*/
|
||||
public MockFilterConfig() {
|
||||
this(null, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockFilterConfig with a default {@link org.springframework.mock.web.MockServletContext}.
|
||||
* @param filterName the name of the filter
|
||||
*/
|
||||
public MockFilterConfig(String filterName) {
|
||||
this(null, filterName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockFilterConfig.
|
||||
* @param servletContext the ServletContext that the servlet runs in
|
||||
*/
|
||||
public MockFilterConfig(ServletContext servletContext) {
|
||||
this(servletContext, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockFilterConfig.
|
||||
* @param servletContext the ServletContext that the servlet runs in
|
||||
* @param filterName the name of the filter
|
||||
*/
|
||||
public MockFilterConfig(ServletContext servletContext, String filterName) {
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.filterName = filterName;
|
||||
}
|
||||
|
||||
|
||||
public String getFilterName() {
|
||||
return filterName;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return servletContext;
|
||||
}
|
||||
|
||||
public void addInitParameter(String name, String value) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.initParameters.put(name, value);
|
||||
}
|
||||
|
||||
public String getInitParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
return this.initParameters.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getInitParameterNames() {
|
||||
return Collections.enumeration(this.initParameters.keySet());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,904 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.Principal;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Vector;
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.LinkedCaseInsensitiveMap;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.http.HttpServletRequest} interface.
|
||||
*
|
||||
* <p>Compatible with Servlet 2.5 and partially with Servlet 3.0 (notable exceptions:
|
||||
* the <code>getPart(s)</code> and <code>startAsync</code> families of methods).
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
* @author Rick Evans
|
||||
* @author Mark Fisher
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockHttpServletRequest implements HttpServletRequest {
|
||||
|
||||
/**
|
||||
* The default protocol: 'http'.
|
||||
*/
|
||||
public static final String DEFAULT_PROTOCOL = "http";
|
||||
|
||||
/**
|
||||
* The default server address: '127.0.0.1'.
|
||||
*/
|
||||
public static final String DEFAULT_SERVER_ADDR = "127.0.0.1";
|
||||
|
||||
/**
|
||||
* The default server name: 'localhost'.
|
||||
*/
|
||||
public static final String DEFAULT_SERVER_NAME = "localhost";
|
||||
|
||||
/**
|
||||
* The default server port: '80'.
|
||||
*/
|
||||
public static final int DEFAULT_SERVER_PORT = 80;
|
||||
|
||||
/**
|
||||
* The default remote address: '127.0.0.1'.
|
||||
*/
|
||||
public static final String DEFAULT_REMOTE_ADDR = "127.0.0.1";
|
||||
|
||||
/**
|
||||
* The default remote host: 'localhost'.
|
||||
*/
|
||||
public static final String DEFAULT_REMOTE_HOST = "localhost";
|
||||
|
||||
private static final String CONTENT_TYPE_HEADER = "Content-Type";
|
||||
|
||||
private static final String CHARSET_PREFIX = "charset=";
|
||||
|
||||
|
||||
private boolean active = true;
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// ServletRequest properties
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
|
||||
|
||||
private String characterEncoding;
|
||||
|
||||
private byte[] content;
|
||||
|
||||
private String contentType;
|
||||
|
||||
private final Map<String, String[]> parameters = new LinkedHashMap<String, String[]>(16);
|
||||
|
||||
private String protocol = DEFAULT_PROTOCOL;
|
||||
|
||||
private String scheme = DEFAULT_PROTOCOL;
|
||||
|
||||
private String serverName = DEFAULT_SERVER_NAME;
|
||||
|
||||
private int serverPort = DEFAULT_SERVER_PORT;
|
||||
|
||||
private String remoteAddr = DEFAULT_REMOTE_ADDR;
|
||||
|
||||
private String remoteHost = DEFAULT_REMOTE_HOST;
|
||||
|
||||
/** List of locales in descending order */
|
||||
private final List<Locale> locales = new LinkedList<Locale>();
|
||||
|
||||
private boolean secure = false;
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private int remotePort = DEFAULT_SERVER_PORT;
|
||||
|
||||
private String localName = DEFAULT_SERVER_NAME;
|
||||
|
||||
private String localAddr = DEFAULT_SERVER_ADDR;
|
||||
|
||||
private int localPort = DEFAULT_SERVER_PORT;
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// HttpServletRequest properties
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
private String authType;
|
||||
|
||||
private Cookie[] cookies;
|
||||
|
||||
private final Map<String, HeaderValueHolder> headers = new LinkedCaseInsensitiveMap<HeaderValueHolder>();
|
||||
|
||||
private String method;
|
||||
|
||||
private String pathInfo;
|
||||
|
||||
private String contextPath = "";
|
||||
|
||||
private String queryString;
|
||||
|
||||
private String remoteUser;
|
||||
|
||||
private final Set<String> userRoles = new HashSet<String>();
|
||||
|
||||
private Principal userPrincipal;
|
||||
|
||||
private String requestedSessionId;
|
||||
|
||||
private String requestURI;
|
||||
|
||||
private String servletPath = "";
|
||||
|
||||
private HttpSession session;
|
||||
|
||||
private boolean requestedSessionIdValid = true;
|
||||
|
||||
private boolean requestedSessionIdFromCookie = true;
|
||||
|
||||
private boolean requestedSessionIdFromURL = false;
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Constructors
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a new MockHttpServletRequest with a default
|
||||
* {@link org.springframework.mock.web.MockServletContext}.
|
||||
* @see org.springframework.mock.web.MockServletContext
|
||||
*/
|
||||
public MockHttpServletRequest() {
|
||||
this(null, "", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpServletRequest with a default
|
||||
* {@link org.springframework.mock.web.MockServletContext}.
|
||||
* @param method the request method (may be <code>null</code>)
|
||||
* @param requestURI the request URI (may be <code>null</code>)
|
||||
* @see #setMethod
|
||||
* @see #setRequestURI
|
||||
* @see org.springframework.mock.web.MockServletContext
|
||||
*/
|
||||
public MockHttpServletRequest(String method, String requestURI) {
|
||||
this(null, method, requestURI);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpServletRequest.
|
||||
* @param servletContext the ServletContext that the request runs in (may be
|
||||
* <code>null</code> to use a default MockServletContext)
|
||||
* @see org.springframework.mock.web.MockServletContext
|
||||
*/
|
||||
public MockHttpServletRequest(ServletContext servletContext) {
|
||||
this(servletContext, "", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpServletRequest.
|
||||
* @param servletContext the ServletContext that the request runs in (may be
|
||||
* <code>null</code> to use a default MockServletContext)
|
||||
* @param method the request method (may be <code>null</code>)
|
||||
* @param requestURI the request URI (may be <code>null</code>)
|
||||
* @see #setMethod
|
||||
* @see #setRequestURI
|
||||
* @see org.springframework.mock.web.MockServletContext
|
||||
*/
|
||||
public MockHttpServletRequest(ServletContext servletContext, String method, String requestURI) {
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.method = method;
|
||||
this.requestURI = requestURI;
|
||||
this.locales.add(Locale.ENGLISH);
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Lifecycle methods
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Return the ServletContext that this request is associated with. (Not
|
||||
* available in the standard HttpServletRequest interface for some reason.)
|
||||
*/
|
||||
public ServletContext getServletContext() {
|
||||
return this.servletContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether this request is still active (that is, not completed yet).
|
||||
*/
|
||||
public boolean isActive() {
|
||||
return this.active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark this request as completed, keeping its state.
|
||||
*/
|
||||
public void close() {
|
||||
this.active = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate this request, clearing its state.
|
||||
*/
|
||||
public void invalidate() {
|
||||
close();
|
||||
clearAttributes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether this request is still active (that is, not completed yet),
|
||||
* throwing an IllegalStateException if not active anymore.
|
||||
*/
|
||||
protected void checkActive() throws IllegalStateException {
|
||||
if (!this.active) {
|
||||
throw new IllegalStateException("Request is not active anymore");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// ServletRequest interface
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
public Object getAttribute(String name) {
|
||||
checkActive();
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
checkActive();
|
||||
return new Vector<String>(this.attributes.keySet()).elements();
|
||||
}
|
||||
|
||||
public String getCharacterEncoding() {
|
||||
return this.characterEncoding;
|
||||
}
|
||||
|
||||
public void setCharacterEncoding(String characterEncoding) {
|
||||
this.characterEncoding = characterEncoding;
|
||||
updateContentTypeHeader();
|
||||
}
|
||||
|
||||
private void updateContentTypeHeader() {
|
||||
if (this.contentType != null) {
|
||||
StringBuilder sb = new StringBuilder(this.contentType);
|
||||
if (this.contentType.toLowerCase().indexOf(CHARSET_PREFIX) == -1 && this.characterEncoding != null) {
|
||||
sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding);
|
||||
}
|
||||
doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true);
|
||||
}
|
||||
}
|
||||
|
||||
public void setContent(byte[] content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public int getContentLength() {
|
||||
return (this.content != null ? this.content.length : -1);
|
||||
}
|
||||
|
||||
public void setContentType(String contentType) {
|
||||
this.contentType = contentType;
|
||||
if (contentType != null) {
|
||||
int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX);
|
||||
if (charsetIndex != -1) {
|
||||
String encoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length());
|
||||
this.characterEncoding = encoding;
|
||||
}
|
||||
updateContentTypeHeader();
|
||||
}
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return this.contentType;
|
||||
}
|
||||
|
||||
public ServletInputStream getInputStream() {
|
||||
if (this.content != null) {
|
||||
return new DelegatingServletInputStream(new ByteArrayInputStream(this.content));
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a single value for the specified HTTP parameter.
|
||||
* <p>
|
||||
* If there are already one or more values registered for the given
|
||||
* parameter name, they will be replaced.
|
||||
*/
|
||||
public void setParameter(String name, String value) {
|
||||
setParameter(name, new String[] { value });
|
||||
}
|
||||
|
||||
/**
|
||||
* Set an array of values for the specified HTTP parameter.
|
||||
* <p>
|
||||
* If there are already one or more values registered for the given
|
||||
* parameter name, they will be replaced.
|
||||
*/
|
||||
public void setParameter(String name, String[] values) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.parameters.put(name, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets all provided parameters <emphasis>replacing</emphasis> any existing
|
||||
* values for the provided parameter names. To add without replacing
|
||||
* existing values, use {@link #addParameters(java.util.Map)}.
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void setParameters(Map params) {
|
||||
Assert.notNull(params, "Parameter map must not be null");
|
||||
for (Object key : params.keySet()) {
|
||||
Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]");
|
||||
Object value = params.get(key);
|
||||
if (value instanceof String) {
|
||||
this.setParameter((String) key, (String) value);
|
||||
}
|
||||
else if (value instanceof String[]) {
|
||||
this.setParameter((String) key, (String[]) value);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type ["
|
||||
+ String.class.getName() + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a single value for the specified HTTP parameter.
|
||||
* <p>
|
||||
* If there are already one or more values registered for the given
|
||||
* parameter name, the given value will be added to the end of the list.
|
||||
*/
|
||||
public void addParameter(String name, String value) {
|
||||
addParameter(name, new String[] { value });
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an array of values for the specified HTTP parameter.
|
||||
* <p>
|
||||
* If there are already one or more values registered for the given
|
||||
* parameter name, the given values will be added to the end of the list.
|
||||
*/
|
||||
public void addParameter(String name, String[] values) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
String[] oldArr = this.parameters.get(name);
|
||||
if (oldArr != null) {
|
||||
String[] newArr = new String[oldArr.length + values.length];
|
||||
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
|
||||
System.arraycopy(values, 0, newArr, oldArr.length, values.length);
|
||||
this.parameters.put(name, newArr);
|
||||
}
|
||||
else {
|
||||
this.parameters.put(name, values);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all provided parameters <emphasis>without</emphasis> replacing any
|
||||
* existing values. To replace existing values, use
|
||||
* {@link #setParameters(java.util.Map)}.
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void addParameters(Map params) {
|
||||
Assert.notNull(params, "Parameter map must not be null");
|
||||
for (Object key : params.keySet()) {
|
||||
Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]");
|
||||
Object value = params.get(key);
|
||||
if (value instanceof String) {
|
||||
this.addParameter((String) key, (String) value);
|
||||
}
|
||||
else if (value instanceof String[]) {
|
||||
this.addParameter((String) key, (String[]) value);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type ["
|
||||
+ String.class.getName() + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove already registered values for the specified HTTP parameter, if
|
||||
* any.
|
||||
*/
|
||||
public void removeParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.parameters.remove(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all existing parameters.
|
||||
*/
|
||||
public void removeAllParameters() {
|
||||
this.parameters.clear();
|
||||
}
|
||||
|
||||
public String getParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
String[] arr = this.parameters.get(name);
|
||||
return (arr != null && arr.length > 0 ? arr[0] : null);
|
||||
}
|
||||
|
||||
public Enumeration<String> getParameterNames() {
|
||||
return Collections.enumeration(this.parameters.keySet());
|
||||
}
|
||||
|
||||
public String[] getParameterValues(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
return this.parameters.get(name);
|
||||
}
|
||||
|
||||
public Map<String, String[]> getParameterMap() {
|
||||
return Collections.unmodifiableMap(this.parameters);
|
||||
}
|
||||
|
||||
public void setProtocol(String protocol) {
|
||||
this.protocol = protocol;
|
||||
}
|
||||
|
||||
public String getProtocol() {
|
||||
return this.protocol;
|
||||
}
|
||||
|
||||
public void setScheme(String scheme) {
|
||||
this.scheme = scheme;
|
||||
}
|
||||
|
||||
public String getScheme() {
|
||||
return this.scheme;
|
||||
}
|
||||
|
||||
public void setServerName(String serverName) {
|
||||
this.serverName = serverName;
|
||||
}
|
||||
|
||||
public String getServerName() {
|
||||
return this.serverName;
|
||||
}
|
||||
|
||||
public void setServerPort(int serverPort) {
|
||||
this.serverPort = serverPort;
|
||||
}
|
||||
|
||||
public int getServerPort() {
|
||||
return this.serverPort;
|
||||
}
|
||||
|
||||
public BufferedReader getReader() throws UnsupportedEncodingException {
|
||||
if (this.content != null) {
|
||||
InputStream sourceStream = new ByteArrayInputStream(this.content);
|
||||
Reader sourceReader = (this.characterEncoding != null) ? new InputStreamReader(sourceStream,
|
||||
this.characterEncoding) : new InputStreamReader(sourceStream);
|
||||
return new BufferedReader(sourceReader);
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void setRemoteAddr(String remoteAddr) {
|
||||
this.remoteAddr = remoteAddr;
|
||||
}
|
||||
|
||||
public String getRemoteAddr() {
|
||||
return this.remoteAddr;
|
||||
}
|
||||
|
||||
public void setRemoteHost(String remoteHost) {
|
||||
this.remoteHost = remoteHost;
|
||||
}
|
||||
|
||||
public String getRemoteHost() {
|
||||
return this.remoteHost;
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object value) {
|
||||
checkActive();
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
if (value != null) {
|
||||
this.attributes.put(name, value);
|
||||
}
|
||||
else {
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAttribute(String name) {
|
||||
checkActive();
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all of this request's attributes.
|
||||
*/
|
||||
public void clearAttributes() {
|
||||
this.attributes.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new preferred locale, before any existing locales.
|
||||
*/
|
||||
public void addPreferredLocale(Locale locale) {
|
||||
Assert.notNull(locale, "Locale must not be null");
|
||||
this.locales.add(0, locale);
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
return this.locales.get(0);
|
||||
}
|
||||
|
||||
public Enumeration<Locale> getLocales() {
|
||||
return Collections.enumeration(this.locales);
|
||||
}
|
||||
|
||||
public void setSecure(boolean secure) {
|
||||
this.secure = secure;
|
||||
}
|
||||
|
||||
public boolean isSecure() {
|
||||
return this.secure;
|
||||
}
|
||||
|
||||
public RequestDispatcher getRequestDispatcher(String path) {
|
||||
return new MockRequestDispatcher(path);
|
||||
}
|
||||
|
||||
public String getRealPath(String path) {
|
||||
return this.servletContext.getRealPath(path);
|
||||
}
|
||||
|
||||
public void setRemotePort(int remotePort) {
|
||||
this.remotePort = remotePort;
|
||||
}
|
||||
|
||||
public int getRemotePort() {
|
||||
return this.remotePort;
|
||||
}
|
||||
|
||||
public void setLocalName(String localName) {
|
||||
this.localName = localName;
|
||||
}
|
||||
|
||||
public String getLocalName() {
|
||||
return this.localName;
|
||||
}
|
||||
|
||||
public void setLocalAddr(String localAddr) {
|
||||
this.localAddr = localAddr;
|
||||
}
|
||||
|
||||
public String getLocalAddr() {
|
||||
return this.localAddr;
|
||||
}
|
||||
|
||||
public void setLocalPort(int localPort) {
|
||||
this.localPort = localPort;
|
||||
}
|
||||
|
||||
public int getLocalPort() {
|
||||
return this.localPort;
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// HttpServletRequest interface
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
public void setAuthType(String authType) {
|
||||
this.authType = authType;
|
||||
}
|
||||
|
||||
public String getAuthType() {
|
||||
return this.authType;
|
||||
}
|
||||
|
||||
public void setCookies(Cookie... cookies) {
|
||||
this.cookies = cookies;
|
||||
}
|
||||
|
||||
public Cookie[] getCookies() {
|
||||
return this.cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a header entry for the given name.
|
||||
* <p>If there was no entry for that header name before, the value will be used
|
||||
* as-is. In case of an existing entry, a String array will be created,
|
||||
* adding the given value (more specifically, its toString representation)
|
||||
* as further element.
|
||||
* <p>Multiple values can only be stored as list of Strings, following the
|
||||
* Servlet spec (see <code>getHeaders</code> accessor). As alternative to
|
||||
* repeated <code>addHeader</code> calls for individual elements, you can
|
||||
* use a single call with an entire array or Collection of values as
|
||||
* parameter.
|
||||
* @see #getHeaderNames
|
||||
* @see #getHeader
|
||||
* @see #getHeaders
|
||||
* @see #getDateHeader
|
||||
* @see #getIntHeader
|
||||
*/
|
||||
public void addHeader(String name, Object value) {
|
||||
if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) {
|
||||
setContentType((String) value);
|
||||
return;
|
||||
}
|
||||
doAddHeaderValue(name, value, false);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private void doAddHeaderValue(String name, Object value, boolean replace) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
Assert.notNull(value, "Header value must not be null");
|
||||
if (header == null || replace) {
|
||||
header = new HeaderValueHolder();
|
||||
this.headers.put(name, header);
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
header.addValues((Collection) value);
|
||||
}
|
||||
else if (value.getClass().isArray()) {
|
||||
header.addValueArray(value);
|
||||
}
|
||||
else {
|
||||
header.addValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
public long getDateHeader(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
Object value = (header != null ? header.getValue() : null);
|
||||
if (value instanceof Date) {
|
||||
return ((Date) value).getTime();
|
||||
}
|
||||
else if (value instanceof Number) {
|
||||
return ((Number) value).longValue();
|
||||
}
|
||||
else if (value != null) {
|
||||
throw new IllegalArgumentException("Value for header '" + name + "' is neither a Date nor a Number: "
|
||||
+ value);
|
||||
}
|
||||
else {
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
public int getIntHeader(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
Object value = (header != null ? header.getValue() : null);
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
else if (value instanceof String) {
|
||||
return Integer.parseInt((String) value);
|
||||
}
|
||||
else if (value != null) {
|
||||
throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value);
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public String getHeader(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
return (header != null ? header.getStringValue() : null);
|
||||
}
|
||||
|
||||
public Enumeration<String> getHeaders(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
return Collections.enumeration(header != null ? header.getStringValues() : new LinkedList<String>());
|
||||
}
|
||||
|
||||
public Enumeration<String> getHeaderNames() {
|
||||
return Collections.enumeration(this.headers.keySet());
|
||||
}
|
||||
|
||||
public void setMethod(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return this.method;
|
||||
}
|
||||
|
||||
public void setPathInfo(String pathInfo) {
|
||||
this.pathInfo = pathInfo;
|
||||
}
|
||||
|
||||
public String getPathInfo() {
|
||||
return this.pathInfo;
|
||||
}
|
||||
|
||||
public String getPathTranslated() {
|
||||
return (this.pathInfo != null ? getRealPath(this.pathInfo) : null);
|
||||
}
|
||||
|
||||
public void setContextPath(String contextPath) {
|
||||
this.contextPath = contextPath;
|
||||
}
|
||||
|
||||
public String getContextPath() {
|
||||
return this.contextPath;
|
||||
}
|
||||
|
||||
public void setQueryString(String queryString) {
|
||||
this.queryString = queryString;
|
||||
}
|
||||
|
||||
public String getQueryString() {
|
||||
return this.queryString;
|
||||
}
|
||||
|
||||
public void setRemoteUser(String remoteUser) {
|
||||
this.remoteUser = remoteUser;
|
||||
}
|
||||
|
||||
public String getRemoteUser() {
|
||||
return this.remoteUser;
|
||||
}
|
||||
|
||||
public void addUserRole(String role) {
|
||||
this.userRoles.add(role);
|
||||
}
|
||||
|
||||
public boolean isUserInRole(String role) {
|
||||
return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext &&
|
||||
((MockServletContext) this.servletContext).getDeclaredRoles().contains(role)));
|
||||
}
|
||||
|
||||
public void setUserPrincipal(Principal userPrincipal) {
|
||||
this.userPrincipal = userPrincipal;
|
||||
}
|
||||
|
||||
public Principal getUserPrincipal() {
|
||||
return this.userPrincipal;
|
||||
}
|
||||
|
||||
public void setRequestedSessionId(String requestedSessionId) {
|
||||
this.requestedSessionId = requestedSessionId;
|
||||
}
|
||||
|
||||
public String getRequestedSessionId() {
|
||||
return this.requestedSessionId;
|
||||
}
|
||||
|
||||
public void setRequestURI(String requestURI) {
|
||||
this.requestURI = requestURI;
|
||||
}
|
||||
|
||||
public String getRequestURI() {
|
||||
return this.requestURI;
|
||||
}
|
||||
|
||||
public StringBuffer getRequestURL() {
|
||||
StringBuffer url = new StringBuffer(this.scheme);
|
||||
url.append("://").append(this.serverName).append(':').append(this.serverPort);
|
||||
url.append(getRequestURI());
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setServletPath(String servletPath) {
|
||||
this.servletPath = servletPath;
|
||||
}
|
||||
|
||||
public String getServletPath() {
|
||||
return this.servletPath;
|
||||
}
|
||||
|
||||
public void setSession(HttpSession session) {
|
||||
this.session = session;
|
||||
if (session instanceof MockHttpSession) {
|
||||
MockHttpSession mockSession = ((MockHttpSession) session);
|
||||
mockSession.access();
|
||||
}
|
||||
}
|
||||
|
||||
public HttpSession getSession(boolean create) {
|
||||
checkActive();
|
||||
// Reset session if invalidated.
|
||||
if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) {
|
||||
this.session = null;
|
||||
}
|
||||
// Create new session if necessary.
|
||||
if (this.session == null && create) {
|
||||
this.session = new MockHttpSession(this.servletContext);
|
||||
}
|
||||
return this.session;
|
||||
}
|
||||
|
||||
public HttpSession getSession() {
|
||||
return getSession(true);
|
||||
}
|
||||
|
||||
public void setRequestedSessionIdValid(boolean requestedSessionIdValid) {
|
||||
this.requestedSessionIdValid = requestedSessionIdValid;
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdValid() {
|
||||
return this.requestedSessionIdValid;
|
||||
}
|
||||
|
||||
public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) {
|
||||
this.requestedSessionIdFromCookie = requestedSessionIdFromCookie;
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromCookie() {
|
||||
return this.requestedSessionIdFromCookie;
|
||||
}
|
||||
|
||||
public void setRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) {
|
||||
this.requestedSessionIdFromURL = requestedSessionIdFromURL;
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromURL() {
|
||||
return this.requestedSessionIdFromURL;
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromUrl() {
|
||||
return isRequestedSessionIdFromURL();
|
||||
}
|
||||
|
||||
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
|
||||
return (this.userPrincipal != null && this.remoteUser != null && this.authType != null);
|
||||
}
|
||||
|
||||
public void login(String username, String password) throws ServletException {
|
||||
throw new ServletException("Username-password authentication not supported - override the login method");
|
||||
}
|
||||
|
||||
public void logout() throws ServletException {
|
||||
this.userPrincipal = null;
|
||||
this.remoteUser = null;
|
||||
this.authType = null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.io.Writer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.LinkedCaseInsensitiveMap;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.http.HttpServletResponse} interface.
|
||||
*
|
||||
* <p>Compatible with Servlet 2.5 as well as Servlet 3.0.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockHttpServletResponse implements HttpServletResponse {
|
||||
|
||||
private static final String CHARSET_PREFIX = "charset=";
|
||||
|
||||
private static final String CONTENT_TYPE_HEADER = "Content-Type";
|
||||
|
||||
private static final String CONTENT_LENGTH_HEADER = "Content-Length";
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// ServletResponse properties
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
private boolean outputStreamAccessAllowed = true;
|
||||
|
||||
private boolean writerAccessAllowed = true;
|
||||
|
||||
private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
|
||||
|
||||
private boolean charset = false;
|
||||
|
||||
private final ByteArrayOutputStream content = new ByteArrayOutputStream();
|
||||
|
||||
private final ServletOutputStream outputStream = new ResponseServletOutputStream(this.content);
|
||||
|
||||
private PrintWriter writer;
|
||||
|
||||
private int contentLength = 0;
|
||||
|
||||
private String contentType;
|
||||
|
||||
private int bufferSize = 4096;
|
||||
|
||||
private boolean committed;
|
||||
|
||||
private Locale locale = Locale.getDefault();
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// HttpServletResponse properties
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
private final List<Cookie> cookies = new ArrayList<Cookie>();
|
||||
|
||||
private final Map<String, HeaderValueHolder> headers = new LinkedCaseInsensitiveMap<HeaderValueHolder>();
|
||||
|
||||
private int status = HttpServletResponse.SC_OK;
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
private String redirectedUrl;
|
||||
|
||||
private String forwardedUrl;
|
||||
|
||||
private final List<String> includedUrls = new ArrayList<String>();
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// ServletResponse interface
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Set whether {@link #getOutputStream()} access is allowed.
|
||||
* <p>Default is <code>true</code>.
|
||||
*/
|
||||
public void setOutputStreamAccessAllowed(boolean outputStreamAccessAllowed) {
|
||||
this.outputStreamAccessAllowed = outputStreamAccessAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether {@link #getOutputStream()} access is allowed.
|
||||
*/
|
||||
public boolean isOutputStreamAccessAllowed() {
|
||||
return this.outputStreamAccessAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether {@link #getWriter()} access is allowed.
|
||||
* <p>Default is <code>true</code>.
|
||||
*/
|
||||
public void setWriterAccessAllowed(boolean writerAccessAllowed) {
|
||||
this.writerAccessAllowed = writerAccessAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether {@link #getOutputStream()} access is allowed.
|
||||
*/
|
||||
public boolean isWriterAccessAllowed() {
|
||||
return this.writerAccessAllowed;
|
||||
}
|
||||
|
||||
public void setCharacterEncoding(String characterEncoding) {
|
||||
this.characterEncoding = characterEncoding;
|
||||
this.charset = true;
|
||||
updateContentTypeHeader();
|
||||
}
|
||||
|
||||
private void updateContentTypeHeader() {
|
||||
if (this.contentType != null) {
|
||||
StringBuilder sb = new StringBuilder(this.contentType);
|
||||
if (this.contentType.toLowerCase().indexOf(CHARSET_PREFIX) == -1 && this.charset) {
|
||||
sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding);
|
||||
}
|
||||
doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true);
|
||||
}
|
||||
}
|
||||
|
||||
public String getCharacterEncoding() {
|
||||
return this.characterEncoding;
|
||||
}
|
||||
|
||||
public ServletOutputStream getOutputStream() {
|
||||
if (!this.outputStreamAccessAllowed) {
|
||||
throw new IllegalStateException("OutputStream access not allowed");
|
||||
}
|
||||
return this.outputStream;
|
||||
}
|
||||
|
||||
public PrintWriter getWriter() throws UnsupportedEncodingException {
|
||||
if (!this.writerAccessAllowed) {
|
||||
throw new IllegalStateException("Writer access not allowed");
|
||||
}
|
||||
if (this.writer == null) {
|
||||
Writer targetWriter = (this.characterEncoding != null ?
|
||||
new OutputStreamWriter(this.content, this.characterEncoding) : new OutputStreamWriter(this.content));
|
||||
this.writer = new ResponsePrintWriter(targetWriter);
|
||||
}
|
||||
return this.writer;
|
||||
}
|
||||
|
||||
public byte[] getContentAsByteArray() {
|
||||
flushBuffer();
|
||||
return this.content.toByteArray();
|
||||
}
|
||||
|
||||
public String getContentAsString() throws UnsupportedEncodingException {
|
||||
flushBuffer();
|
||||
return (this.characterEncoding != null) ?
|
||||
this.content.toString(this.characterEncoding) : this.content.toString();
|
||||
}
|
||||
|
||||
public void setContentLength(int contentLength) {
|
||||
this.contentLength = contentLength;
|
||||
doAddHeaderValue(CONTENT_LENGTH_HEADER, contentLength, true);
|
||||
}
|
||||
|
||||
public int getContentLength() {
|
||||
return this.contentLength;
|
||||
}
|
||||
|
||||
public void setContentType(String contentType) {
|
||||
this.contentType = contentType;
|
||||
if (contentType != null) {
|
||||
int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX);
|
||||
if (charsetIndex != -1) {
|
||||
String encoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length());
|
||||
this.characterEncoding = encoding;
|
||||
this.charset = true;
|
||||
}
|
||||
updateContentTypeHeader();
|
||||
}
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return this.contentType;
|
||||
}
|
||||
|
||||
public void setBufferSize(int bufferSize) {
|
||||
this.bufferSize = bufferSize;
|
||||
}
|
||||
|
||||
public int getBufferSize() {
|
||||
return this.bufferSize;
|
||||
}
|
||||
|
||||
public void flushBuffer() {
|
||||
setCommitted(true);
|
||||
}
|
||||
|
||||
public void resetBuffer() {
|
||||
if (isCommitted()) {
|
||||
throw new IllegalStateException("Cannot reset buffer - response is already committed");
|
||||
}
|
||||
this.content.reset();
|
||||
}
|
||||
|
||||
private void setCommittedIfBufferSizeExceeded() {
|
||||
int bufSize = getBufferSize();
|
||||
if (bufSize > 0 && this.content.size() > bufSize) {
|
||||
setCommitted(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void setCommitted(boolean committed) {
|
||||
this.committed = committed;
|
||||
}
|
||||
|
||||
public boolean isCommitted() {
|
||||
return this.committed;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
resetBuffer();
|
||||
this.characterEncoding = null;
|
||||
this.contentLength = 0;
|
||||
this.contentType = null;
|
||||
this.locale = null;
|
||||
this.cookies.clear();
|
||||
this.headers.clear();
|
||||
this.status = HttpServletResponse.SC_OK;
|
||||
this.errorMessage = null;
|
||||
}
|
||||
|
||||
public void setLocale(Locale locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
return this.locale;
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// HttpServletResponse interface
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public void addCookie(Cookie cookie) {
|
||||
Assert.notNull(cookie, "Cookie must not be null");
|
||||
this.cookies.add(cookie);
|
||||
}
|
||||
|
||||
public Cookie[] getCookies() {
|
||||
return this.cookies.toArray(new Cookie[this.cookies.size()]);
|
||||
}
|
||||
|
||||
public Cookie getCookie(String name) {
|
||||
Assert.notNull(name, "Cookie name must not be null");
|
||||
for (Cookie cookie : this.cookies) {
|
||||
if (name.equals(cookie.getName())) {
|
||||
return cookie;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean containsHeader(String name) {
|
||||
return (HeaderValueHolder.getByName(this.headers, name) != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the names of all specified headers as a Set of Strings.
|
||||
* <p>As of Servlet 3.0, this method is also defined HttpServletResponse.
|
||||
* @return the <code>Set</code> of header name <code>Strings</code>, or an empty <code>Set</code> if none
|
||||
*/
|
||||
public Set<String> getHeaderNames() {
|
||||
return this.headers.keySet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the primary value for the given header as a String, if any.
|
||||
* Will return the first value in case of multiple values.
|
||||
* <p>As of Servlet 3.0, this method is also defined HttpServletResponse.
|
||||
* As of Spring 3.1, it returns a stringified value for Servlet 3.0 compatibility.
|
||||
* Consider using {@link #getHeaderValue(String)} for raw Object access.
|
||||
* @param name the name of the header
|
||||
* @return the associated header value, or <code>null<code> if none
|
||||
*/
|
||||
public String getHeader(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
return (header != null ? header.getStringValue() : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all values for the given header as a List of Strings.
|
||||
* <p>As of Servlet 3.0, this method is also defined HttpServletResponse.
|
||||
* As of Spring 3.1, it returns a List of stringified values for Servlet 3.0 compatibility.
|
||||
* Consider using {@link #getHeaderValues(String)} for raw Object access.
|
||||
* @param name the name of the header
|
||||
* @return the associated header values, or an empty List if none
|
||||
*/
|
||||
public List<String> getHeaders(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
if (header != null) {
|
||||
return header.getStringValues();
|
||||
}
|
||||
else {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the primary value for the given header, if any.
|
||||
* <p>Will return the first value in case of multiple values.
|
||||
* @param name the name of the header
|
||||
* @return the associated header value, or <code>null<code> if none
|
||||
*/
|
||||
public Object getHeaderValue(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
return (header != null ? header.getValue() : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all values for the given header as a List of value objects.
|
||||
* @param name the name of the header
|
||||
* @return the associated header values, or an empty List if none
|
||||
*/
|
||||
public List<Object> getHeaderValues(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
if (header != null) {
|
||||
return header.getValues();
|
||||
}
|
||||
else {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The default implementation returns the given URL String as-is.
|
||||
* <p>Can be overridden in subclasses, appending a session id or the like.
|
||||
*/
|
||||
public String encodeURL(String url) {
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default implementation delegates to {@link #encodeURL},
|
||||
* returning the given URL String as-is.
|
||||
* <p>Can be overridden in subclasses, appending a session id or the like
|
||||
* in a redirect-specific fashion. For general URL encoding rules,
|
||||
* override the common {@link #encodeURL} method instead, appyling
|
||||
* to redirect URLs as well as to general URLs.
|
||||
*/
|
||||
public String encodeRedirectURL(String url) {
|
||||
return encodeURL(url);
|
||||
}
|
||||
|
||||
public String encodeUrl(String url) {
|
||||
return encodeURL(url);
|
||||
}
|
||||
|
||||
public String encodeRedirectUrl(String url) {
|
||||
return encodeRedirectURL(url);
|
||||
}
|
||||
|
||||
public void sendError(int status, String errorMessage) throws IOException {
|
||||
if (isCommitted()) {
|
||||
throw new IllegalStateException("Cannot set error status - response is already committed");
|
||||
}
|
||||
this.status = status;
|
||||
this.errorMessage = errorMessage;
|
||||
setCommitted(true);
|
||||
}
|
||||
|
||||
public void sendError(int status) throws IOException {
|
||||
if (isCommitted()) {
|
||||
throw new IllegalStateException("Cannot set error status - response is already committed");
|
||||
}
|
||||
this.status = status;
|
||||
setCommitted(true);
|
||||
}
|
||||
|
||||
public void sendRedirect(String url) throws IOException {
|
||||
if (isCommitted()) {
|
||||
throw new IllegalStateException("Cannot send redirect - response is already committed");
|
||||
}
|
||||
Assert.notNull(url, "Redirect URL must not be null");
|
||||
this.redirectedUrl = url;
|
||||
setCommitted(true);
|
||||
}
|
||||
|
||||
public String getRedirectedUrl() {
|
||||
return this.redirectedUrl;
|
||||
}
|
||||
|
||||
public void setDateHeader(String name, long value) {
|
||||
setHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void addDateHeader(String name, long value) {
|
||||
addHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void setHeader(String name, String value) {
|
||||
setHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void addHeader(String name, String value) {
|
||||
addHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void setIntHeader(String name, int value) {
|
||||
setHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void addIntHeader(String name, int value) {
|
||||
addHeaderValue(name, value);
|
||||
}
|
||||
|
||||
private void setHeaderValue(String name, Object value) {
|
||||
if (setSpecialHeader(name, value)) {
|
||||
return;
|
||||
}
|
||||
doAddHeaderValue(name, value, true);
|
||||
}
|
||||
|
||||
private void addHeaderValue(String name, Object value) {
|
||||
if (setSpecialHeader(name, value)) {
|
||||
return;
|
||||
}
|
||||
doAddHeaderValue(name, value, false);
|
||||
}
|
||||
|
||||
private boolean setSpecialHeader(String name, Object value) {
|
||||
if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) {
|
||||
setContentType((String) value);
|
||||
return true;
|
||||
}
|
||||
else if (CONTENT_LENGTH_HEADER.equalsIgnoreCase(name)) {
|
||||
setContentLength(Integer.parseInt((String) value));
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void doAddHeaderValue(String name, Object value, boolean replace) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
Assert.notNull(value, "Header value must not be null");
|
||||
if (header == null) {
|
||||
header = new HeaderValueHolder();
|
||||
this.headers.put(name, header);
|
||||
}
|
||||
if (replace) {
|
||||
header.setValue(value);
|
||||
}
|
||||
else {
|
||||
header.addValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public void setStatus(int status, String errorMessage) {
|
||||
this.status = status;
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return this.errorMessage;
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// Methods for MockRequestDispatcher
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public void setForwardedUrl(String forwardedUrl) {
|
||||
this.forwardedUrl = forwardedUrl;
|
||||
}
|
||||
|
||||
public String getForwardedUrl() {
|
||||
return this.forwardedUrl;
|
||||
}
|
||||
|
||||
public void setIncludedUrl(String includedUrl) {
|
||||
this.includedUrls.clear();
|
||||
if (includedUrl != null) {
|
||||
this.includedUrls.add(includedUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public String getIncludedUrl() {
|
||||
int count = this.includedUrls.size();
|
||||
if (count > 1) {
|
||||
throw new IllegalStateException(
|
||||
"More than 1 URL included - check getIncludedUrls instead: " + this.includedUrls);
|
||||
}
|
||||
return (count == 1 ? this.includedUrls.get(0) : null);
|
||||
}
|
||||
|
||||
public void addIncludedUrl(String includedUrl) {
|
||||
Assert.notNull(includedUrl, "Included URL must not be null");
|
||||
this.includedUrls.add(includedUrl);
|
||||
}
|
||||
|
||||
public List<String> getIncludedUrls() {
|
||||
return this.includedUrls;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inner class that adapts the ServletOutputStream to mark the
|
||||
* response as committed once the buffer size is exceeded.
|
||||
*/
|
||||
private class ResponseServletOutputStream extends DelegatingServletOutputStream {
|
||||
|
||||
public ResponseServletOutputStream(OutputStream out) {
|
||||
super(out);
|
||||
}
|
||||
|
||||
public void write(int b) throws IOException {
|
||||
super.write(b);
|
||||
super.flush();
|
||||
setCommittedIfBufferSizeExceeded();
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
super.flush();
|
||||
setCommitted(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inner class that adapts the PrintWriter to mark the
|
||||
* response as committed once the buffer size is exceeded.
|
||||
*/
|
||||
private class ResponsePrintWriter extends PrintWriter {
|
||||
|
||||
public ResponsePrintWriter(Writer out) {
|
||||
super(out, true);
|
||||
}
|
||||
|
||||
public void write(char buf[], int off, int len) {
|
||||
super.write(buf, off, len);
|
||||
super.flush();
|
||||
setCommittedIfBufferSizeExceeded();
|
||||
}
|
||||
|
||||
public void write(String s, int off, int len) {
|
||||
super.write(s, off, len);
|
||||
super.flush();
|
||||
setCommittedIfBufferSizeExceeded();
|
||||
}
|
||||
|
||||
public void write(int c) {
|
||||
super.write(c);
|
||||
super.flush();
|
||||
setCommittedIfBufferSizeExceeded();
|
||||
}
|
||||
|
||||
public void flush() {
|
||||
super.flush();
|
||||
setCommitted(true);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Vector;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.servlet.http.HttpSessionBindingEvent;
|
||||
import javax.servlet.http.HttpSessionBindingListener;
|
||||
import javax.servlet.http.HttpSessionContext;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.http.HttpSession} interface.
|
||||
*
|
||||
* <p>Compatible with Servlet 2.5 as well as Servlet 3.0.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
* @author Mark Fisher
|
||||
* @since 1.0.2
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public class MockHttpSession implements HttpSession {
|
||||
|
||||
private static int nextId = 1;
|
||||
|
||||
private final String id;
|
||||
|
||||
private final long creationTime = System.currentTimeMillis();
|
||||
|
||||
private int maxInactiveInterval;
|
||||
|
||||
private long lastAccessedTime = System.currentTimeMillis();
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
|
||||
|
||||
private boolean invalid = false;
|
||||
|
||||
private boolean isNew = true;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockHttpSession with a default {@link org.springframework.mock.web.MockServletContext}.
|
||||
*
|
||||
* @see org.springframework.mock.web.MockServletContext
|
||||
*/
|
||||
public MockHttpSession() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpSession.
|
||||
*
|
||||
* @param servletContext the ServletContext that the session runs in
|
||||
*/
|
||||
public MockHttpSession(ServletContext servletContext) {
|
||||
this(servletContext, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpSession.
|
||||
*
|
||||
* @param servletContext the ServletContext that the session runs in
|
||||
* @param id a unique identifier for this session
|
||||
*/
|
||||
public MockHttpSession(ServletContext servletContext, String id) {
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.id = (id != null ? id : Integer.toString(nextId++));
|
||||
}
|
||||
|
||||
public long getCreationTime() {
|
||||
return this.creationTime;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void access() {
|
||||
this.lastAccessedTime = System.currentTimeMillis();
|
||||
this.isNew = false;
|
||||
}
|
||||
|
||||
public long getLastAccessedTime() {
|
||||
return this.lastAccessedTime;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return this.servletContext;
|
||||
}
|
||||
|
||||
public void setMaxInactiveInterval(int interval) {
|
||||
this.maxInactiveInterval = interval;
|
||||
}
|
||||
|
||||
public int getMaxInactiveInterval() {
|
||||
return this.maxInactiveInterval;
|
||||
}
|
||||
|
||||
public HttpSessionContext getSessionContext() {
|
||||
throw new UnsupportedOperationException("getSessionContext");
|
||||
}
|
||||
|
||||
public Object getAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
public Object getValue(String name) {
|
||||
return getAttribute(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
return new Vector<String>(this.attributes.keySet()).elements();
|
||||
}
|
||||
|
||||
public String[] getValueNames() {
|
||||
return this.attributes.keySet().toArray(new String[this.attributes.size()]);
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object value) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
if (value != null) {
|
||||
this.attributes.put(name, value);
|
||||
if (value instanceof HttpSessionBindingListener) {
|
||||
((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
|
||||
}
|
||||
}
|
||||
else {
|
||||
removeAttribute(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void putValue(String name, Object value) {
|
||||
setAttribute(name, value);
|
||||
}
|
||||
|
||||
public void removeAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
Object value = this.attributes.remove(name);
|
||||
if (value instanceof HttpSessionBindingListener) {
|
||||
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
|
||||
}
|
||||
}
|
||||
|
||||
public void removeValue(String name) {
|
||||
removeAttribute(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all of this session's attributes.
|
||||
*/
|
||||
public void clearAttributes() {
|
||||
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
|
||||
Map.Entry<String, Object> entry = it.next();
|
||||
String name = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
it.remove();
|
||||
if (value instanceof HttpSessionBindingListener) {
|
||||
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void invalidate() {
|
||||
this.invalid = true;
|
||||
clearAttributes();
|
||||
}
|
||||
|
||||
public boolean isInvalid() {
|
||||
return this.invalid;
|
||||
}
|
||||
|
||||
public void setNew(boolean value) {
|
||||
this.isNew = value;
|
||||
}
|
||||
|
||||
public boolean isNew() {
|
||||
return this.isNew;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the attributes of this session into an object that can be
|
||||
* turned into a byte array with standard Java serialization.
|
||||
*
|
||||
* @return a representation of this session's serialized state
|
||||
*/
|
||||
public Serializable serializeState() {
|
||||
HashMap<String, Serializable> state = new HashMap<String, Serializable>();
|
||||
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
|
||||
Map.Entry<String, Object> entry = it.next();
|
||||
String name = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
it.remove();
|
||||
if (value instanceof Serializable) {
|
||||
state.put(name, (Serializable) value);
|
||||
}
|
||||
else {
|
||||
// Not serializable... Servlet containers usually automatically
|
||||
// unbind the attribute in this case.
|
||||
if (value instanceof HttpSessionBindingListener) {
|
||||
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize the attributes of this session from a state object created by
|
||||
* {@link #serializeState()}.
|
||||
*
|
||||
* @param state a representation of this session's serialized state
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void deserializeState(Serializable state) {
|
||||
Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]");
|
||||
this.attributes.putAll((Map<String, Object>) state);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletResponseWrapper;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.RequestDispatcher} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; typically not necessary for
|
||||
* testing application controllers.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockRequestDispatcher implements RequestDispatcher {
|
||||
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final String url;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockRequestDispatcher for the given URL.
|
||||
* @param url the URL to dispatch to.
|
||||
*/
|
||||
public MockRequestDispatcher(String url) {
|
||||
Assert.notNull(url, "URL must not be null");
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
|
||||
public void forward(ServletRequest request, ServletResponse response) {
|
||||
Assert.notNull(request, "Request must not be null");
|
||||
Assert.notNull(response, "Response must not be null");
|
||||
if (response.isCommitted()) {
|
||||
throw new IllegalStateException("Cannot perform forward - response is already committed");
|
||||
}
|
||||
getMockHttpServletResponse(response).setForwardedUrl(this.url);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("MockRequestDispatcher: forwarding to URL [" + this.url + "]");
|
||||
}
|
||||
}
|
||||
|
||||
public void include(ServletRequest request, ServletResponse response) {
|
||||
Assert.notNull(request, "Request must not be null");
|
||||
Assert.notNull(response, "Response must not be null");
|
||||
getMockHttpServletResponse(response).addIncludedUrl(this.url);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("MockRequestDispatcher: including URL [" + this.url + "]");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the underlying MockHttpServletResponse,
|
||||
* unwrapping {@link javax.servlet.http.HttpServletResponseWrapper} decorators if necessary.
|
||||
*/
|
||||
protected MockHttpServletResponse getMockHttpServletResponse(ServletResponse response) {
|
||||
if (response instanceof MockHttpServletResponse) {
|
||||
return (MockHttpServletResponse) response;
|
||||
}
|
||||
if (response instanceof HttpServletResponseWrapper) {
|
||||
return getMockHttpServletResponse(((HttpServletResponseWrapper) response).getResponse());
|
||||
}
|
||||
throw new IllegalArgumentException("MockRequestDispatcher requires MockHttpServletResponse");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.ServletConfig} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; typically not necessary for
|
||||
* testing application controllers.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockServletConfig implements ServletConfig {
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private final String servletName;
|
||||
|
||||
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockServletConfig with a default {@link org.springframework.mock.web.MockServletContext}.
|
||||
*/
|
||||
public MockServletConfig() {
|
||||
this(null, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletConfig with a default {@link org.springframework.mock.web.MockServletContext}.
|
||||
* @param servletName the name of the servlet
|
||||
*/
|
||||
public MockServletConfig(String servletName) {
|
||||
this(null, servletName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletConfig.
|
||||
* @param servletContext the ServletContext that the servlet runs in
|
||||
*/
|
||||
public MockServletConfig(ServletContext servletContext) {
|
||||
this(servletContext, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletConfig.
|
||||
* @param servletContext the ServletContext that the servlet runs in
|
||||
* @param servletName the name of the servlet
|
||||
*/
|
||||
public MockServletConfig(ServletContext servletContext, String servletName) {
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.servletName = servletName;
|
||||
}
|
||||
|
||||
|
||||
public String getServletName() {
|
||||
return this.servletName;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return this.servletContext;
|
||||
}
|
||||
|
||||
public void addInitParameter(String name, String value) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.initParameters.put(name, value);
|
||||
}
|
||||
|
||||
public String getInitParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
return this.initParameters.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getInitParameterNames() {
|
||||
return Collections.enumeration(this.initParameters.keySet());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Vector;
|
||||
import javax.activation.FileTypeMap;
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.core.io.DefaultResourceLoader;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.ServletContext} interface.
|
||||
*
|
||||
* <p>Compatible with Servlet 2.5 and partially with Servlet 3.0. Can be configured to
|
||||
* expose a specific version through {@link #setMajorVersion}/{@link #setMinorVersion};
|
||||
* default is 2.5. Note that Servlet 3.0 support is limited: servlet, filter and listener
|
||||
* registration methods are not supported; neither is cookie or JSP configuration.
|
||||
* We generally do not recommend to unit-test your ServletContainerInitializers and
|
||||
* WebApplicationInitializers which is where those registration methods would be used.
|
||||
*
|
||||
* <p>Used for testing the Spring web framework; only rarely necessary for testing
|
||||
* application controllers. As long as application components don't explicitly
|
||||
* access the ServletContext, ClassPathXmlApplicationContext or
|
||||
* FileSystemXmlApplicationContext can be used to load the context files for testing,
|
||||
* even for DispatcherServlet context definitions.
|
||||
*
|
||||
* <p>For setting up a full WebApplicationContext in a test environment, you can
|
||||
* use XmlWebApplicationContext (or GenericWebApplicationContext), passing in an
|
||||
* appropriate MockServletContext instance. You might want to configure your
|
||||
* MockServletContext with a FileSystemResourceLoader in that case, to make your
|
||||
* resource paths interpreted as relative file system locations.
|
||||
*
|
||||
* <p>A common setup is to point your JVM working directory to the root of your
|
||||
* web application directory, in combination with filesystem-based resource loading.
|
||||
* This allows to load the context files as used in the web application, with
|
||||
* relative paths getting interpreted correctly. Such a setup will work with both
|
||||
* FileSystemXmlApplicationContext (which will load straight from the file system)
|
||||
* and XmlWebApplicationContext with an underlying MockServletContext (as long as
|
||||
* the MockServletContext has been configured with a FileSystemResourceLoader).
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
* @see #MockServletContext(org.springframework.core.io.ResourceLoader)
|
||||
* @see org.springframework.web.context.support.XmlWebApplicationContext
|
||||
* @see org.springframework.web.context.support.GenericWebApplicationContext
|
||||
* @see org.springframework.context.support.ClassPathXmlApplicationContext
|
||||
* @see org.springframework.context.support.FileSystemXmlApplicationContext
|
||||
*/
|
||||
public class MockServletContext implements ServletContext {
|
||||
|
||||
private static final String TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir";
|
||||
|
||||
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final ResourceLoader resourceLoader;
|
||||
|
||||
private final String resourceBasePath;
|
||||
|
||||
private String contextPath = "";
|
||||
|
||||
private int majorVersion = 2;
|
||||
|
||||
private int minorVersion = 5;
|
||||
|
||||
private int effectiveMajorVersion = 2;
|
||||
|
||||
private int effectiveMinorVersion = 5;
|
||||
|
||||
private final Map<String, ServletContext> contexts = new HashMap<String, ServletContext>();
|
||||
|
||||
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
|
||||
|
||||
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
|
||||
|
||||
private String servletContextName = "MockServletContext";
|
||||
|
||||
private final Set<String> declaredRoles = new HashSet<String>();
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockServletContext, using no base path and a
|
||||
* DefaultResourceLoader (i.e. the classpath root as WAR root).
|
||||
* @see org.springframework.core.io.DefaultResourceLoader
|
||||
*/
|
||||
public MockServletContext() {
|
||||
this("", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletContext, using a DefaultResourceLoader.
|
||||
* @param resourceBasePath the WAR root directory (should not end with a slash)
|
||||
* @see org.springframework.core.io.DefaultResourceLoader
|
||||
*/
|
||||
public MockServletContext(String resourceBasePath) {
|
||||
this(resourceBasePath, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletContext, using the specified ResourceLoader
|
||||
* and no base path.
|
||||
* @param resourceLoader the ResourceLoader to use (or null for the default)
|
||||
*/
|
||||
public MockServletContext(ResourceLoader resourceLoader) {
|
||||
this("", resourceLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletContext.
|
||||
* @param resourceBasePath the WAR root directory (should not end with a slash)
|
||||
* @param resourceLoader the ResourceLoader to use (or null for the default)
|
||||
*/
|
||||
public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
|
||||
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
|
||||
this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
|
||||
|
||||
// Use JVM temp dir as ServletContext temp dir.
|
||||
String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
|
||||
if (tempDir != null) {
|
||||
this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Build a full resource location for the given path,
|
||||
* prepending the resource base path of this MockServletContext.
|
||||
* @param path the path as specified
|
||||
* @return the full resource path
|
||||
*/
|
||||
protected String getResourceLocation(String path) {
|
||||
if (!path.startsWith("/")) {
|
||||
path = "/" + path;
|
||||
}
|
||||
return this.resourceBasePath + path;
|
||||
}
|
||||
|
||||
|
||||
public void setContextPath(String contextPath) {
|
||||
this.contextPath = (contextPath != null ? contextPath : "");
|
||||
}
|
||||
|
||||
/* This is a Servlet API 2.5 method. */
|
||||
public String getContextPath() {
|
||||
return this.contextPath;
|
||||
}
|
||||
|
||||
public void registerContext(String contextPath, ServletContext context) {
|
||||
this.contexts.put(contextPath, context);
|
||||
}
|
||||
|
||||
public ServletContext getContext(String contextPath) {
|
||||
if (this.contextPath.equals(contextPath)) {
|
||||
return this;
|
||||
}
|
||||
return this.contexts.get(contextPath);
|
||||
}
|
||||
|
||||
public void setMajorVersion(int majorVersion) {
|
||||
this.majorVersion = majorVersion;
|
||||
}
|
||||
|
||||
public int getMajorVersion() {
|
||||
return this.majorVersion;
|
||||
}
|
||||
|
||||
public void setMinorVersion(int minorVersion) {
|
||||
this.minorVersion = minorVersion;
|
||||
}
|
||||
|
||||
public int getMinorVersion() {
|
||||
return this.minorVersion;
|
||||
}
|
||||
|
||||
public void setEffectiveMajorVersion(int effectiveMajorVersion) {
|
||||
this.effectiveMajorVersion = effectiveMajorVersion;
|
||||
}
|
||||
|
||||
public int getEffectiveMajorVersion() {
|
||||
return this.effectiveMajorVersion;
|
||||
}
|
||||
|
||||
public void setEffectiveMinorVersion(int effectiveMinorVersion) {
|
||||
this.effectiveMinorVersion = effectiveMinorVersion;
|
||||
}
|
||||
|
||||
public int getEffectiveMinorVersion() {
|
||||
return this.effectiveMinorVersion;
|
||||
}
|
||||
|
||||
public String getMimeType(String filePath) {
|
||||
return MimeTypeResolver.getMimeType(filePath);
|
||||
}
|
||||
|
||||
public Set<String> getResourcePaths(String path) {
|
||||
String actualPath = (path.endsWith("/") ? path : path + "/");
|
||||
Resource resource = this.resourceLoader.getResource(getResourceLocation(actualPath));
|
||||
try {
|
||||
File file = resource.getFile();
|
||||
String[] fileList = file.list();
|
||||
if (ObjectUtils.isEmpty(fileList)) {
|
||||
return null;
|
||||
}
|
||||
Set<String> resourcePaths = new LinkedHashSet<String>(fileList.length);
|
||||
for (String fileEntry : fileList) {
|
||||
String resultPath = actualPath + fileEntry;
|
||||
if (resource.createRelative(fileEntry).getFile().isDirectory()) {
|
||||
resultPath += "/";
|
||||
}
|
||||
resourcePaths.add(resultPath);
|
||||
}
|
||||
return resourcePaths;
|
||||
}
|
||||
catch (IOException ex) {
|
||||
logger.warn("Couldn't get resource paths for " + resource, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public URL getResource(String path) throws MalformedURLException {
|
||||
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
|
||||
if (!resource.exists()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return resource.getURL();
|
||||
}
|
||||
catch (MalformedURLException ex) {
|
||||
throw ex;
|
||||
}
|
||||
catch (IOException ex) {
|
||||
logger.warn("Couldn't get URL for " + resource, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream getResourceAsStream(String path) {
|
||||
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
|
||||
if (!resource.exists()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return resource.getInputStream();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
logger.warn("Couldn't open InputStream for " + resource, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public RequestDispatcher getRequestDispatcher(String path) {
|
||||
if (!path.startsWith("/")) {
|
||||
throw new IllegalArgumentException("RequestDispatcher path at ServletContext level must start with '/'");
|
||||
}
|
||||
return new MockRequestDispatcher(path);
|
||||
}
|
||||
|
||||
public RequestDispatcher getNamedDispatcher(String path) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Servlet getServlet(String name) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Enumeration<Servlet> getServlets() {
|
||||
return Collections.enumeration(new HashSet<Servlet>());
|
||||
}
|
||||
|
||||
public Enumeration<String> getServletNames() {
|
||||
return Collections.enumeration(new HashSet<String>());
|
||||
}
|
||||
|
||||
public void log(String message) {
|
||||
logger.info(message);
|
||||
}
|
||||
|
||||
public void log(Exception ex, String message) {
|
||||
logger.info(message, ex);
|
||||
}
|
||||
|
||||
public void log(String message, Throwable ex) {
|
||||
logger.info(message, ex);
|
||||
}
|
||||
|
||||
public String getRealPath(String path) {
|
||||
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
|
||||
try {
|
||||
return resource.getFile().getAbsolutePath();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
logger.warn("Couldn't determine real path of resource " + resource, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String getServerInfo() {
|
||||
return "MockServletContext";
|
||||
}
|
||||
|
||||
public String getInitParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
return this.initParameters.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getInitParameterNames() {
|
||||
return Collections.enumeration(this.initParameters.keySet());
|
||||
}
|
||||
|
||||
public boolean setInitParameter(String name, String value) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
if (this.initParameters.containsKey(name)) {
|
||||
return false;
|
||||
}
|
||||
this.initParameters.put(name, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void addInitParameter(String name, String value) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.initParameters.put(name, value);
|
||||
}
|
||||
|
||||
public Object getAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
return new Vector<String>(this.attributes.keySet()).elements();
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object value) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
if (value != null) {
|
||||
this.attributes.put(name, value);
|
||||
}
|
||||
else {
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
|
||||
public void setServletContextName(String servletContextName) {
|
||||
this.servletContextName = servletContextName;
|
||||
}
|
||||
|
||||
public String getServletContextName() {
|
||||
return this.servletContextName;
|
||||
}
|
||||
|
||||
public ClassLoader getClassLoader() {
|
||||
return ClassUtils.getDefaultClassLoader();
|
||||
}
|
||||
|
||||
public void declareRoles(String... roleNames) {
|
||||
Assert.notNull(roleNames, "Role names array must not be null");
|
||||
for (String roleName : roleNames) {
|
||||
Assert.hasLength(roleName, "Role name must not be empty");
|
||||
this.declaredRoles.add(roleName);
|
||||
}
|
||||
}
|
||||
|
||||
public Set<String> getDeclaredRoles() {
|
||||
return Collections.unmodifiableSet(this.declaredRoles);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inner factory class used to just introduce a Java Activation Framework
|
||||
* dependency when actually asked to resolve a MIME type.
|
||||
*/
|
||||
private static class MimeTypeResolver {
|
||||
|
||||
public static String getMimeType(String filePath) {
|
||||
return FileTypeMap.getDefaultFileTypeMap().getContentType(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Implementation of the {@link javax.servlet.FilterConfig} interface which
|
||||
* simply passes the call through to a given Filter/FilterChain combination
|
||||
* (indicating the next Filter in the chain along with the FilterChain that it is
|
||||
* supposed to work on) or to a given Servlet (indicating the end of the chain).
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.0.3
|
||||
* @see javax.servlet.Filter
|
||||
* @see javax.servlet.Servlet
|
||||
* @see org.springframework.mock.web.MockFilterChain
|
||||
*/
|
||||
public class PassThroughFilterChain implements FilterChain {
|
||||
|
||||
private Filter filter;
|
||||
|
||||
private FilterChain nextFilterChain;
|
||||
|
||||
private Servlet servlet;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new PassThroughFilterChain that delegates to the given Filter,
|
||||
* calling it with the given FilterChain.
|
||||
* @param filter the Filter to delegate to
|
||||
* @param nextFilterChain the FilterChain to use for that next Filter
|
||||
*/
|
||||
public PassThroughFilterChain(Filter filter, FilterChain nextFilterChain) {
|
||||
Assert.notNull(filter, "Filter must not be null");
|
||||
Assert.notNull(nextFilterChain, "'FilterChain must not be null");
|
||||
this.filter = filter;
|
||||
this.nextFilterChain = nextFilterChain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new PassThroughFilterChain that delegates to the given Servlet.
|
||||
* @param servlet the Servlet to delegate to
|
||||
*/
|
||||
public PassThroughFilterChain(Servlet servlet) {
|
||||
Assert.notNull(servlet, "Servlet must not be null");
|
||||
this.servlet = servlet;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Pass the call on to the Filter/Servlet.
|
||||
*/
|
||||
public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException {
|
||||
if (this.filter != null) {
|
||||
this.filter.doFilter(request, response, this.nextFilterChain);
|
||||
}
|
||||
else {
|
||||
this.servlet.service(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.hibernate3;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.hibernate.proxy.HibernateProxy;
|
||||
import org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.BeanUtils;
|
||||
|
||||
/**
|
||||
* Test for compatibility of Spring's BeanUtils and its BridgeMethodResolver use
|
||||
* when operating on a Hibernate-generated CGLIB proxy class.
|
||||
*
|
||||
* @author Arnout Engelen
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class CglibProxyBridgeMethodTests {
|
||||
|
||||
@Test
|
||||
public void introspectHibernateProxyForGenericClass() {
|
||||
BeanUtils.getPropertyDescriptor(CglibInstantieMedewerker.class, "organisatie");
|
||||
Class<?> clazz = CGLIBLazyInitializer.getProxyFactory(
|
||||
CglibInstantieMedewerker.class, new Class[] {HibernateProxy.class});
|
||||
BeanUtils.getPropertyDescriptor(clazz, "organisatie");
|
||||
}
|
||||
|
||||
|
||||
public interface CglibIOrganisatie {
|
||||
}
|
||||
|
||||
|
||||
public class CglibOrganisatie implements CglibIOrganisatie {
|
||||
}
|
||||
|
||||
|
||||
public class CglibInstantie extends CglibOrganisatie {
|
||||
}
|
||||
|
||||
|
||||
public interface CglibIOrganisatieMedewerker<T extends CglibIOrganisatie> {
|
||||
|
||||
void setOrganisatie(T organisatie);
|
||||
}
|
||||
|
||||
|
||||
public class CglibOrganisatieMedewerker<T extends CglibOrganisatie> implements CglibIOrganisatieMedewerker<T> {
|
||||
|
||||
public void setOrganisatie(CglibOrganisatie organisatie) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class CglibInstantieMedewerker extends CglibOrganisatieMedewerker<CglibInstantie> implements Serializable {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.hibernate3;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.aopalliance.intercept.Interceptor;
|
||||
import org.aopalliance.intercept.Invocation;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.easymock.MockControl;
|
||||
import org.hibernate.FlushMode;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.classic.Session;
|
||||
import org.hibernate.exception.ConstraintViolationException;
|
||||
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 05.03.2005
|
||||
*/
|
||||
public class HibernateInterceptorTests extends TestCase {
|
||||
|
||||
public void testInterceptorWithNewSession() throws HibernateException {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf);
|
||||
session.flush();
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithNewSessionAndFlushNever() throws HibernateException {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf);
|
||||
session.setFlushMode(FlushMode.MANUAL);
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setFlushModeName("FLUSH_NEVER");
|
||||
interceptor.setSessionFactory(sf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithNewSessionAndFilter() throws HibernateException {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf);
|
||||
session.enableFilter("myFilter");
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
session.flush();
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setFilterName("myFilter");
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBound() {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(sf);
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundAndFlushEager() throws HibernateException {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
session.getFlushMode();
|
||||
sessionControl.setReturnValue(FlushMode.AUTO, 1);
|
||||
session.flush();
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER);
|
||||
interceptor.setSessionFactory(sf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(sf);
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundAndFlushEagerSwitch() throws HibernateException {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
session.getFlushMode();
|
||||
sessionControl.setReturnValue(FlushMode.NEVER, 1);
|
||||
session.setFlushMode(FlushMode.AUTO);
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.flush();
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.setFlushMode(FlushMode.NEVER);
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER);
|
||||
interceptor.setSessionFactory(sf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(sf);
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundAndFlushCommit() {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
session.getFlushMode();
|
||||
sessionControl.setReturnValue(FlushMode.AUTO, 1);
|
||||
session.setFlushMode(FlushMode.COMMIT);
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.setFlushMode(FlushMode.AUTO);
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setFlushMode(HibernateInterceptor.FLUSH_COMMIT);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(sf);
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundAndFlushAlways() {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
session.getFlushMode();
|
||||
sessionControl.setReturnValue(FlushMode.AUTO, 1);
|
||||
session.setFlushMode(FlushMode.ALWAYS);
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.setFlushMode(FlushMode.AUTO);
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setFlushMode(HibernateInterceptor.FLUSH_ALWAYS);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(sf);
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundAndFilter() {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
session.enableFilter("myFilter");
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
session.disableFilter("myFilter");
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setFilterName("myFilter");
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(sf);
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundAndFilters() {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
session.enableFilter("myFilter");
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
session.enableFilter("yourFilter");
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
session.disableFilter("myFilter");
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.disableFilter("yourFilter");
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setFilterNames(new String[] {"myFilter", "yourFilter"});
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(sf);
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithFlushFailure() throws Throwable {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
SQLException sqlEx = new SQLException("argh", "27");
|
||||
session.flush();
|
||||
ConstraintViolationException jdbcEx = new ConstraintViolationException("", sqlEx, null);
|
||||
sessionControl.setThrowable(jdbcEx, 1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
fail("Should have thrown DataIntegrityViolationException");
|
||||
}
|
||||
catch (DataIntegrityViolationException ex) {
|
||||
// expected
|
||||
assertEquals(jdbcEx, ex.getCause());
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundEmptyHolder() {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.flush();
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
SessionHolder holder = new SessionHolder("key", session);
|
||||
holder.removeSession("key");
|
||||
TransactionSynchronizationManager.bindResource(sf, holder);
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithEntityInterceptor() throws HibernateException {
|
||||
MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class);
|
||||
org.hibernate.Interceptor entityInterceptor = (org.hibernate.Interceptor) interceptorControl.getMock();
|
||||
interceptorControl.replay();
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
sf.openSession(entityInterceptor);
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.flush();
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setEntityInterceptor(entityInterceptor);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
|
||||
interceptorControl.verify();
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithEntityInterceptorBeanName() throws HibernateException {
|
||||
MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class);
|
||||
org.hibernate.Interceptor entityInterceptor = (org.hibernate.Interceptor) interceptorControl.getMock();
|
||||
interceptorControl.replay();
|
||||
MockControl interceptor2Control = MockControl.createControl(org.hibernate.Interceptor.class);
|
||||
org.hibernate.Interceptor entityInterceptor2 = (org.hibernate.Interceptor) interceptor2Control.getMock();
|
||||
interceptor2Control.replay();
|
||||
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
sf.openSession(entityInterceptor);
|
||||
sfControl.setReturnValue(session, 1);
|
||||
sf.openSession(entityInterceptor2);
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 2);
|
||||
session.flush();
|
||||
sessionControl.setVoidCallable(2);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 2);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
MockControl beanFactoryControl = MockControl.createControl(BeanFactory.class);
|
||||
BeanFactory beanFactory = (BeanFactory) beanFactoryControl.getMock();
|
||||
beanFactory.getBean("entityInterceptor", org.hibernate.Interceptor.class);
|
||||
beanFactoryControl.setReturnValue(entityInterceptor, 1);
|
||||
beanFactory.getBean("entityInterceptor", org.hibernate.Interceptor.class);
|
||||
beanFactoryControl.setReturnValue(entityInterceptor2, 1);
|
||||
beanFactoryControl.replay();
|
||||
|
||||
HibernateInterceptor interceptor = new HibernateInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setEntityInterceptorBeanName("entityInterceptor");
|
||||
interceptor.setBeanFactory(beanFactory);
|
||||
for (int i = 0; i < 2; i++) {
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(sf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
interceptorControl.verify();
|
||||
interceptor2Control.verify();
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
protected void tearDown() {
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
}
|
||||
|
||||
|
||||
private static class TestInvocation implements MethodInvocation {
|
||||
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
public TestInvocation(SessionFactory sessionFactory) {
|
||||
this.sessionFactory = sessionFactory;
|
||||
}
|
||||
|
||||
public Object proceed() throws Throwable {
|
||||
if (!TransactionSynchronizationManager.hasResource(this.sessionFactory)) {
|
||||
throw new IllegalStateException("Session not bound");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public int getCurrentInterceptorIndex() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getNumberOfInterceptors() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Interceptor getInterceptor(int i) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Method getMethod() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public AccessibleObject getStaticPart() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object getArgument(int i) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object[] getArguments() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setArgument(int i, Object handler) {
|
||||
}
|
||||
|
||||
public int getArgumentCount() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Object getThis() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object getProxy() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Invocation cloneInstance() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void release() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,617 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.hibernate3;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import javax.transaction.TransactionManager;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.Interceptor;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.cache.CacheProvider;
|
||||
import org.hibernate.cache.NoCacheProvider;
|
||||
import org.hibernate.cache.RegionFactory;
|
||||
import org.hibernate.cache.impl.NoCachingRegionFactory;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.cfg.Environment;
|
||||
import org.hibernate.cfg.ImprovedNamingStrategy;
|
||||
import org.hibernate.cfg.Mappings;
|
||||
import org.hibernate.cfg.NamingStrategy;
|
||||
import org.hibernate.connection.UserSuppliedConnectionProvider;
|
||||
import org.hibernate.engine.FilterDefinition;
|
||||
import org.hibernate.event.MergeEvent;
|
||||
import org.hibernate.event.MergeEventListener;
|
||||
import org.hibernate.mapping.TypeDef;
|
||||
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 05.03.2005
|
||||
*/
|
||||
public class LocalSessionFactoryBeanTests extends TestCase {
|
||||
|
||||
public void testLocalSessionFactoryBeanWithDataSource() throws Exception {
|
||||
final DriverManagerDataSource ds = new DriverManagerDataSource();
|
||||
final List invocations = new ArrayList();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration addInputStream(InputStream is) {
|
||||
try {
|
||||
is.close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
}
|
||||
invocations.add("addResource");
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
assertEquals(LocalDataSourceConnectionProvider.class.getName(),
|
||||
config.getProperty(Environment.CONNECTION_PROVIDER));
|
||||
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
|
||||
invocations.add("newSessionFactory");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setDataSource(ds);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sfb.getConfiguration() != null);
|
||||
assertEquals("newSessionFactory", invocations.get(0));
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithCacheRegionFactory() throws Exception {
|
||||
final RegionFactory regionFactory = new NoCachingRegionFactory(null);
|
||||
final List invocations = new ArrayList();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration addInputStream(InputStream is) {
|
||||
try {
|
||||
is.close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
}
|
||||
invocations.add("addResource");
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
assertEquals(LocalRegionFactoryProxy.class.getName(),
|
||||
config.getProperty(Environment.CACHE_REGION_FACTORY));
|
||||
assertSame(regionFactory, LocalSessionFactoryBean.getConfigTimeRegionFactory());
|
||||
invocations.add("newSessionFactory");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setCacheRegionFactory(regionFactory);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sfb.getConfiguration() != null);
|
||||
assertEquals("newSessionFactory", invocations.get(0));
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithCacheProvider() throws Exception {
|
||||
final CacheProvider cacheProvider = new NoCacheProvider();
|
||||
final List invocations = new ArrayList();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration addInputStream(InputStream is) {
|
||||
try {
|
||||
is.close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
}
|
||||
invocations.add("addResource");
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
assertEquals(LocalCacheProviderProxy.class.getName(),
|
||||
config.getProperty(Environment.CACHE_PROVIDER));
|
||||
assertSame(cacheProvider, LocalSessionFactoryBean.getConfigTimeCacheProvider());
|
||||
invocations.add("newSessionFactory");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setCacheProvider(cacheProvider);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sfb.getConfiguration() != null);
|
||||
assertEquals("newSessionFactory", invocations.get(0));
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithTransactionAwareDataSource() throws Exception {
|
||||
final DriverManagerDataSource ds = new DriverManagerDataSource();
|
||||
final List invocations = new ArrayList();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration addInputStream(InputStream is) {
|
||||
try {
|
||||
is.close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
}
|
||||
invocations.add("addResource");
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
assertEquals(TransactionAwareDataSourceConnectionProvider.class.getName(),
|
||||
config.getProperty(Environment.CONNECTION_PROVIDER));
|
||||
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
|
||||
invocations.add("newSessionFactory");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setDataSource(ds);
|
||||
sfb.setUseTransactionAwareDataSource(true);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sfb.getConfiguration() != null);
|
||||
assertEquals("newSessionFactory", invocations.get(0));
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithDataSourceAndMappingResources() throws Exception {
|
||||
final DriverManagerDataSource ds = new DriverManagerDataSource();
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
final TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
final List invocations = new ArrayList();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration addInputStream(InputStream is) {
|
||||
try {
|
||||
is.close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
}
|
||||
invocations.add("addResource");
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
assertEquals(LocalJtaDataSourceConnectionProvider.class.getName(),
|
||||
config.getProperty(Environment.CONNECTION_PROVIDER));
|
||||
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
|
||||
assertEquals(LocalTransactionManagerLookup.class.getName(),
|
||||
config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY));
|
||||
assertEquals(tm, LocalSessionFactoryBean.getConfigTimeTransactionManager());
|
||||
invocations.add("newSessionFactory");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setMappingResources(new String[]{
|
||||
"/org/springframework/beans/factory/xml/test.xml",
|
||||
"/org/springframework/beans/factory/xml/child.xml"});
|
||||
sfb.setDataSource(ds);
|
||||
sfb.setJtaTransactionManager(tm);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sfb.getConfiguration() != null);
|
||||
assertEquals("addResource", invocations.get(0));
|
||||
assertEquals("addResource", invocations.get(1));
|
||||
assertEquals("newSessionFactory", invocations.get(2));
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithDataSourceAndMappingJarLocations() throws Exception {
|
||||
final DriverManagerDataSource ds = new DriverManagerDataSource();
|
||||
final Set invocations = new HashSet();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration addJar(File file) {
|
||||
invocations.add("addResource " + file.getPath());
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
assertEquals(LocalDataSourceConnectionProvider.class.getName(),
|
||||
config.getProperty(Environment.CONNECTION_PROVIDER));
|
||||
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
|
||||
invocations.add("newSessionFactory");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setMappingJarLocations(new Resource[]{
|
||||
new FileSystemResource("mapping.hbm.jar"), new FileSystemResource("mapping2.hbm.jar")});
|
||||
sfb.setDataSource(ds);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sfb.getConfiguration() != null);
|
||||
assertTrue(invocations.contains("addResource mapping.hbm.jar"));
|
||||
assertTrue(invocations.contains("addResource mapping2.hbm.jar"));
|
||||
assertTrue(invocations.contains("newSessionFactory"));
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithDataSourceAndProperties() throws Exception {
|
||||
final DriverManagerDataSource ds = new DriverManagerDataSource();
|
||||
final Set invocations = new HashSet();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration addInputStream(InputStream is) {
|
||||
try {
|
||||
is.close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
}
|
||||
invocations.add("addResource");
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
assertEquals(LocalDataSourceConnectionProvider.class.getName(),
|
||||
config.getProperty(Environment.CONNECTION_PROVIDER));
|
||||
assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
|
||||
assertEquals("myValue", config.getProperty("myProperty"));
|
||||
invocations.add("newSessionFactory");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setMappingLocations(new Resource[]{
|
||||
new ClassPathResource("/org/springframework/beans/factory/xml/test.xml")});
|
||||
sfb.setDataSource(ds);
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(Environment.CONNECTION_PROVIDER, "myClass");
|
||||
prop.setProperty("myProperty", "myValue");
|
||||
sfb.setHibernateProperties(prop);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sfb.getConfiguration() != null);
|
||||
assertTrue(invocations.contains("addResource"));
|
||||
assertTrue(invocations.contains("newSessionFactory"));
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithValidProperties() throws Exception {
|
||||
final Set invocations = new HashSet();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
assertEquals(UserSuppliedConnectionProvider.class.getName(),
|
||||
config.getProperty(Environment.CONNECTION_PROVIDER));
|
||||
assertEquals("myValue", config.getProperty("myProperty"));
|
||||
invocations.add("newSessionFactory");
|
||||
return null;
|
||||
}
|
||||
};
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(Environment.CONNECTION_PROVIDER, UserSuppliedConnectionProvider.class.getName());
|
||||
prop.setProperty("myProperty", "myValue");
|
||||
sfb.setHibernateProperties(prop);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sfb.getConfiguration() != null);
|
||||
assertTrue(invocations.contains("newSessionFactory"));
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithInvalidProperties() throws Exception {
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
|
||||
sfb.setMappingResources(new String[0]);
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(Environment.CONNECTION_PROVIDER, "myClass");
|
||||
sfb.setHibernateProperties(prop);
|
||||
try {
|
||||
sfb.afterPropertiesSet();
|
||||
}
|
||||
catch (HibernateException ex) {
|
||||
// expected, provider class not found
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithInvalidMappings() throws Exception {
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
|
||||
sfb.setMappingResources(new String[]{"mapping.hbm.xml"});
|
||||
try {
|
||||
sfb.afterPropertiesSet();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
// expected, mapping resource not found
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithCustomSessionFactory() throws Exception {
|
||||
MockControl factoryControl = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sessionFactory = (SessionFactory) factoryControl.getMock();
|
||||
sessionFactory.close();
|
||||
factoryControl.setVoidCallable(1);
|
||||
factoryControl.replay();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
return sessionFactory;
|
||||
}
|
||||
};
|
||||
sfb.setMappingResources(new String[0]);
|
||||
sfb.setDataSource(new DriverManagerDataSource());
|
||||
sfb.setExposeTransactionAwareSessionFactory(false);
|
||||
sfb.afterPropertiesSet();
|
||||
assertTrue(sessionFactory == sfb.getObject());
|
||||
sfb.destroy();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithEntityInterceptor() throws Exception {
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration setInterceptor(Interceptor interceptor) {
|
||||
throw new IllegalArgumentException(interceptor.toString());
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
sfb.setMappingResources(new String[0]);
|
||||
sfb.setDataSource(new DriverManagerDataSource());
|
||||
MockControl interceptorControl = MockControl.createControl(Interceptor.class);
|
||||
Interceptor entityInterceptor = (Interceptor) interceptorControl.getMock();
|
||||
interceptorControl.replay();
|
||||
sfb.setEntityInterceptor(entityInterceptor);
|
||||
try {
|
||||
sfb.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
assertTrue("Correct exception", ex.getMessage().equals(entityInterceptor.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithNamingStrategy() throws Exception {
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration setNamingStrategy(NamingStrategy namingStrategy) {
|
||||
throw new IllegalArgumentException(namingStrategy.toString());
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
sfb.setMappingResources(new String[0]);
|
||||
sfb.setDataSource(new DriverManagerDataSource());
|
||||
sfb.setNamingStrategy(ImprovedNamingStrategy.INSTANCE);
|
||||
try {
|
||||
sfb.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
assertTrue("Correct exception", ex.getMessage().equals(ImprovedNamingStrategy.INSTANCE.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithCacheStrategies() throws Exception {
|
||||
final Properties registeredClassCache = new Properties();
|
||||
final Properties registeredCollectionCache = new Properties();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public Configuration setCacheConcurrencyStrategy(String clazz, String concurrencyStrategy) {
|
||||
registeredClassCache.setProperty(clazz, concurrencyStrategy);
|
||||
return this;
|
||||
}
|
||||
public Configuration setCollectionCacheConcurrencyStrategy(String collectionRole, String concurrencyStrategy) {
|
||||
registeredCollectionCache.setProperty(collectionRole, concurrencyStrategy);
|
||||
return this;
|
||||
}
|
||||
};
|
||||
}
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
sfb.setMappingResources(new String[0]);
|
||||
sfb.setDataSource(new DriverManagerDataSource());
|
||||
Properties classCache = new Properties();
|
||||
classCache.setProperty("org.springframework.beans.TestBean", "read-write");
|
||||
sfb.setEntityCacheStrategies(classCache);
|
||||
Properties collectionCache = new Properties();
|
||||
collectionCache.setProperty("org.springframework.beans.TestBean.friends", "read-only");
|
||||
sfb.setCollectionCacheStrategies(collectionCache);
|
||||
sfb.afterPropertiesSet();
|
||||
|
||||
assertEquals(classCache, registeredClassCache);
|
||||
assertEquals(collectionCache, registeredCollectionCache);
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithCacheStrategiesAndRegions() throws Exception {
|
||||
final Properties registeredClassCache = new Properties();
|
||||
final Properties registeredCollectionCache = new Properties();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
// changed from return type 'void' to 'Configuration' in Hibernate 3.6
|
||||
public void setCacheConcurrencyStrategy(String clazz, String concurrencyStrategy, String regionName) {
|
||||
registeredClassCache.setProperty(clazz, concurrencyStrategy + "," + regionName);
|
||||
}
|
||||
public void setCollectionCacheConcurrencyStrategy(String collectionRole, String concurrencyStrategy, String regionName) {
|
||||
registeredCollectionCache.setProperty(collectionRole, concurrencyStrategy + "," + regionName);
|
||||
}
|
||||
};
|
||||
}
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
sfb.setMappingResources(new String[0]);
|
||||
sfb.setDataSource(new DriverManagerDataSource());
|
||||
Properties classCache = new Properties();
|
||||
classCache.setProperty("org.springframework.beans.TestBean", "read-write,myRegion");
|
||||
sfb.setEntityCacheStrategies(classCache);
|
||||
Properties collectionCache = new Properties();
|
||||
collectionCache.setProperty("org.springframework.beans.TestBean.friends", "read-only,myRegion");
|
||||
sfb.setCollectionCacheStrategies(collectionCache);
|
||||
sfb.afterPropertiesSet();
|
||||
|
||||
assertEquals(classCache, registeredClassCache);
|
||||
assertEquals(collectionCache, registeredCollectionCache);
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithEventListeners() throws Exception {
|
||||
final Map registeredListeners = new HashMap();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public void setListener(String type, Object listener) {
|
||||
registeredListeners.put(type, listener);
|
||||
}
|
||||
};
|
||||
}
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setMappingResources(new String[0]);
|
||||
sfb.setDataSource(new DriverManagerDataSource());
|
||||
Map listeners = new HashMap();
|
||||
listeners.put("flush", "myListener");
|
||||
listeners.put("create", "yourListener");
|
||||
sfb.setEventListeners(listeners);
|
||||
sfb.afterPropertiesSet();
|
||||
assertEquals(listeners, registeredListeners);
|
||||
}
|
||||
|
||||
public void testLocalSessionFactoryBeanWithEventListenerSet() throws Exception {
|
||||
final Map registeredListeners = new HashMap();
|
||||
LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
|
||||
protected Configuration newConfiguration() {
|
||||
return new Configuration() {
|
||||
public void setListeners(String type, Object[] listeners) {
|
||||
assertTrue(listeners instanceof MergeEventListener[]);
|
||||
registeredListeners.put(type, new HashSet(Arrays.asList(listeners)));
|
||||
}
|
||||
};
|
||||
}
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
sfb.setMappingResources(new String[0]);
|
||||
sfb.setDataSource(new DriverManagerDataSource());
|
||||
Map listeners = new HashMap();
|
||||
Set mergeSet = new HashSet();
|
||||
mergeSet.add(new DummyMergeEventListener());
|
||||
mergeSet.add(new DummyMergeEventListener());
|
||||
listeners.put("merge", mergeSet);
|
||||
sfb.setEventListeners(listeners);
|
||||
sfb.afterPropertiesSet();
|
||||
assertEquals(listeners, registeredListeners);
|
||||
}
|
||||
|
||||
/*
|
||||
public void testLocalSessionFactoryBeanWithFilterDefinitions() throws Exception {
|
||||
XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("filterDefinitions.xml", getClass()));
|
||||
FilterTestLocalSessionFactoryBean sf = (FilterTestLocalSessionFactoryBean) xbf.getBean("&sessionFactory");
|
||||
assertEquals(2, sf.registeredFilterDefinitions.size());
|
||||
FilterDefinition filter1 = (FilterDefinition) sf.registeredFilterDefinitions.get(0);
|
||||
FilterDefinition filter2 = (FilterDefinition) sf.registeredFilterDefinitions.get(1);
|
||||
|
||||
assertEquals("filter1", filter1.getFilterName());
|
||||
assertEquals(2, filter1.getParameterNames().size());
|
||||
assertEquals(Hibernate.STRING, filter1.getParameterType("param1"));
|
||||
assertEquals(Hibernate.LONG, filter1.getParameterType("otherParam"));
|
||||
assertEquals("someCondition", filter1.getDefaultFilterCondition());
|
||||
|
||||
assertEquals("filter2", filter2.getFilterName());
|
||||
assertEquals(1, filter2.getParameterNames().size());
|
||||
assertEquals(Hibernate.INTEGER, filter2.getParameterType("myParam"));
|
||||
}
|
||||
*/
|
||||
|
||||
public void testLocalSessionFactoryBeanWithTypeDefinitions() throws Exception {
|
||||
XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("typeDefinitions.xml", getClass()));
|
||||
TypeTestLocalSessionFactoryBean sf = (TypeTestLocalSessionFactoryBean) xbf.getBean("&sessionFactory");
|
||||
// Requires re-compilation when switching to Hibernate 3.5/3.6
|
||||
// since Mappings changed from a class to an interface
|
||||
TypeDef type1 = sf.mappings.getTypeDef("type1");
|
||||
TypeDef type2 = sf.mappings.getTypeDef("type2");
|
||||
|
||||
assertEquals("mypackage.MyTypeClass", type1.getTypeClass());
|
||||
assertEquals(2, type1.getParameters().size());
|
||||
assertEquals("value1", type1.getParameters().getProperty("param1"));
|
||||
assertEquals("othervalue", type1.getParameters().getProperty("otherParam"));
|
||||
|
||||
assertEquals("mypackage.MyOtherTypeClass", type2.getTypeClass());
|
||||
assertEquals(1, type2.getParameters().size());
|
||||
assertEquals("myvalue", type2.getParameters().getProperty("myParam"));
|
||||
}
|
||||
|
||||
|
||||
public static class FilterTestLocalSessionFactoryBean extends LocalSessionFactoryBean {
|
||||
|
||||
public List registeredFilterDefinitions = new LinkedList();
|
||||
|
||||
protected Configuration newConfiguration() throws HibernateException {
|
||||
return new Configuration() {
|
||||
public void addFilterDefinition(FilterDefinition definition) {
|
||||
registeredFilterDefinitions.add(definition);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class TypeTestLocalSessionFactoryBean extends LocalSessionFactoryBean {
|
||||
|
||||
public Mappings mappings;
|
||||
|
||||
protected SessionFactory newSessionFactory(Configuration config) {
|
||||
this.mappings = config.createMappings();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class DummyMergeEventListener implements MergeEventListener {
|
||||
|
||||
public void onMerge(MergeEvent event) throws HibernateException {
|
||||
}
|
||||
|
||||
public void onMerge(MergeEvent event, Map copiedAlready) throws HibernateException {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests$FilterTestLocalSessionFactoryBean">
|
||||
<property name="filterDefinitions">
|
||||
<list>
|
||||
<bean class="org.springframework.orm.hibernate3.FilterDefinitionFactoryBean">
|
||||
<property name="filterName" value="filter1"/>
|
||||
<property name="parameterTypes">
|
||||
<props>
|
||||
<prop key="param1">string</prop>
|
||||
<prop key="otherParam">long</prop>
|
||||
</props>
|
||||
</property>
|
||||
<property name="defaultFilterCondition" value="someCondition"/>
|
||||
</bean>
|
||||
<bean id="filter2" class="org.springframework.orm.hibernate3.FilterDefinitionFactoryBean">
|
||||
<property name="parameterTypes">
|
||||
<props>
|
||||
<prop key="myParam">integer</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
</list>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.hibernate3.support;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.orm.hibernate3.HibernateTemplate;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 05.03.2005
|
||||
*/
|
||||
public class HibernateDaoSupportTests extends TestCase {
|
||||
|
||||
public void testHibernateDaoSupportWithSessionFactory() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
sfControl.replay();
|
||||
final List test = new ArrayList();
|
||||
HibernateDaoSupport dao = new HibernateDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setSessionFactory(sf);
|
||||
dao.afterPropertiesSet();
|
||||
assertEquals("Correct SessionFactory", sf, dao.getSessionFactory());
|
||||
assertEquals("Correct HibernateTemplate", sf, dao.getHibernateTemplate().getSessionFactory());
|
||||
assertEquals("initDao called", test.size(), 1);
|
||||
sfControl.verify();
|
||||
}
|
||||
|
||||
public void testHibernateDaoSupportWithHibernateTemplate() throws Exception {
|
||||
HibernateTemplate template = new HibernateTemplate();
|
||||
final List test = new ArrayList();
|
||||
HibernateDaoSupport dao = new HibernateDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setHibernateTemplate(template);
|
||||
dao.afterPropertiesSet();
|
||||
assertEquals("Correct HibernateTemplate", template, dao.getHibernateTemplate());
|
||||
assertEquals("initDao called", test.size(), 1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.hibernate3.support;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.transaction.Status;
|
||||
import javax.transaction.Synchronization;
|
||||
import javax.transaction.TransactionManager;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.easymock.internal.ArrayMatcher;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.classic.Session;
|
||||
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
import org.springframework.jdbc.support.lob.LobHandler;
|
||||
import org.springframework.orm.hibernate3.SessionFactoryUtils;
|
||||
import org.springframework.transaction.MockJtaTransaction;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 05.03.2005
|
||||
*/
|
||||
public class LobTypeTests extends TestCase {
|
||||
|
||||
private MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
private ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
private MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
private PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
private MockControl lobHandlerControl = MockControl.createControl(LobHandler.class);
|
||||
private LobHandler lobHandler = (LobHandler) lobHandlerControl.getMock();
|
||||
private MockControl lobCreatorControl = MockControl.createControl(LobCreator.class);
|
||||
private LobCreator lobCreator = (LobCreator) lobCreatorControl.getMock();
|
||||
|
||||
protected void setUp() throws SQLException {
|
||||
lobHandler.getLobCreator();
|
||||
lobHandlerControl.setReturnValue(lobCreator);
|
||||
lobCreator.close();
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
rsControl.replay();
|
||||
psControl.replay();
|
||||
}
|
||||
|
||||
public void testClobStringType() throws Exception {
|
||||
lobHandler.getClobAsString(rs, "column");
|
||||
lobHandlerControl.setReturnValue("content");
|
||||
lobCreator.setClobAsString(ps, 1, "content");
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
ClobStringType type = new ClobStringType(lobHandler, null);
|
||||
assertEquals(1, type.sqlTypes().length);
|
||||
assertEquals(Types.CLOB, type.sqlTypes()[0]);
|
||||
assertEquals(String.class, type.returnedClass());
|
||||
assertTrue(type.equals("content", "content"));
|
||||
assertEquals("content", type.deepCopy("content"));
|
||||
assertFalse(type.isMutable());
|
||||
|
||||
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.nullSafeSet(ps, "content", 1);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
assertTrue(synchs.get(0).getClass().getName().endsWith("SpringLobCreatorSynchronization"));
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testClobStringTypeWithSynchronizedSession() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
lobHandler.getClobAsString(rs, "column");
|
||||
lobHandlerControl.setReturnValue("content");
|
||||
lobCreator.setClobAsString(ps, 1, "content");
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
ClobStringType type = new ClobStringType(lobHandler, null);
|
||||
assertEquals(1, type.sqlTypes().length);
|
||||
assertEquals(Types.CLOB, type.sqlTypes()[0]);
|
||||
assertEquals(String.class, type.returnedClass());
|
||||
assertTrue(type.equals("content", "content"));
|
||||
assertEquals("content", type.deepCopy("content"));
|
||||
assertFalse(type.isMutable());
|
||||
|
||||
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
SessionFactoryUtils.getSession(sf, true);
|
||||
type.nullSafeSet(ps, "content", 1);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(2, synchs.size());
|
||||
assertTrue(synchs.get(0).getClass().getName().endsWith("SpringLobCreatorSynchronization"));
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
((TransactionSynchronization) synchs.get(1)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(1)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testClobStringTypeWithFlushOnCommit() throws Exception {
|
||||
lobHandler.getClobAsString(rs, "column");
|
||||
lobHandlerControl.setReturnValue("content");
|
||||
lobCreator.setClobAsString(ps, 1, "content");
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
ClobStringType type = new ClobStringType(lobHandler, null);
|
||||
assertEquals(1, type.sqlTypes().length);
|
||||
assertEquals(Types.CLOB, type.sqlTypes()[0]);
|
||||
assertEquals(String.class, type.returnedClass());
|
||||
assertTrue(type.equals("content", "content"));
|
||||
assertEquals("content", type.deepCopy("content"));
|
||||
assertFalse(type.isMutable());
|
||||
|
||||
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.nullSafeSet(ps, "content", 1);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testClobStringTypeWithJtaSynchronization() throws Exception {
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockJtaTransaction transaction = new MockJtaTransaction();
|
||||
tm.getStatus();
|
||||
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(transaction, 1);
|
||||
|
||||
lobHandler.getClobAsString(rs, "column");
|
||||
lobHandlerControl.setReturnValue("content");
|
||||
lobCreator.setClobAsString(ps, 1, "content");
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
ClobStringType type = new ClobStringType(lobHandler, tm);
|
||||
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
tmControl.replay();
|
||||
type.nullSafeSet(ps, "content", 1);
|
||||
Synchronization synch = transaction.getSynchronization();
|
||||
assertNotNull(synch);
|
||||
synch.beforeCompletion();
|
||||
synch.afterCompletion(Status.STATUS_COMMITTED);
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testClobStringTypeWithJtaSynchronizationAndRollback() throws Exception {
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockJtaTransaction transaction = new MockJtaTransaction();
|
||||
tm.getStatus();
|
||||
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(transaction, 1);
|
||||
|
||||
lobHandler.getClobAsString(rs, "column");
|
||||
lobHandlerControl.setReturnValue("content");
|
||||
lobCreator.setClobAsString(ps, 1, "content");
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
ClobStringType type = new ClobStringType(lobHandler, tm);
|
||||
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
tmControl.replay();
|
||||
type.nullSafeSet(ps, "content", 1);
|
||||
Synchronization synch = transaction.getSynchronization();
|
||||
assertNotNull(synch);
|
||||
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testBlobStringType() throws Exception {
|
||||
String content = "content";
|
||||
byte[] contentBytes = content.getBytes();
|
||||
lobHandler.getBlobAsBytes(rs, "column");
|
||||
lobHandlerControl.setReturnValue(contentBytes);
|
||||
lobCreator.setBlobAsBytes(ps, 1, contentBytes);
|
||||
lobCreatorControl.setMatcher(new ArrayMatcher());
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobStringType type = new BlobStringType(lobHandler, null);
|
||||
assertEquals(1, type.sqlTypes().length);
|
||||
assertEquals(Types.BLOB, type.sqlTypes()[0]);
|
||||
assertEquals(String.class, type.returnedClass());
|
||||
assertTrue(type.equals("content", "content"));
|
||||
assertEquals("content", type.deepCopy("content"));
|
||||
assertFalse(type.isMutable());
|
||||
|
||||
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.nullSafeSet(ps, content, 1);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testBlobStringTypeWithNull() throws Exception {
|
||||
lobHandler.getBlobAsBytes(rs, "column");
|
||||
lobHandlerControl.setReturnValue(null);
|
||||
lobCreator.setBlobAsBytes(ps, 1, null);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobStringType type = new BlobStringType(lobHandler, null);
|
||||
assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.nullSafeSet(ps, null, 1);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testBlobStringTypeWithJtaSynchronization() throws Exception {
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockJtaTransaction transaction = new MockJtaTransaction();
|
||||
tm.getStatus();
|
||||
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(transaction, 1);
|
||||
|
||||
String content = "content";
|
||||
byte[] contentBytes = content.getBytes();
|
||||
lobHandler.getBlobAsBytes(rs, "column");
|
||||
lobHandlerControl.setReturnValue(contentBytes);
|
||||
lobCreator.setBlobAsBytes(ps, 1, contentBytes);
|
||||
lobCreatorControl.setMatcher(new ArrayMatcher());
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobStringType type = new BlobStringType(lobHandler, tm);
|
||||
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
tmControl.replay();
|
||||
type.nullSafeSet(ps, content, 1);
|
||||
Synchronization synch = transaction.getSynchronization();
|
||||
assertNotNull(synch);
|
||||
synch.beforeCompletion();
|
||||
synch.afterCompletion(Status.STATUS_COMMITTED);
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testBlobStringTypeWithJtaSynchronizationAndRollback() throws Exception {
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockJtaTransaction transaction = new MockJtaTransaction();
|
||||
tm.getStatus();
|
||||
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(transaction, 1);
|
||||
|
||||
String content = "content";
|
||||
byte[] contentBytes = content.getBytes();
|
||||
lobHandler.getBlobAsBytes(rs, "column");
|
||||
lobHandlerControl.setReturnValue(contentBytes);
|
||||
lobCreator.setBlobAsBytes(ps, 1, contentBytes);
|
||||
lobCreatorControl.setMatcher(new ArrayMatcher());
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobStringType type = new BlobStringType(lobHandler, tm);
|
||||
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
tmControl.replay();
|
||||
type.nullSafeSet(ps, content, 1);
|
||||
Synchronization synch = transaction.getSynchronization();
|
||||
assertNotNull(synch);
|
||||
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testBlobByteArrayType() throws Exception {
|
||||
byte[] content = "content".getBytes();
|
||||
lobHandler.getBlobAsBytes(rs, "column");
|
||||
lobHandlerControl.setReturnValue(content);
|
||||
lobCreator.setBlobAsBytes(ps, 1, content);
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobByteArrayType type = new BlobByteArrayType(lobHandler, null);
|
||||
assertEquals(1, type.sqlTypes().length);
|
||||
assertEquals(Types.BLOB, type.sqlTypes()[0]);
|
||||
assertEquals(byte[].class, type.returnedClass());
|
||||
assertTrue(type.equals(new byte[] {(byte) 255}, new byte[] {(byte) 255}));
|
||||
assertTrue(Arrays.equals(new byte[] {(byte) 255}, (byte[]) type.deepCopy(new byte[] {(byte) 255})));
|
||||
assertTrue(type.isMutable());
|
||||
|
||||
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.nullSafeSet(ps, content, 1);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testBlobByteArrayTypeWithJtaSynchronization() throws Exception {
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockJtaTransaction transaction = new MockJtaTransaction();
|
||||
tm.getStatus();
|
||||
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(transaction, 1);
|
||||
|
||||
byte[] content = "content".getBytes();
|
||||
lobHandler.getBlobAsBytes(rs, "column");
|
||||
lobHandlerControl.setReturnValue(content);
|
||||
lobCreator.setBlobAsBytes(ps, 1, content);
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobByteArrayType type = new BlobByteArrayType(lobHandler, tm);
|
||||
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
tmControl.replay();
|
||||
type.nullSafeSet(ps, content, 1);
|
||||
Synchronization synch = transaction.getSynchronization();
|
||||
assertNotNull(synch);
|
||||
synch.beforeCompletion();
|
||||
synch.afterCompletion(Status.STATUS_COMMITTED);
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testBlobByteArrayTypeWithJtaSynchronizationAndRollback() throws Exception {
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockJtaTransaction transaction = new MockJtaTransaction();
|
||||
tm.getStatus();
|
||||
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(transaction, 1);
|
||||
|
||||
byte[] content = "content".getBytes();
|
||||
lobHandler.getBlobAsBytes(rs, "column");
|
||||
lobHandlerControl.setReturnValue(content);
|
||||
lobCreator.setBlobAsBytes(ps, 1, content);
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobByteArrayType type = new BlobByteArrayType(lobHandler, tm);
|
||||
assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
tmControl.replay();
|
||||
type.nullSafeSet(ps, content, 1);
|
||||
Synchronization synch = transaction.getSynchronization();
|
||||
assertNotNull(synch);
|
||||
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testBlobSerializableType() throws Exception {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject("content");
|
||||
oos.close();
|
||||
|
||||
lobHandler.getBlobAsBinaryStream(rs, "column");
|
||||
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()));
|
||||
lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray());
|
||||
lobCreatorControl.setMatcher(new ArrayMatcher());
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobSerializableType type = new BlobSerializableType(lobHandler, null);
|
||||
assertEquals(1, type.sqlTypes().length);
|
||||
assertEquals(Types.BLOB, type.sqlTypes()[0]);
|
||||
assertEquals(Serializable.class, type.returnedClass());
|
||||
assertTrue(type.isMutable());
|
||||
|
||||
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.nullSafeSet(ps, "content", 1);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testBlobSerializableTypeWithNull() throws Exception {
|
||||
lobHandler.getBlobAsBinaryStream(rs, "column");
|
||||
lobHandlerControl.setReturnValue(null);
|
||||
lobCreator.setBlobAsBytes(ps, 1, null);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobSerializableType type = new BlobSerializableType(lobHandler, null);
|
||||
assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.nullSafeSet(ps, null, 1);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testBlobSerializableTypeWithJtaSynchronization() throws Exception {
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockJtaTransaction transaction = new MockJtaTransaction();
|
||||
tm.getStatus();
|
||||
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(transaction, 1);
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject("content");
|
||||
oos.close();
|
||||
|
||||
lobHandler.getBlobAsBinaryStream(rs, "column");
|
||||
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()));
|
||||
lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray());
|
||||
lobCreatorControl.setMatcher(new ArrayMatcher());
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobSerializableType type = new BlobSerializableType(lobHandler, tm);
|
||||
assertEquals(1, type.sqlTypes().length);
|
||||
assertEquals(Types.BLOB, type.sqlTypes()[0]);
|
||||
assertEquals(Serializable.class, type.returnedClass());
|
||||
assertTrue(type.isMutable());
|
||||
|
||||
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
tmControl.replay();
|
||||
type.nullSafeSet(ps, "content", 1);
|
||||
Synchronization synch = transaction.getSynchronization();
|
||||
assertNotNull(synch);
|
||||
synch.beforeCompletion();
|
||||
synch.afterCompletion(Status.STATUS_COMMITTED);
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testBlobSerializableTypeWithJtaSynchronizationAndRollback() throws Exception {
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockJtaTransaction transaction = new MockJtaTransaction();
|
||||
tm.getStatus();
|
||||
tmControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(transaction, 1);
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject("content");
|
||||
oos.close();
|
||||
|
||||
lobHandler.getBlobAsBinaryStream(rs, "column");
|
||||
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()));
|
||||
lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray());
|
||||
lobCreatorControl.setMatcher(new ArrayMatcher());
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobSerializableType type = new BlobSerializableType(lobHandler, tm);
|
||||
assertEquals(1, type.sqlTypes().length);
|
||||
assertEquals(Types.BLOB, type.sqlTypes()[0]);
|
||||
assertEquals(Serializable.class, type.returnedClass());
|
||||
assertTrue(type.isMutable());
|
||||
|
||||
assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
|
||||
tmControl.replay();
|
||||
type.nullSafeSet(ps, "content", 1);
|
||||
Synchronization synch = transaction.getSynchronization();
|
||||
assertNotNull(synch);
|
||||
synch.afterCompletion(Status.STATUS_ROLLEDBACK);
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testHbm2JavaStyleInitialization() throws Exception {
|
||||
rsControl.reset();
|
||||
psControl.reset();
|
||||
lobHandlerControl.reset();
|
||||
lobCreatorControl.reset();
|
||||
|
||||
ClobStringType cst = null;
|
||||
BlobByteArrayType bbat = null;
|
||||
BlobSerializableType bst = null;
|
||||
try {
|
||||
cst = new ClobStringType();
|
||||
bbat = new BlobByteArrayType();
|
||||
bst = new BlobSerializableType();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
fail("Should not have thrown exception on initialization");
|
||||
}
|
||||
|
||||
try {
|
||||
cst.nullSafeGet(rs, new String[] {"column"}, null);
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
try {
|
||||
bbat.nullSafeGet(rs, new String[] {"column"}, null);
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
try {
|
||||
bst.nullSafeGet(rs, new String[] {"column"}, null);
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
protected void tearDown() {
|
||||
try {
|
||||
rsControl.verify();
|
||||
psControl.verify();
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// ignore: test method didn't call replay
|
||||
}
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,659 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.hibernate3.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.transaction.TransactionManager;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.hibernate.FlushMode;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.classic.Session;
|
||||
import org.hibernate.engine.SessionFactoryImplementor;
|
||||
|
||||
import org.springframework.mock.web.MockFilterConfig;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.mock.web.PassThroughFilterChain;
|
||||
import org.springframework.orm.hibernate3.HibernateAccessor;
|
||||
import org.springframework.orm.hibernate3.HibernateTransactionManager;
|
||||
import org.springframework.orm.hibernate3.SessionFactoryUtils;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.request.ServletWebRequest;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 05.03.2005
|
||||
*/
|
||||
public class OpenSessionInViewTests extends TestCase {
|
||||
|
||||
public void testOpenSessionInViewInterceptorWithSingleSession() throws Exception {
|
||||
|
||||
//SessionFactory sf = createMock(SessionFactory.class);
|
||||
//Session session = createMock(Session.class);
|
||||
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
|
||||
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
|
||||
//expect(mockStorage.size()).andReturn(expectedValue);
|
||||
|
||||
//expect(sf.openSession()).andReturn(session);
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 2);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
session.setFlushMode(FlushMode.MANUAL);
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
|
||||
// check that further invocations simply participate
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
|
||||
assertEquals(session, SessionFactoryUtils.getSession(sf, false));
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
|
||||
sfControl.reset();
|
||||
sessionControl.reset();
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
|
||||
sfControl.reset();
|
||||
sessionControl.reset();
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(sf));
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testOpenSessionInViewInterceptorWithSingleSessionAndJtaTm() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class);
|
||||
final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
tm.getTransaction();
|
||||
tmControl.setReturnValue(null, 2);
|
||||
|
||||
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
sf.getTransactionManager();
|
||||
sfControl.setReturnValue(tm, 2);
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.isOpen();
|
||||
sessionControl.setReturnValue(true, 1);
|
||||
session.setFlushMode(FlushMode.MANUAL);
|
||||
sessionControl.setVoidCallable(1);
|
||||
|
||||
tmControl.replay();
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
|
||||
// check that further invocations simply participate
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
|
||||
assertEquals(session, SessionFactoryUtils.getSession(sf, false));
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
|
||||
sfControl.reset();
|
||||
sessionControl.reset();
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
|
||||
sfControl.reset();
|
||||
sessionControl.reset();
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(sf));
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testOpenSessionInViewInterceptorWithSingleSessionAndFlush() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
|
||||
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setFlushMode(HibernateAccessor.FLUSH_AUTO);
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
|
||||
sfControl.reset();
|
||||
sessionControl.reset();
|
||||
session.flush();
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
|
||||
sfControl.reset();
|
||||
sessionControl.reset();
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(sf));
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testOpenSessionInViewInterceptorAndDeferredClose() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
|
||||
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setSingleSession(false);
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf, 1);
|
||||
session.setFlushMode(FlushMode.MANUAL);
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
|
||||
SessionFactoryUtils.releaseSession(sess, sf);
|
||||
|
||||
// check that further invocations simply participate
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
sfControl.reset();
|
||||
sessionControl.reset();
|
||||
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
}
|
||||
|
||||
public void testOpenSessionInViewFilterWithSingleSession() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf);
|
||||
session.setFlushMode(FlushMode.MANUAL);
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
MockControl sf2Control = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf2 = (SessionFactory) sf2Control.getMock();
|
||||
MockControl session2Control = MockControl.createControl(Session.class);
|
||||
Session session2 = (Session) session2Control.getMock();
|
||||
|
||||
sf2.openSession();
|
||||
sf2Control.setReturnValue(session2, 1);
|
||||
session2.getSessionFactory();
|
||||
session2Control.setReturnValue(sf);
|
||||
session2.setFlushMode(FlushMode.AUTO);
|
||||
session2Control.setVoidCallable(1);
|
||||
session2.close();
|
||||
session2Control.setReturnValue(null, 1);
|
||||
sf2Control.replay();
|
||||
session2Control.replay();
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("mySessionFactory", sf2);
|
||||
wac.refresh();
|
||||
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
|
||||
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
|
||||
filterConfig2.addInitParameter("sessionFactoryBeanName", "mySessionFactory");
|
||||
filterConfig2.addInitParameter("flushMode", "AUTO");
|
||||
|
||||
final OpenSessionInViewFilter filter = new OpenSessionInViewFilter();
|
||||
filter.init(filterConfig);
|
||||
final OpenSessionInViewFilter filter2 = new OpenSessionInViewFilter();
|
||||
filter2.init(filterConfig2);
|
||||
|
||||
final FilterChain filterChain = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
servletRequest.setAttribute("invoked", Boolean.TRUE);
|
||||
}
|
||||
};
|
||||
|
||||
final FilterChain filterChain2 = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
|
||||
throws IOException, ServletException {
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf2));
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
}
|
||||
};
|
||||
|
||||
FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
|
||||
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(sf));
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(sf2));
|
||||
filter2.doFilter(request, response, filterChain3);
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(sf));
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(sf2));
|
||||
assertNotNull(request.getAttribute("invoked"));
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
sf2Control.verify();
|
||||
session2Control.verify();
|
||||
|
||||
wac.close();
|
||||
}
|
||||
|
||||
public void testOpenSessionInViewFilterWithSingleSessionAndPreBoundSession() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
Session session = (Session) sessionControl.getMock();
|
||||
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf);
|
||||
session.setFlushMode(FlushMode.MANUAL);
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf);
|
||||
wac.refresh();
|
||||
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
|
||||
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
|
||||
filterConfig2.addInitParameter("sessionFactoryBeanName", "mySessionFactory");
|
||||
|
||||
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
|
||||
final OpenSessionInViewFilter filter = new OpenSessionInViewFilter();
|
||||
filter.init(filterConfig);
|
||||
|
||||
final FilterChain filterChain = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
servletRequest.setAttribute("invoked", Boolean.TRUE);
|
||||
}
|
||||
};
|
||||
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
filter.doFilter(request, response, filterChain);
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(sf));
|
||||
assertNotNull(request.getAttribute("invoked"));
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
|
||||
wac.close();
|
||||
}
|
||||
|
||||
public void testOpenSessionInViewFilterWithDeferredClose() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
final MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
final Session session = (Session) sessionControl.getMock();
|
||||
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf);
|
||||
session.getFlushMode();
|
||||
sessionControl.setReturnValue(FlushMode.MANUAL, 1);
|
||||
session.setFlushMode(FlushMode.MANUAL);
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
MockControl sf2Control = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf2 = (SessionFactory) sf2Control.getMock();
|
||||
final MockControl session2Control = MockControl.createControl(Session.class);
|
||||
final Session session2 = (Session) session2Control.getMock();
|
||||
MockControl txControl = MockControl.createControl(Transaction.class);
|
||||
Transaction tx = (Transaction) txControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
|
||||
sf2.openSession();
|
||||
sf2Control.setReturnValue(session2, 1);
|
||||
session2.beginTransaction();
|
||||
session2Control.setReturnValue(tx, 1);
|
||||
session2.connection();
|
||||
session2Control.setReturnValue(con, 2);
|
||||
tx.commit();
|
||||
txControl.setVoidCallable(1);
|
||||
session2.isConnected();
|
||||
session2Control.setReturnValue(true, 1);
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(false, 1);
|
||||
session2.setFlushMode(FlushMode.MANUAL);
|
||||
session2Control.setVoidCallable(1);
|
||||
|
||||
sf2Control.replay();
|
||||
session2Control.replay();
|
||||
txControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("mySessionFactory", sf2);
|
||||
wac.refresh();
|
||||
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
|
||||
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
|
||||
filterConfig.addInitParameter("singleSession", "false");
|
||||
filterConfig2.addInitParameter("singleSession", "false");
|
||||
filterConfig2.addInitParameter("sessionFactoryBeanName", "mySessionFactory");
|
||||
|
||||
final OpenSessionInViewFilter filter = new OpenSessionInViewFilter();
|
||||
filter.init(filterConfig);
|
||||
final OpenSessionInViewFilter filter2 = new OpenSessionInViewFilter();
|
||||
filter2.init(filterConfig2);
|
||||
|
||||
final FilterChain filterChain = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
|
||||
HibernateTransactionManager tm = new HibernateTransactionManager(sf);
|
||||
TransactionStatus ts = tm.getTransaction(
|
||||
new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS));
|
||||
org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
|
||||
SessionFactoryUtils.releaseSession(sess, sf);
|
||||
tm.commit(ts);
|
||||
|
||||
sessionControl.verify();
|
||||
sessionControl.reset();
|
||||
|
||||
session.close();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sessionControl.replay();
|
||||
|
||||
servletRequest.setAttribute("invoked", Boolean.TRUE);
|
||||
}
|
||||
};
|
||||
|
||||
final FilterChain filterChain2 = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
|
||||
throws IOException, ServletException {
|
||||
|
||||
HibernateTransactionManager tm = new HibernateTransactionManager(sf2);
|
||||
TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
|
||||
tm.commit(ts);
|
||||
|
||||
session2Control.verify();
|
||||
session2Control.reset();
|
||||
|
||||
session2.close();
|
||||
session2Control.setReturnValue(null, 1);
|
||||
session2Control.replay();
|
||||
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
}
|
||||
};
|
||||
|
||||
FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
|
||||
|
||||
filter2.doFilter(request, response, filterChain3);
|
||||
assertNotNull(request.getAttribute("invoked"));
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
sf2Control.verify();
|
||||
session2Control.verify();
|
||||
txControl.verify();
|
||||
conControl.verify();
|
||||
|
||||
wac.close();
|
||||
}
|
||||
|
||||
public void testOpenSessionInViewFilterWithDeferredCloseAndAlreadyActiveDeferredClose() throws Exception {
|
||||
MockControl sfControl = MockControl.createControl(SessionFactory.class);
|
||||
final SessionFactory sf = (SessionFactory) sfControl.getMock();
|
||||
final MockControl sessionControl = MockControl.createControl(Session.class);
|
||||
final Session session = (Session) sessionControl.getMock();
|
||||
|
||||
sf.openSession();
|
||||
sfControl.setReturnValue(session, 1);
|
||||
session.getSessionFactory();
|
||||
sessionControl.setReturnValue(sf);
|
||||
session.getFlushMode();
|
||||
sessionControl.setReturnValue(FlushMode.MANUAL, 1);
|
||||
session.setFlushMode(FlushMode.MANUAL);
|
||||
sessionControl.setVoidCallable(1);
|
||||
sfControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf);
|
||||
wac.refresh();
|
||||
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
|
||||
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
|
||||
filterConfig.addInitParameter("singleSession", "false");
|
||||
filterConfig2.addInitParameter("singleSession", "false");
|
||||
filterConfig2.addInitParameter("sessionFactoryBeanName", "mySessionFactory");
|
||||
|
||||
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
|
||||
interceptor.setSessionFactory(sf);
|
||||
interceptor.setSingleSession(false);
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
|
||||
final OpenSessionInViewFilter filter = new OpenSessionInViewFilter();
|
||||
filter.init(filterConfig);
|
||||
final OpenSessionInViewFilter filter2 = new OpenSessionInViewFilter();
|
||||
filter2.init(filterConfig2);
|
||||
|
||||
final FilterChain filterChain = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
|
||||
HibernateTransactionManager tm = new HibernateTransactionManager(sf);
|
||||
TransactionStatus ts = tm.getTransaction(
|
||||
new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS));
|
||||
org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true);
|
||||
SessionFactoryUtils.releaseSession(sess, sf);
|
||||
tm.commit(ts);
|
||||
|
||||
sessionControl.verify();
|
||||
sessionControl.reset();
|
||||
try {
|
||||
session.close();
|
||||
}
|
||||
catch (HibernateException ex) {
|
||||
}
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
sessionControl.replay();
|
||||
|
||||
servletRequest.setAttribute("invoked", Boolean.TRUE);
|
||||
}
|
||||
};
|
||||
|
||||
FilterChain filterChain2 = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
|
||||
throws IOException, ServletException {
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
}
|
||||
};
|
||||
|
||||
filter.doFilter(request, response, filterChain2);
|
||||
assertNotNull(request.getAttribute("invoked"));
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
sfControl.verify();
|
||||
sessionControl.verify();
|
||||
|
||||
wac.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.hibernate3.support;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.aop.scope.ScopedObject;
|
||||
|
||||
/**
|
||||
* @author Costin Leau
|
||||
*/
|
||||
public class ScopedBeanInterceptorTests extends TestCase {
|
||||
|
||||
public void testInterceptorWithPlainObject() throws Exception {
|
||||
ScopedBeanInterceptor interceptor = new ScopedBeanInterceptor();
|
||||
final Object realObject = new Object();
|
||||
|
||||
ScopedObject scoped = new ScopedObject() {
|
||||
public Object getTargetObject() {
|
||||
return realObject;
|
||||
}
|
||||
public void removeFromScope() {
|
||||
// do nothing
|
||||
}
|
||||
};
|
||||
|
||||
// default contract is to return null for default behavior
|
||||
assertEquals(null, interceptor.getEntityName(realObject));
|
||||
assertEquals(realObject.getClass().getName(), interceptor.getEntityName(scoped));
|
||||
}
|
||||
|
||||
public void testInterceptorWithCglibProxy() throws Exception {
|
||||
ScopedBeanInterceptor interceptor = new ScopedBeanInterceptor();
|
||||
final Object realObject = new Object();
|
||||
ProxyFactory proxyFactory = new ProxyFactory();
|
||||
proxyFactory.setTarget(realObject);
|
||||
proxyFactory.setProxyTargetClass(true);
|
||||
final Object proxy = proxyFactory.getProxy();
|
||||
|
||||
ScopedObject scoped = new ScopedObject() {
|
||||
public Object getTargetObject() {
|
||||
return proxy;
|
||||
}
|
||||
public void removeFromScope() {
|
||||
// do nothing
|
||||
}
|
||||
};
|
||||
|
||||
assertEquals(realObject.getClass().getName(), interceptor.getEntityName(scoped));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests$TypeTestLocalSessionFactoryBean">
|
||||
<property name="typeDefinitions">
|
||||
<list>
|
||||
<bean class="org.springframework.orm.hibernate3.TypeDefinitionBean">
|
||||
<property name="typeName" value="type1"/>
|
||||
<property name="typeClass" value="mypackage.MyTypeClass"/>
|
||||
<property name="parameters">
|
||||
<props>
|
||||
<prop key="param1">value1</prop>
|
||||
<prop key="otherParam">othervalue</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
<bean id="type2" class="org.springframework.orm.hibernate3.TypeDefinitionBean">
|
||||
<property name="typeName" value="type2"/>
|
||||
<property name="typeClass" value="mypackage.MyOtherTypeClass"/>
|
||||
<property name="parameters">
|
||||
<props>
|
||||
<prop key="myParam">myvalue</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
</list>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,440 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.ibatis;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import com.ibatis.sqlmap.client.SqlMapClient;
|
||||
import com.ibatis.sqlmap.client.SqlMapExecutor;
|
||||
import com.ibatis.sqlmap.client.SqlMapSession;
|
||||
import com.ibatis.sqlmap.client.event.RowHandler;
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
|
||||
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @author Alef Arendsen
|
||||
* @since 09.10.2004
|
||||
*/
|
||||
public class SqlMapClientTests extends TestCase {
|
||||
|
||||
public void testSqlMapClientFactoryBeanWithoutConfig() throws Exception {
|
||||
SqlMapClientFactoryBean factory = new SqlMapClientFactoryBean();
|
||||
// explicitly set to null, don't know why ;-)
|
||||
factory.setConfigLocation(null);
|
||||
try {
|
||||
factory.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testSqlMapClientTemplate() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
MockControl sessionControl = MockControl.createControl(SqlMapSession.class);
|
||||
final SqlMapSession session = (SqlMapSession) sessionControl.getMock();
|
||||
MockControl clientControl = MockControl.createControl(SqlMapClient.class);
|
||||
SqlMapClient client = (SqlMapClient) clientControl.getMock();
|
||||
client.openSession();
|
||||
clientControl.setReturnValue(session, 1);
|
||||
session.getCurrentConnection();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
session.setUserConnection(con);
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.close();
|
||||
sessionControl.setVoidCallable(1);
|
||||
sessionControl.replay();
|
||||
clientControl.replay();
|
||||
|
||||
SqlMapClientTemplate template = new SqlMapClientTemplate();
|
||||
template.setDataSource(ds);
|
||||
template.setSqlMapClient(client);
|
||||
template.afterPropertiesSet();
|
||||
Object result = template.execute(new SqlMapClientCallback() {
|
||||
public Object doInSqlMapClient(SqlMapExecutor executor) {
|
||||
assertTrue(executor == session);
|
||||
return "done";
|
||||
}
|
||||
});
|
||||
assertEquals("done", result);
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
sessionControl.verify();
|
||||
clientControl.verify();
|
||||
}
|
||||
|
||||
public void testSqlMapClientTemplateWithNestedSqlMapSession() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
final Connection con = (Connection) conControl.getMock();
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
MockControl sessionControl = MockControl.createControl(SqlMapSession.class);
|
||||
final SqlMapSession session = (SqlMapSession) sessionControl.getMock();
|
||||
MockControl clientControl = MockControl.createControl(SqlMapClient.class);
|
||||
SqlMapClient client = (SqlMapClient) clientControl.getMock();
|
||||
client.openSession();
|
||||
clientControl.setReturnValue(session, 1);
|
||||
session.getCurrentConnection();
|
||||
sessionControl.setReturnValue(con, 1);
|
||||
sessionControl.replay();
|
||||
clientControl.replay();
|
||||
|
||||
SqlMapClientTemplate template = new SqlMapClientTemplate();
|
||||
template.setDataSource(ds);
|
||||
template.setSqlMapClient(client);
|
||||
template.afterPropertiesSet();
|
||||
Object result = template.execute(new SqlMapClientCallback() {
|
||||
public Object doInSqlMapClient(SqlMapExecutor executor) {
|
||||
assertTrue(executor == session);
|
||||
return "done";
|
||||
}
|
||||
});
|
||||
assertEquals("done", result);
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
sessionControl.verify();
|
||||
clientControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectOnSqlMapSession() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl clientControl = MockControl.createControl(SqlMapClient.class);
|
||||
SqlMapClient client = (SqlMapClient) clientControl.getMock();
|
||||
MockControl sessionControl = MockControl.createControl(SqlMapSession.class);
|
||||
SqlMapSession session = (SqlMapSession) sessionControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
client.getDataSource();
|
||||
clientControl.setReturnValue(ds, 2);
|
||||
client.openSession();
|
||||
clientControl.setReturnValue(session, 1);
|
||||
session.getCurrentConnection();
|
||||
sessionControl.setReturnValue(null, 1);
|
||||
session.setUserConnection(con);
|
||||
sessionControl.setVoidCallable(1);
|
||||
session.queryForObject("myStatement", "myParameter");
|
||||
sessionControl.setReturnValue("myResult", 1);
|
||||
session.close();
|
||||
sessionControl.setVoidCallable(1);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
clientControl.replay();
|
||||
sessionControl.replay();
|
||||
|
||||
SqlMapClientTemplate template = new SqlMapClientTemplate();
|
||||
template.setSqlMapClient(client);
|
||||
template.afterPropertiesSet();
|
||||
assertEquals("myResult", template.queryForObject("myStatement", "myParameter"));
|
||||
|
||||
dsControl.verify();
|
||||
clientControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObject() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForObject("myStatement", null);
|
||||
template.executorControl.setReturnValue("myResult", 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals("myResult", template.queryForObject("myStatement"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithParameter() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForObject("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue("myResult", 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals("myResult", template.queryForObject("myStatement", "myParameter"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithParameterAndResultObject() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForObject("myStatement", "myParameter", "myResult");
|
||||
template.executorControl.setReturnValue("myResult", 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals("myResult", template.queryForObject("myStatement", "myParameter", "myResult"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForList() throws SQLException {
|
||||
List result = new ArrayList();
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForList("myStatement", null);
|
||||
template.executorControl.setReturnValue(result, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(result, template.queryForList("myStatement"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForListWithParameter() throws SQLException {
|
||||
List result = new ArrayList();
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForList("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue(result, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(result, template.queryForList("myStatement", "myParameter"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForListWithResultSize() throws SQLException {
|
||||
List result = new ArrayList();
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForList("myStatement", null, 10, 20);
|
||||
template.executorControl.setReturnValue(result, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(result, template.queryForList("myStatement", 10, 20));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForListParameterAndWithResultSize() throws SQLException {
|
||||
List result = new ArrayList();
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForList("myStatement", "myParameter", 10, 20);
|
||||
template.executorControl.setReturnValue(result, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(result, template.queryForList("myStatement", "myParameter", 10, 20));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryWithRowHandler() throws SQLException {
|
||||
RowHandler rowHandler = new TestRowHandler();
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryWithRowHandler("myStatement", null, rowHandler);
|
||||
template.executorControl.setVoidCallable(1);
|
||||
template.executorControl.replay();
|
||||
template.queryWithRowHandler("myStatement", rowHandler);
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryWithRowHandlerWithParameter() throws SQLException {
|
||||
RowHandler rowHandler = new TestRowHandler();
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryWithRowHandler("myStatement", "myParameter", rowHandler);
|
||||
template.executorControl.setVoidCallable(1);
|
||||
template.executorControl.replay();
|
||||
template.queryWithRowHandler("myStatement", "myParameter", rowHandler);
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForMap() throws SQLException {
|
||||
Map result = new HashMap();
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForMap("myStatement", "myParameter", "myKey");
|
||||
template.executorControl.setReturnValue(result, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(result, template.queryForMap("myStatement", "myParameter", "myKey"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testQueryForMapWithValueProperty() throws SQLException {
|
||||
Map result = new HashMap();
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.queryForMap("myStatement", "myParameter", "myKey", "myValue");
|
||||
template.executorControl.setReturnValue(result, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(result, template.queryForMap("myStatement", "myParameter", "myKey", "myValue"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testInsert() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.insert("myStatement", null);
|
||||
template.executorControl.setReturnValue("myResult", 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals("myResult", template.insert("myStatement"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testInsertWithParameter() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.insert("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue("myResult", 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals("myResult", template.insert("myStatement", "myParameter"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testUpdate() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.update("myStatement", null);
|
||||
template.executorControl.setReturnValue(10, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(10, template.update("myStatement"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testUpdateWithParameter() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.update("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue(10, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(10, template.update("myStatement", "myParameter"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testUpdateWithRequiredRowsAffected() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.update("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue(10, 1);
|
||||
template.executorControl.replay();
|
||||
template.update("myStatement", "myParameter", 10);
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testUpdateWithRequiredRowsAffectedAndInvalidRowCount() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.update("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue(20, 1);
|
||||
template.executorControl.replay();
|
||||
try {
|
||||
template.update("myStatement", "myParameter", 10);
|
||||
fail("Should have thrown JdbcUpdateAffectedIncorrectNumberOfRowsException");
|
||||
}
|
||||
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException ex) {
|
||||
// expected
|
||||
assertEquals(10, ex.getExpectedRowsAffected());
|
||||
assertEquals(20, ex.getActualRowsAffected());
|
||||
}
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testDelete() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.delete("myStatement", null);
|
||||
template.executorControl.setReturnValue(10, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(10, template.delete("myStatement"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testDeleteWithParameter() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.delete("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue(10, 1);
|
||||
template.executorControl.replay();
|
||||
assertEquals(10, template.delete("myStatement", "myParameter"));
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testDeleteWithRequiredRowsAffected() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.delete("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue(10, 1);
|
||||
template.executorControl.replay();
|
||||
template.delete("myStatement", "myParameter", 10);
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testDeleteWithRequiredRowsAffectedAndInvalidRowCount() throws SQLException {
|
||||
TestSqlMapClientTemplate template = new TestSqlMapClientTemplate();
|
||||
template.executor.delete("myStatement", "myParameter");
|
||||
template.executorControl.setReturnValue(20, 1);
|
||||
template.executorControl.replay();
|
||||
try {
|
||||
template.delete("myStatement", "myParameter", 10);
|
||||
fail("Should have thrown JdbcUpdateAffectedIncorrectNumberOfRowsException");
|
||||
}
|
||||
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException ex) {
|
||||
// expected
|
||||
assertEquals(10, ex.getExpectedRowsAffected());
|
||||
assertEquals(20, ex.getActualRowsAffected());
|
||||
}
|
||||
template.executorControl.verify();
|
||||
}
|
||||
|
||||
public void testSqlMapClientDaoSupport() throws Exception {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
SqlMapClientDaoSupport testDao = new SqlMapClientDaoSupport() {
|
||||
};
|
||||
testDao.setDataSource(ds);
|
||||
assertEquals(ds, testDao.getDataSource());
|
||||
|
||||
MockControl clientControl = MockControl.createControl(SqlMapClient.class);
|
||||
SqlMapClient client = (SqlMapClient) clientControl.getMock();
|
||||
clientControl.replay();
|
||||
|
||||
testDao.setSqlMapClient(client);
|
||||
assertEquals(client, testDao.getSqlMapClient());
|
||||
|
||||
SqlMapClientTemplate template = new SqlMapClientTemplate();
|
||||
template.setDataSource(ds);
|
||||
template.setSqlMapClient(client);
|
||||
testDao.setSqlMapClientTemplate(template);
|
||||
assertEquals(template, testDao.getSqlMapClientTemplate());
|
||||
|
||||
testDao.afterPropertiesSet();
|
||||
}
|
||||
|
||||
|
||||
private static class TestSqlMapClientTemplate extends SqlMapClientTemplate {
|
||||
|
||||
public MockControl executorControl = MockControl.createControl(SqlMapExecutor.class);
|
||||
public SqlMapExecutor executor = (SqlMapExecutor) executorControl.getMock();
|
||||
|
||||
public Object execute(SqlMapClientCallback action) throws DataAccessException {
|
||||
try {
|
||||
return action.doInSqlMapClient(executor);
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
throw getExceptionTranslator().translate("SqlMapClient operation", null, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class TestRowHandler implements RowHandler {
|
||||
|
||||
public void handleRow(Object row) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.ibatis.support;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.ArgumentsMatcher;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.jdbc.datasource.DataSourceUtils;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
import org.springframework.jdbc.support.lob.LobHandler;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 27.02.2005
|
||||
*/
|
||||
public class LobTypeHandlerTests extends TestCase {
|
||||
|
||||
private MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
private ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
private MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
private PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
private MockControl lobHandlerControl = MockControl.createControl(LobHandler.class);
|
||||
private LobHandler lobHandler = (LobHandler) lobHandlerControl.getMock();
|
||||
private MockControl lobCreatorControl = MockControl.createControl(LobCreator.class);
|
||||
private LobCreator lobCreator = (LobCreator) lobCreatorControl.getMock();
|
||||
|
||||
protected void setUp() throws SQLException {
|
||||
rs.findColumn("column");
|
||||
rsControl.setReturnValue(1);
|
||||
|
||||
lobHandler.getLobCreator();
|
||||
lobHandlerControl.setReturnValue(lobCreator);
|
||||
lobCreator.close();
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
rsControl.replay();
|
||||
psControl.replay();
|
||||
}
|
||||
|
||||
public void testClobStringTypeHandler() throws Exception {
|
||||
lobHandler.getClobAsString(rs, 1);
|
||||
lobHandlerControl.setReturnValue("content", 2);
|
||||
lobCreator.setClobAsString(ps, 1, "content");
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
ClobStringTypeHandler type = new ClobStringTypeHandler(lobHandler);
|
||||
assertEquals("content", type.valueOf("content"));
|
||||
assertEquals("content", type.getResult(rs, "column"));
|
||||
assertEquals("content", type.getResult(rs, 1));
|
||||
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.setParameter(ps, 1, "content", null);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
assertTrue(synchs.get(0).getClass().getName().endsWith("LobCreatorSynchronization"));
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testClobStringTypeWithSynchronizedConnection() throws Exception {
|
||||
DataSource dsTarget = new DriverManagerDataSource();
|
||||
DataSource ds = new LazyConnectionDataSourceProxy(dsTarget);
|
||||
|
||||
lobHandler.getClobAsString(rs, 1);
|
||||
lobHandlerControl.setReturnValue("content", 2);
|
||||
lobCreator.setClobAsString(ps, 1, "content");
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
ClobStringTypeHandler type = new ClobStringTypeHandler(lobHandler);
|
||||
assertEquals("content", type.valueOf("content"));
|
||||
assertEquals("content", type.getResult(rs, "column"));
|
||||
assertEquals("content", type.getResult(rs, 1));
|
||||
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
DataSourceUtils.getConnection(ds);
|
||||
type.setParameter(ps, 1, "content", null);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(2, synchs.size());
|
||||
assertTrue(synchs.get(0).getClass().getName().endsWith("LobCreatorSynchronization"));
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
((TransactionSynchronization) synchs.get(1)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(1)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testBlobByteArrayType() throws Exception {
|
||||
byte[] content = "content".getBytes();
|
||||
lobHandler.getBlobAsBytes(rs, 1);
|
||||
lobHandlerControl.setReturnValue(content, 2);
|
||||
lobCreator.setBlobAsBytes(ps, 1, content);
|
||||
lobCreatorControl.setVoidCallable(1);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobByteArrayTypeHandler type = new BlobByteArrayTypeHandler(lobHandler);
|
||||
assertTrue(Arrays.equals(content, (byte[]) type.valueOf("content")));
|
||||
assertEquals(content, type.getResult(rs, "column"));
|
||||
assertEquals(content, type.getResult(rs, 1));
|
||||
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.setParameter(ps, 1, content, null);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testBlobSerializableType() throws Exception {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject("content");
|
||||
oos.close();
|
||||
|
||||
lobHandler.getBlobAsBinaryStream(rs, 1);
|
||||
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()), 1);
|
||||
lobHandler.getBlobAsBinaryStream(rs, 1);
|
||||
lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()), 1);
|
||||
lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray());
|
||||
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
|
||||
public boolean matches(Object[] o1, Object[] o2) {
|
||||
return Arrays.equals((byte[]) o1[2], (byte[]) o2[2]);
|
||||
}
|
||||
public String toString(Object[] objects) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobSerializableTypeHandler type = new BlobSerializableTypeHandler(lobHandler);
|
||||
assertEquals("content", type.valueOf("content"));
|
||||
assertEquals("content", type.getResult(rs, "column"));
|
||||
assertEquals("content", type.getResult(rs, 1));
|
||||
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.setParameter(ps, 1, "content", null);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
public void testBlobSerializableTypeWithNull() throws Exception {
|
||||
lobHandler.getBlobAsBinaryStream(rs, 1);
|
||||
lobHandlerControl.setReturnValue(null, 2);
|
||||
lobCreator.setBlobAsBytes(ps, 1, null);
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
|
||||
BlobSerializableTypeHandler type = new BlobSerializableTypeHandler(lobHandler);
|
||||
assertEquals(null, type.valueOf(null));
|
||||
assertEquals(null, type.getResult(rs, "column"));
|
||||
assertEquals(null, type.getResult(rs, 1));
|
||||
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
try {
|
||||
type.setParameter(ps, 1, null, null);
|
||||
List synchs = TransactionSynchronizationManager.getSynchronizations();
|
||||
assertEquals(1, synchs.size());
|
||||
((TransactionSynchronization) synchs.get(0)).beforeCompletion();
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
}
|
||||
|
||||
protected void tearDown() {
|
||||
try {
|
||||
rsControl.verify();
|
||||
psControl.verify();
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// ignore: test method didn't call replay
|
||||
}
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jdo;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.aopalliance.intercept.Interceptor;
|
||||
import org.aopalliance.intercept.Invocation;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.easymock.MockControl;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class JdoInterceptorTests extends TestCase {
|
||||
|
||||
public void testInterceptor() {
|
||||
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
|
||||
PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
|
||||
MockControl pmControl = MockControl.createControl(PersistenceManager.class);
|
||||
PersistenceManager pm = (PersistenceManager) pmControl.getMock();
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm, 1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoInterceptor interceptor = new JdoInterceptor();
|
||||
interceptor.setPersistenceManagerFactory(pmf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(pmf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
|
||||
pmfControl.verify();
|
||||
pmControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithPrebound() {
|
||||
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
|
||||
PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
|
||||
MockControl pmControl = MockControl.createControl(PersistenceManager.class);
|
||||
PersistenceManager pm = (PersistenceManager) pmControl.getMock();
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm));
|
||||
JdoInterceptor interceptor = new JdoInterceptor();
|
||||
interceptor.setPersistenceManagerFactory(pmf);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(pmf));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(pmf);
|
||||
}
|
||||
|
||||
pmfControl.verify();
|
||||
pmControl.verify();
|
||||
}
|
||||
|
||||
|
||||
private static class TestInvocation implements MethodInvocation {
|
||||
|
||||
private PersistenceManagerFactory persistenceManagerFactory;
|
||||
|
||||
public TestInvocation(PersistenceManagerFactory persistenceManagerFactory) {
|
||||
this.persistenceManagerFactory = persistenceManagerFactory;
|
||||
}
|
||||
|
||||
public Object proceed() throws Throwable {
|
||||
if (!TransactionSynchronizationManager.hasResource(this.persistenceManagerFactory)) {
|
||||
throw new IllegalStateException("PersistenceManager not bound");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object[] getArguments() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public int getCurrentInterceptorIndex() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getNumberOfInterceptors() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Interceptor getInterceptor(int i) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Method getMethod() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public AccessibleObject getStaticPart() {
|
||||
return getMethod();
|
||||
}
|
||||
|
||||
public Object getArgument(int i) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setArgument(int i, Object handler) {
|
||||
}
|
||||
|
||||
public int getArgumentCount() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Object getThis() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object getProxy() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Invocation cloneInstance() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void release() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,743 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jdo;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.jdo.JDODataStoreException;
|
||||
import javax.jdo.JDOException;
|
||||
import javax.jdo.JDOFatalDataStoreException;
|
||||
import javax.jdo.JDOFatalUserException;
|
||||
import javax.jdo.JDOObjectNotFoundException;
|
||||
import javax.jdo.JDOOptimisticVerificationException;
|
||||
import javax.jdo.JDOUserException;
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.jdo.Query;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 03.06.2003
|
||||
*/
|
||||
public class JdoTemplateTests extends TestCase {
|
||||
|
||||
private MockControl pmfControl;
|
||||
private PersistenceManagerFactory pmf;
|
||||
private MockControl pmControl;
|
||||
private PersistenceManager pm;
|
||||
|
||||
protected void setUp() {
|
||||
pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
|
||||
pmf = (PersistenceManagerFactory) pmfControl.getMock();
|
||||
pmControl = MockControl.createControl(PersistenceManager.class);
|
||||
pm = (PersistenceManager) pmControl.getMock();
|
||||
pmf.getConnectionFactory();
|
||||
pmfControl.setReturnValue(null, 1);
|
||||
}
|
||||
|
||||
protected void tearDown() {
|
||||
try {
|
||||
pmfControl.verify();
|
||||
pmControl.verify();
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// ignore: test method didn't call replay
|
||||
}
|
||||
}
|
||||
|
||||
public void testTemplateExecuteWithNotAllowCreate() {
|
||||
JdoTemplate jt = new JdoTemplate();
|
||||
jt.setPersistenceManagerFactory(pmf);
|
||||
jt.setAllowCreate(false);
|
||||
try {
|
||||
jt.execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testTemplateExecuteWithNotAllowCreateAndThreadBound() {
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.setAllowCreate(false);
|
||||
TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm));
|
||||
final List l = new ArrayList();
|
||||
l.add("test");
|
||||
List result = (List) jt.execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
return l;
|
||||
}
|
||||
});
|
||||
assertTrue("Correct result list", result == l);
|
||||
TransactionSynchronizationManager.unbindResource(pmf);
|
||||
}
|
||||
|
||||
public void testTemplateExecuteWithNewPersistenceManager() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm, 1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
final List l = new ArrayList();
|
||||
l.add("test");
|
||||
List result = (List) jt.execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
return l;
|
||||
}
|
||||
});
|
||||
assertTrue("Correct result list", result == l);
|
||||
}
|
||||
|
||||
public void testTemplateExecuteWithThreadBoundAndFlushEager() {
|
||||
pm.flush();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.setFlushEager(true);
|
||||
jt.setAllowCreate(false);
|
||||
TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm));
|
||||
final List l = new ArrayList();
|
||||
l.add("test");
|
||||
List result = (List) jt.execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
return l;
|
||||
}
|
||||
});
|
||||
assertTrue("Correct result list", result == l);
|
||||
TransactionSynchronizationManager.unbindResource(pmf);
|
||||
}
|
||||
|
||||
public void testGetObjectById() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.getObjectById("0", true);
|
||||
pmControl.setReturnValue("A");
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals("A", jt.getObjectById("0"));
|
||||
}
|
||||
|
||||
public void testGetObjectByIdWithClassAndValue() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.getObjectById(String.class, "0");
|
||||
pmControl.setReturnValue("A");
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals("A", jt.getObjectById(String.class, "0"));
|
||||
}
|
||||
|
||||
public void testEvict() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.evict("0");
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.evict("0");
|
||||
}
|
||||
|
||||
public void testEvictAllWithCollection() {
|
||||
Collection coll = new HashSet();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.evictAll(coll);
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.evictAll(coll);
|
||||
}
|
||||
|
||||
public void testEvictAll() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.evictAll();
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.evictAll();
|
||||
}
|
||||
|
||||
public void testRefresh() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.refresh("0");
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.refresh("0");
|
||||
}
|
||||
|
||||
public void testRefreshAllWithCollection() {
|
||||
Collection coll = new HashSet();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.refreshAll(coll);
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.refreshAll(coll);
|
||||
}
|
||||
|
||||
public void testRefreshAll() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.refreshAll();
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.refreshAll();
|
||||
}
|
||||
|
||||
public void testMakePersistent() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.makePersistent("0");
|
||||
pmControl.setReturnValue(null, 1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.makePersistent("0");
|
||||
}
|
||||
|
||||
public void testMakePersistentAll() {
|
||||
Collection coll = new HashSet();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.makePersistentAll(coll);
|
||||
pmControl.setReturnValue(null, 1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.makePersistentAll(coll);
|
||||
}
|
||||
|
||||
public void testDeletePersistent() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.deletePersistent("0");
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.deletePersistent("0");
|
||||
}
|
||||
|
||||
public void testDeletePersistentAll() {
|
||||
Collection coll = new HashSet();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.deletePersistentAll(coll);
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.deletePersistentAll(coll);
|
||||
}
|
||||
|
||||
public void testDetachCopy() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.detachCopy("0");
|
||||
pmControl.setReturnValue("0x", 1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals("0x", jt.detachCopy("0"));
|
||||
}
|
||||
|
||||
public void testDetachCopyAll() {
|
||||
Collection attached = new HashSet();
|
||||
Collection detached = new HashSet();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.detachCopyAll(attached);
|
||||
pmControl.setReturnValue(detached, 1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(detached, jt.detachCopyAll(attached));
|
||||
}
|
||||
|
||||
public void testFlush() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.flush();
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.flush();
|
||||
}
|
||||
|
||||
public void testFlushWithDialect() {
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.flush();
|
||||
pmControl.setVoidCallable(1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
jt.flush();
|
||||
}
|
||||
|
||||
public void testFind() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery(String.class);
|
||||
pmControl.setReturnValue(query);
|
||||
Collection coll = new HashSet();
|
||||
query.execute();
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find(String.class));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindWithFilter() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery(String.class, "a == b");
|
||||
pmControl.setReturnValue(query);
|
||||
Collection coll = new HashSet();
|
||||
query.execute();
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find(String.class, "a == b"));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindWithFilterAndOrdering() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery(String.class, "a == b");
|
||||
pmControl.setReturnValue(query);
|
||||
query.setOrdering("c asc");
|
||||
queryControl.setVoidCallable(1);
|
||||
Collection coll = new HashSet();
|
||||
query.execute();
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find(String.class, "a == b", "c asc"));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindWithParameterArray() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery(String.class, "a == b");
|
||||
pmControl.setReturnValue(query);
|
||||
query.declareParameters("params");
|
||||
queryControl.setVoidCallable(1);
|
||||
Object[] values = new Object[0];
|
||||
Collection coll = new HashSet();
|
||||
query.executeWithArray(values);
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find(String.class, "a == b", "params", values));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindWithParameterArrayAndOrdering() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery(String.class, "a == b");
|
||||
pmControl.setReturnValue(query);
|
||||
query.declareParameters("params");
|
||||
queryControl.setVoidCallable(1);
|
||||
query.setOrdering("c asc");
|
||||
queryControl.setVoidCallable(1);
|
||||
Object[] values = new Object[0];
|
||||
Collection coll = new HashSet();
|
||||
query.executeWithArray(values);
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find(String.class, "a == b", "params", values, "c asc"));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindWithParameterMap() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery(String.class, "a == b");
|
||||
pmControl.setReturnValue(query);
|
||||
query.declareParameters("params");
|
||||
queryControl.setVoidCallable(1);
|
||||
Map values = new HashMap();
|
||||
Collection coll = new HashSet();
|
||||
query.executeWithMap(values);
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find(String.class, "a == b", "params", values));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindWithParameterMapAndOrdering() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery(String.class, "a == b");
|
||||
pmControl.setReturnValue(query);
|
||||
query.declareParameters("params");
|
||||
queryControl.setVoidCallable(1);
|
||||
query.setOrdering("c asc");
|
||||
queryControl.setVoidCallable(1);
|
||||
Map values = new HashMap();
|
||||
Collection coll = new HashSet();
|
||||
query.executeWithMap(values);
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find(String.class, "a == b", "params", values, "c asc"));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindWithLanguageAndQueryObject() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery(Query.SQL, "some SQL");
|
||||
pmControl.setReturnValue(query);
|
||||
Collection coll = new HashSet();
|
||||
query.execute();
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find(Query.SQL, "some SQL"));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindWithQueryString() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newQuery("single string query");
|
||||
pmControl.setReturnValue(query);
|
||||
Collection coll = new HashSet();
|
||||
query.execute();
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.find("single string query"));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testFindByNamedQuery() {
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm);
|
||||
pm.newNamedQuery(String.class, "some query name");
|
||||
pmControl.setReturnValue(query);
|
||||
Collection coll = new HashSet();
|
||||
query.execute();
|
||||
queryControl.setReturnValue(coll);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
JdoTemplate jt = new JdoTemplate(pmf);
|
||||
assertEquals(coll, jt.findByNamedQuery(String.class, "some query name"));
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
public void testTemplateExceptions() {
|
||||
try {
|
||||
createTemplate().execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
throw new JDOObjectNotFoundException();
|
||||
}
|
||||
});
|
||||
fail("Should have thrown JdoObjectRetrievalFailureException");
|
||||
}
|
||||
catch (JdoObjectRetrievalFailureException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
try {
|
||||
createTemplate().execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
throw new JDOOptimisticVerificationException();
|
||||
}
|
||||
});
|
||||
fail("Should have thrown JdoOptimisticLockingFailureException");
|
||||
}
|
||||
catch (JdoOptimisticLockingFailureException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
try {
|
||||
createTemplate().execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
throw new JDODataStoreException();
|
||||
}
|
||||
});
|
||||
fail("Should have thrown JdoResourceFailureException");
|
||||
}
|
||||
catch (JdoResourceFailureException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
try {
|
||||
createTemplate().execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
throw new JDOFatalDataStoreException();
|
||||
}
|
||||
});
|
||||
fail("Should have thrown JdoResourceFailureException");
|
||||
}
|
||||
catch (JdoResourceFailureException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
try {
|
||||
createTemplate().execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
throw new JDOUserException();
|
||||
}
|
||||
});
|
||||
fail("Should have thrown JdoUsageException");
|
||||
}
|
||||
catch (JdoUsageException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
try {
|
||||
createTemplate().execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
throw new JDOFatalUserException();
|
||||
}
|
||||
});
|
||||
fail("Should have thrown JdoUsageException");
|
||||
}
|
||||
catch (JdoUsageException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
try {
|
||||
createTemplate().execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
throw new JDOException();
|
||||
}
|
||||
});
|
||||
fail("Should have thrown JdoSystemException");
|
||||
}
|
||||
catch (JdoSystemException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testTranslateException() {
|
||||
MockControl dialectControl = MockControl.createControl(JdoDialect.class);
|
||||
JdoDialect dialect = (JdoDialect) dialectControl.getMock();
|
||||
final JDOException ex = new JDOException();
|
||||
dialect.translateException(ex);
|
||||
dialectControl.setReturnValue(new DataIntegrityViolationException("test", ex));
|
||||
dialectControl.replay();
|
||||
try {
|
||||
JdoTemplate template = createTemplate();
|
||||
template.setJdoDialect(dialect);
|
||||
template.execute(new JdoCallback() {
|
||||
public Object doInJdo(PersistenceManager pm) {
|
||||
throw ex;
|
||||
}
|
||||
});
|
||||
fail("Should have thrown DataIntegrityViolationException");
|
||||
}
|
||||
catch (DataIntegrityViolationException dive) {
|
||||
// expected
|
||||
}
|
||||
dialectControl.verify();
|
||||
}
|
||||
|
||||
private JdoTemplate createTemplate() {
|
||||
pmfControl.reset();
|
||||
pmControl.reset();
|
||||
pmf.getConnectionFactory();
|
||||
pmfControl.setReturnValue(null, 1);
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm, 1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
return new JdoTemplate(pmf);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jdo;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.jdo.JDOFatalUserException;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class LocalPersistenceManagerFactoryTests extends TestCase {
|
||||
|
||||
public void testLocalPersistenceManagerFactoryBean() throws IOException {
|
||||
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
|
||||
final PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
|
||||
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
|
||||
protected PersistenceManagerFactory newPersistenceManagerFactory(Map props) {
|
||||
return pmf;
|
||||
}
|
||||
};
|
||||
pmfb.setJdoProperties(new Properties());
|
||||
pmfb.afterPropertiesSet();
|
||||
assertSame(pmf, pmfb.getObject());
|
||||
}
|
||||
|
||||
public void testLocalPersistenceManagerFactoryBeanWithInvalidSettings() throws IOException {
|
||||
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean();
|
||||
try {
|
||||
pmfb.afterPropertiesSet();
|
||||
fail("Should have thrown JDOFatalUserException");
|
||||
}
|
||||
catch (JDOFatalUserException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalPersistenceManagerFactoryBeanWithIncompleteProperties() throws IOException {
|
||||
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean();
|
||||
Properties props = new Properties();
|
||||
props.setProperty("myKey", "myValue");
|
||||
pmfb.setJdoProperties(props);
|
||||
try {
|
||||
pmfb.afterPropertiesSet();
|
||||
fail("Should have thrown JDOFatalUserException");
|
||||
}
|
||||
catch (JDOFatalUserException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalPersistenceManagerFactoryBeanWithInvalidProperty() throws IOException {
|
||||
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
|
||||
protected PersistenceManagerFactory newPersistenceManagerFactory(Map props) {
|
||||
throw new IllegalArgumentException((String) props.get("myKey"));
|
||||
}
|
||||
};
|
||||
Properties props = new Properties();
|
||||
props.setProperty("myKey", "myValue");
|
||||
pmfb.setJdoProperties(props);
|
||||
try {
|
||||
pmfb.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
assertTrue("Correct exception", "myValue".equals(ex.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalPersistenceManagerFactoryBeanWithFile() throws IOException {
|
||||
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
|
||||
protected PersistenceManagerFactory newPersistenceManagerFactory(Map props) {
|
||||
throw new IllegalArgumentException((String) props.get("myKey"));
|
||||
}
|
||||
};
|
||||
pmfb.setConfigLocation(new ClassPathResource("test.properties", getClass()));
|
||||
try {
|
||||
pmfb.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
assertTrue("Correct exception", "myValue".equals(ex.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalPersistenceManagerFactoryBeanWithName() throws IOException {
|
||||
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
|
||||
protected PersistenceManagerFactory newPersistenceManagerFactory(String name) {
|
||||
throw new IllegalArgumentException(name);
|
||||
}
|
||||
};
|
||||
pmfb.setPersistenceManagerFactoryName("myName");
|
||||
try {
|
||||
pmfb.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
assertTrue("Correct exception", "myName".equals(ex.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testLocalPersistenceManagerFactoryBeanWithNameAndProperties() throws IOException {
|
||||
LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() {
|
||||
protected PersistenceManagerFactory newPersistenceManagerFactory(String name) {
|
||||
throw new IllegalArgumentException(name);
|
||||
}
|
||||
};
|
||||
pmfb.setPersistenceManagerFactoryName("myName");
|
||||
pmfb.getJdoPropertyMap().put("myKey", "myValue");
|
||||
try {
|
||||
pmfb.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getMessage().indexOf("persistenceManagerFactoryName") != -1);
|
||||
assertTrue(ex.getMessage().indexOf("jdoProp") != -1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jdo.support;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.orm.jdo.JdoTemplate;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 30.07.2003
|
||||
*/
|
||||
public class JdoDaoSupportTests extends TestCase {
|
||||
|
||||
public void testJdoDaoSupportWithPersistenceManagerFactory() throws Exception {
|
||||
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
|
||||
PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
|
||||
pmf.getConnectionFactory();
|
||||
pmfControl.setReturnValue(null, 1);
|
||||
pmfControl.replay();
|
||||
final List test = new ArrayList();
|
||||
JdoDaoSupport dao = new JdoDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setPersistenceManagerFactory(pmf);
|
||||
dao.afterPropertiesSet();
|
||||
assertEquals("Correct PersistenceManagerFactory", pmf, dao.getPersistenceManagerFactory());
|
||||
assertEquals("Correct JdoTemplate", pmf, dao.getJdoTemplate().getPersistenceManagerFactory());
|
||||
assertEquals("initDao called", test.size(), 1);
|
||||
pmfControl.verify();
|
||||
}
|
||||
|
||||
public void testJdoDaoSupportWithJdoTemplate() throws Exception {
|
||||
JdoTemplate template = new JdoTemplate();
|
||||
final List test = new ArrayList();
|
||||
JdoDaoSupport dao = new JdoDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setJdoTemplate(template);
|
||||
dao.afterPropertiesSet();
|
||||
assertEquals("Correct JdoTemplate", template, dao.getJdoTemplate());
|
||||
assertEquals("initDao called", test.size(), 1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jdo.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.jdo.PersistenceManager;
|
||||
import javax.jdo.PersistenceManagerFactory;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.mock.web.MockFilterConfig;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.mock.web.PassThroughFilterChain;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.request.ServletWebRequest;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
* @since 15.06.2004
|
||||
*/
|
||||
public class OpenPersistenceManagerInViewTests extends TestCase {
|
||||
|
||||
public void testOpenPersistenceManagerInViewInterceptor() throws Exception {
|
||||
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
|
||||
PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
|
||||
MockControl pmControl = MockControl.createControl(PersistenceManager.class);
|
||||
PersistenceManager pm = (PersistenceManager) pmControl.getMock();
|
||||
|
||||
OpenPersistenceManagerInViewInterceptor interceptor = new OpenPersistenceManagerInViewInterceptor();
|
||||
interceptor.setPersistenceManagerFactory(pmf);
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm, 1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(pmf));
|
||||
|
||||
// check that further invocations simply participate
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
pmfControl.verify();
|
||||
pmControl.verify();
|
||||
|
||||
pmfControl.reset();
|
||||
pmControl.reset();
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(pmf));
|
||||
pmfControl.verify();
|
||||
pmControl.verify();
|
||||
|
||||
pmfControl.reset();
|
||||
pmControl.reset();
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(pmf));
|
||||
pmfControl.verify();
|
||||
pmControl.verify();
|
||||
}
|
||||
|
||||
public void testOpenPersistenceManagerInViewFilter() throws Exception {
|
||||
MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
|
||||
final PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
|
||||
MockControl pmControl = MockControl.createControl(PersistenceManager.class);
|
||||
PersistenceManager pm = (PersistenceManager) pmControl.getMock();
|
||||
|
||||
pmf.getPersistenceManager();
|
||||
pmfControl.setReturnValue(pm, 1);
|
||||
pm.close();
|
||||
pmControl.setVoidCallable(1);
|
||||
pmfControl.replay();
|
||||
pmControl.replay();
|
||||
|
||||
MockControl pmf2Control = MockControl.createControl(PersistenceManagerFactory.class);
|
||||
final PersistenceManagerFactory pmf2 = (PersistenceManagerFactory) pmf2Control.getMock();
|
||||
MockControl pm2Control = MockControl.createControl(PersistenceManager.class);
|
||||
PersistenceManager pm2 = (PersistenceManager) pm2Control.getMock();
|
||||
|
||||
pmf2.getPersistenceManager();
|
||||
pmf2Control.setReturnValue(pm2, 1);
|
||||
pm2.close();
|
||||
pm2Control.setVoidCallable(1);
|
||||
pmf2Control.replay();
|
||||
pm2Control.replay();
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("persistenceManagerFactory", pmf);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("myPersistenceManagerFactory", pmf2);
|
||||
wac.refresh();
|
||||
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
|
||||
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
|
||||
filterConfig2.addInitParameter("persistenceManagerFactoryBeanName", "myPersistenceManagerFactory");
|
||||
|
||||
final OpenPersistenceManagerInViewFilter filter = new OpenPersistenceManagerInViewFilter();
|
||||
filter.init(filterConfig);
|
||||
final OpenPersistenceManagerInViewFilter filter2 = new OpenPersistenceManagerInViewFilter();
|
||||
filter2.init(filterConfig2);
|
||||
|
||||
final FilterChain filterChain = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(pmf));
|
||||
servletRequest.setAttribute("invoked", Boolean.TRUE);
|
||||
}
|
||||
};
|
||||
|
||||
final FilterChain filterChain2 = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
|
||||
throws IOException, ServletException {
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(pmf2));
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
}
|
||||
};
|
||||
|
||||
FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
|
||||
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(pmf));
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(pmf2));
|
||||
filter2.doFilter(request, response, filterChain3);
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(pmf));
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(pmf2));
|
||||
assertNotNull(request.getAttribute("invoked"));
|
||||
|
||||
pmfControl.verify();
|
||||
pmControl.verify();
|
||||
pmf2Control.verify();
|
||||
pm2Control.verify();
|
||||
|
||||
wac.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
myKey=myValue
|
||||
@@ -0,0 +1,272 @@
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.List;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityNotFoundException;
|
||||
import javax.persistence.FlushModeType;
|
||||
import javax.persistence.NoResultException;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.orm.jpa.domain.DriversLicense;
|
||||
import org.springframework.orm.jpa.domain.Person;
|
||||
import org.springframework.test.annotation.ExpectedException;
|
||||
import org.springframework.test.annotation.NotTransactional;
|
||||
import org.springframework.test.annotation.Repeat;
|
||||
import org.springframework.test.annotation.Timed;
|
||||
import org.springframework.util.SerializationTestUtils;
|
||||
|
||||
/**
|
||||
* Integration tests for LocalContainerEntityManagerFactoryBean.
|
||||
* Uses an in-memory database.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public abstract class AbstractContainerEntityManagerFactoryIntegrationTests
|
||||
extends AbstractEntityManagerFactoryIntegrationTests {
|
||||
|
||||
@NotTransactional
|
||||
public void testEntityManagerFactoryImplementsEntityManagerFactoryInfo() {
|
||||
assertTrue(Proxy.isProxyClass(entityManagerFactory.getClass()));
|
||||
assertTrue("Must have introduced config interface",
|
||||
entityManagerFactory instanceof EntityManagerFactoryInfo);
|
||||
EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory;
|
||||
//assertEquals("Person", emfi.getPersistenceUnitName());
|
||||
assertNotNull("PersistenceUnitInfo must be available", emfi.getPersistenceUnitInfo());
|
||||
assertNotNull("Raw EntityManagerFactory must be available", emfi.getNativeEntityManagerFactory());
|
||||
}
|
||||
|
||||
public void testStateClean() {
|
||||
assertEquals("Should be no people from previous transactions",
|
||||
0, countRowsInTable("person"));
|
||||
}
|
||||
|
||||
@Repeat(5)
|
||||
public void testJdbcTx1() throws Exception {
|
||||
testJdbcTx2();
|
||||
}
|
||||
|
||||
@Timed(millis=273)
|
||||
public void testJdbcTx2() throws InterruptedException {
|
||||
//Thread.sleep(2000);
|
||||
assertEquals("Any previous tx must have been rolled back", 0, countRowsInTable("person"));
|
||||
//insertPerson("foo");
|
||||
executeSqlScript("/org/springframework/orm/jpa/insertPerson.sql", false);
|
||||
}
|
||||
|
||||
//@NotTransactional
|
||||
@SuppressWarnings({ "unused", "unchecked" })
|
||||
public void testEntityManagerProxyIsProxy() {
|
||||
assertTrue(Proxy.isProxyClass(sharedEntityManager.getClass()));
|
||||
Query q = sharedEntityManager.createQuery("select p from Person as p");
|
||||
List<Person> people = q.getResultList();
|
||||
|
||||
assertTrue("Should be open to start with", sharedEntityManager.isOpen());
|
||||
sharedEntityManager.close();
|
||||
assertTrue("Close should have been silently ignored", sharedEntityManager.isOpen());
|
||||
}
|
||||
|
||||
@ExpectedException(RuntimeException.class)
|
||||
public void testBogusQuery() {
|
||||
Query query = sharedEntityManager.createQuery("It's raining toads");
|
||||
// required in OpenJPA case
|
||||
query.executeUpdate();
|
||||
}
|
||||
|
||||
@ExpectedException(EntityNotFoundException.class)
|
||||
public void testGetReferenceWhenNoRow() {
|
||||
// Fails here with TopLink
|
||||
Person notThere = sharedEntityManager.getReference(Person.class, 666);
|
||||
|
||||
// We may get here (as with Hibernate).
|
||||
// Either behaviour is valid: throw exception on first access
|
||||
// or on getReference itself.
|
||||
notThere.getFirstName();
|
||||
}
|
||||
|
||||
public void testLazyLoading() {
|
||||
try {
|
||||
Person tony = new Person();
|
||||
tony.setFirstName("Tony");
|
||||
tony.setLastName("Blair");
|
||||
tony.setDriversLicense(new DriversLicense("8439DK"));
|
||||
sharedEntityManager.persist(tony);
|
||||
setComplete();
|
||||
endTransaction();
|
||||
|
||||
startNewTransaction();
|
||||
sharedEntityManager.clear();
|
||||
Person newTony = entityManagerFactory.createEntityManager().getReference(Person.class, tony.getId());
|
||||
assertNotSame(newTony, tony);
|
||||
endTransaction();
|
||||
|
||||
assertNotNull(newTony.getDriversLicense());
|
||||
|
||||
newTony.getDriversLicense().getSerialNumber();
|
||||
}
|
||||
finally {
|
||||
deleteFromTables(new String[] { "person", "drivers_license" });
|
||||
//setComplete();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testMultipleResults() {
|
||||
// Add with JDBC
|
||||
String firstName = "Tony";
|
||||
insertPerson(firstName);
|
||||
|
||||
assertTrue(Proxy.isProxyClass(sharedEntityManager.getClass()));
|
||||
Query q = sharedEntityManager.createQuery("select p from Person as p");
|
||||
List<Person> people = q.getResultList();
|
||||
|
||||
assertEquals(1, people.size());
|
||||
assertEquals(firstName, people.get(0).getFirstName());
|
||||
}
|
||||
|
||||
protected final void insertPerson(String firstName) {
|
||||
String INSERT_PERSON = "INSERT INTO PERSON (ID, FIRST_NAME, LAST_NAME) VALUES (?, ?, ?)";
|
||||
simpleJdbcTemplate.update(INSERT_PERSON, 1, firstName, "Blair");
|
||||
}
|
||||
|
||||
public void testEntityManagerProxyRejectsProgrammaticTxManagement() {
|
||||
try {
|
||||
sharedEntityManager.getTransaction();
|
||||
fail("Should not be able to create transactions on container managed EntityManager");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testSharedEntityManagerProxyRejectsProgrammaticTxJoining() {
|
||||
try {
|
||||
sharedEntityManager.joinTransaction();
|
||||
fail("Should not be able to join transactions with container managed EntityManager");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
}
|
||||
}
|
||||
|
||||
// public void testAspectJInjectionOfConfigurableEntity() {
|
||||
// Person p = new Person();
|
||||
// System.err.println(p);
|
||||
// assertNotNull("Was injected", p.getTestBean());
|
||||
// assertEquals("Ramnivas", p.getTestBean().getName());
|
||||
// }
|
||||
|
||||
public void testInstantiateAndSaveWithSharedEmProxy() {
|
||||
testInstantiateAndSave(sharedEntityManager);
|
||||
}
|
||||
|
||||
protected void testInstantiateAndSave(EntityManager em) {
|
||||
assertEquals("Should be no people from previous transactions", 0, countRowsInTable("person"));
|
||||
Person p = new Person();
|
||||
p.setFirstName("Tony");
|
||||
p.setLastName("Blair");
|
||||
em.persist(p);
|
||||
|
||||
em.flush();
|
||||
assertEquals("1 row must have been inserted", 1, countRowsInTable("person"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testQueryNoPersons() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
Query q = em.createQuery("select p from Person as p");
|
||||
List<Person> people = q.getResultList();
|
||||
assertEquals(0, people.size());
|
||||
try {
|
||||
assertNull(q.getSingleResult());
|
||||
fail("Should have thrown NoResultException");
|
||||
}
|
||||
catch (NoResultException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
@NotTransactional
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testQueryNoPersonsNotTransactional() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
Query q = em.createQuery("select p from Person as p");
|
||||
List<Person> people = q.getResultList();
|
||||
assertEquals(0, people.size());
|
||||
try {
|
||||
assertNull(q.getSingleResult());
|
||||
fail("Should have thrown NoResultException");
|
||||
}
|
||||
catch (NoResultException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unused", "unchecked" })
|
||||
public void testQueryNoPersonsShared() {
|
||||
EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory);
|
||||
Query q = em.createQuery("select p from Person as p");
|
||||
q.setFlushMode(FlushModeType.AUTO);
|
||||
List<Person> people = q.getResultList();
|
||||
try {
|
||||
assertNull(q.getSingleResult());
|
||||
fail("Should have thrown NoResultException");
|
||||
}
|
||||
catch (NoResultException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
@NotTransactional
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testQueryNoPersonsSharedNotTransactional() {
|
||||
EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory);
|
||||
Query q = em.createQuery("select p from Person as p");
|
||||
q.setFlushMode(FlushModeType.AUTO);
|
||||
List<Person> people = q.getResultList();
|
||||
assertEquals(0, people.size());
|
||||
try {
|
||||
assertNull(q.getSingleResult());
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (Exception ex) {
|
||||
// IllegalStateException expected, but PersistenceException thrown by Hibernate
|
||||
assertTrue(ex.getMessage().indexOf("closed") != -1);
|
||||
}
|
||||
q = em.createQuery("select p from Person as p");
|
||||
q.setFlushMode(FlushModeType.AUTO);
|
||||
try {
|
||||
assertNull(q.getSingleResult());
|
||||
fail("Should have thrown NoResultException");
|
||||
}
|
||||
catch (NoResultException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testCanSerializeProxies() throws Exception {
|
||||
// just necessary because of AbstractJpaTests magically cloning the BeanFactory
|
||||
((DefaultListableBeanFactory) getApplicationContext().getBeanFactory()).setSerializationId("emf-it");
|
||||
|
||||
assertNotNull(SerializationTestUtils.serializeAndDeserialize(entityManagerFactory));
|
||||
assertNotNull(SerializationTestUtils.serializeAndDeserialize(sharedEntityManager));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* Superclass for unit tests for EntityManagerFactory-creating beans.
|
||||
* Note: Subclasses must set expectations on the mock EntityManagerFactory.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public abstract class AbstractEntityManagerFactoryBeanTests extends TestCase {
|
||||
|
||||
protected static MockControl emfMc;
|
||||
|
||||
protected static EntityManagerFactory mockEmf;
|
||||
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
emfMc = MockControl.createControl(EntityManagerFactory.class);
|
||||
mockEmf = (EntityManagerFactory) emfMc.getMock();
|
||||
}
|
||||
|
||||
protected void checkInvariants(AbstractEntityManagerFactoryBean demf) {
|
||||
assertTrue(EntityManagerFactory.class.isAssignableFrom(demf.getObjectType()));
|
||||
Object gotObject = demf.getObject();
|
||||
assertTrue("Object created by factory implements EntityManagerFactoryInfo",
|
||||
gotObject instanceof EntityManagerFactoryInfo);
|
||||
EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) demf.getObject();
|
||||
assertSame("Successive invocations of getObject() return same object", emfi, demf.getObject());
|
||||
assertSame(emfi, demf.getObject());
|
||||
assertSame(emfi.getNativeEntityManagerFactory(), mockEmf);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
}
|
||||
|
||||
|
||||
protected static class DummyEntityManagerFactoryBean extends AbstractEntityManagerFactoryBean {
|
||||
|
||||
private final EntityManagerFactory emf;
|
||||
|
||||
public DummyEntityManagerFactoryBean(EntityManagerFactory emf) {
|
||||
this.emf = emf;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException {
|
||||
return emf;
|
||||
}
|
||||
|
||||
public PersistenceUnitInfo getPersistenceUnitInfo() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String getPersistenceUnitName() {
|
||||
return "test";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import org.springframework.test.jpa.AbstractJpaTests;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public abstract class AbstractEntityManagerFactoryIntegrationTests extends AbstractJpaTests {
|
||||
|
||||
public static final String[] TOPLINK_CONFIG_LOCATIONS = new String[] {
|
||||
"/org/springframework/orm/jpa/toplink/toplink-manager.xml", "/org/springframework/orm/jpa/memdb.xml",
|
||||
"/org/springframework/orm/jpa/inject.xml"};
|
||||
|
||||
public static final String[] ECLIPSELINK_CONFIG_LOCATIONS = new String[] {
|
||||
"/org/springframework/orm/jpa/eclipselink/eclipselink-manager.xml", "/org/springframework/orm/jpa/memdb.xml",
|
||||
"/org/springframework/orm/jpa/inject.xml"};
|
||||
|
||||
public static final String[] HIBERNATE_CONFIG_LOCATIONS = new String[] {
|
||||
"/org/springframework/orm/jpa/hibernate/hibernate-manager.xml", "/org/springframework/orm/jpa/memdb.xml",
|
||||
"/org/springframework/orm/jpa/inject.xml"};
|
||||
|
||||
public static final String[] OPENJPA_CONFIG_LOCATIONS = new String[] {
|
||||
"/org/springframework/orm/jpa/openjpa/openjpa-manager.xml", "/org/springframework/orm/jpa/memdb.xml",
|
||||
"/org/springframework/orm/jpa/inject.xml"};
|
||||
|
||||
|
||||
public static Provider getProvider() {
|
||||
String provider = System.getProperty("org.springframework.orm.jpa.provider");
|
||||
if (provider != null) {
|
||||
if (provider.toLowerCase().contains("eclipselink")) {
|
||||
return Provider.ECLIPSELINK;
|
||||
}
|
||||
if (provider.toLowerCase().contains("hibernate")) {
|
||||
return Provider.HIBERNATE;
|
||||
}
|
||||
if (provider.toLowerCase().contains("openjpa")) {
|
||||
return Provider.OPENJPA;
|
||||
}
|
||||
}
|
||||
return Provider.TOPLINK;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected String getActualOrmXmlLocation() {
|
||||
// Specify that we do NOT want to find such a file.
|
||||
return null;
|
||||
}
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
Provider provider = getProvider();
|
||||
switch (provider) {
|
||||
case HIBERNATE:
|
||||
return HIBERNATE_CONFIG_LOCATIONS;
|
||||
case TOPLINK:
|
||||
return TOPLINK_CONFIG_LOCATIONS;
|
||||
case OPENJPA:
|
||||
return OPENJPA_CONFIG_LOCATIONS;
|
||||
default:
|
||||
throw new IllegalStateException("Unknown provider: " + provider);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onTearDownAfterTransaction() throws Exception {
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
}
|
||||
|
||||
|
||||
public enum Provider {
|
||||
TOPLINK, ECLIPSELINK, HIBERNATE, OPENJPA
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import java.util.List;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.Query;
|
||||
import javax.persistence.TransactionRequiredException;
|
||||
|
||||
import org.springframework.aop.support.AopUtils;
|
||||
import org.springframework.orm.jpa.domain.Person;
|
||||
import org.springframework.orm.jpa.AbstractEntityManagerFactoryIntegrationTests;
|
||||
import org.springframework.test.annotation.NotTransactional;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* An application-managed entity manager can join an existing transaction,
|
||||
* but such joining must be made programmatically, not transactionally.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @since 2.0
|
||||
*/
|
||||
public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEntityManagerFactoryIntegrationTests {
|
||||
|
||||
@NotTransactional
|
||||
public void testEntityManagerIsProxy() {
|
||||
assertTrue("EntityManagerFactory is proxied", Proxy.isProxyClass(entityManagerFactory.getClass()));
|
||||
}
|
||||
|
||||
@Transactional(readOnly=true)
|
||||
public void testEntityManagerProxyIsProxy() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
assertTrue(Proxy.isProxyClass(em.getClass()));
|
||||
Query q = em.createQuery("select p from Person as p");
|
||||
List<Person> people = q.getResultList();
|
||||
|
||||
assertTrue("Should be open to start with", em.isOpen());
|
||||
em.close();
|
||||
assertFalse("Close should work on application managed EM", em.isOpen());
|
||||
}
|
||||
|
||||
public void testEntityManagerProxyAcceptsProgrammaticTxJoining() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
em.joinTransaction();
|
||||
}
|
||||
|
||||
public void testInstantiateAndSave() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
em.joinTransaction();
|
||||
doInstantiateAndSave(em);
|
||||
}
|
||||
|
||||
public void testCannotFlushWithoutGettingTransaction() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
try {
|
||||
doInstantiateAndSave(em);
|
||||
fail("Should have thrown TransactionRequiredException");
|
||||
}
|
||||
catch (TransactionRequiredException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
// TODO following lines are a workaround for Hibernate bug
|
||||
// If Hibernate throws an exception due to flush(),
|
||||
// it actually HAS flushed, meaning that the database
|
||||
// was updated outside the transaction
|
||||
deleteAllPeopleUsingEntityManager(sharedEntityManager);
|
||||
setComplete();
|
||||
}
|
||||
|
||||
public void doInstantiateAndSave(EntityManager em) {
|
||||
testStateClean();
|
||||
Person p = new Person();
|
||||
|
||||
p.setFirstName("Tony");
|
||||
p.setLastName("Blair");
|
||||
em.persist(p);
|
||||
|
||||
em.flush();
|
||||
assertEquals("1 row must have been inserted", 1, countRowsInTable("person"));
|
||||
}
|
||||
|
||||
public void testStateClean() {
|
||||
assertEquals("Should be no people from previous transactions", 0, countRowsInTable("person"));
|
||||
}
|
||||
|
||||
public void testReuseInNewTransaction() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
em.joinTransaction();
|
||||
|
||||
doInstantiateAndSave(em);
|
||||
endTransaction();
|
||||
|
||||
assertFalse(em.getTransaction().isActive());
|
||||
|
||||
startNewTransaction();
|
||||
// Call any method: should cause automatic tx invocation
|
||||
assertFalse(em.contains(new Person()));
|
||||
|
||||
assertFalse(em.getTransaction().isActive());
|
||||
em.joinTransaction();
|
||||
|
||||
assertTrue(em.getTransaction().isActive());
|
||||
|
||||
doInstantiateAndSave(em);
|
||||
setComplete();
|
||||
endTransaction(); // Should rollback
|
||||
assertEquals("Tx must have committed back",
|
||||
1, countRowsInTable("person"));
|
||||
|
||||
// Now clean up the database
|
||||
startNewTransaction();
|
||||
em.joinTransaction();
|
||||
deleteAllPeopleUsingEntityManager(em);
|
||||
assertEquals("People have been killed",
|
||||
0, countRowsInTable("person"));
|
||||
setComplete();
|
||||
}
|
||||
|
||||
public static void deleteAllPeopleUsingEntityManager(EntityManager em) {
|
||||
em.createQuery("delete from Person p").executeUpdate();
|
||||
}
|
||||
|
||||
public void testRollbackOccurs() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
em.joinTransaction();
|
||||
doInstantiateAndSave(em);
|
||||
endTransaction(); // Should rollback
|
||||
assertEquals("Tx must have been rolled back",
|
||||
0, countRowsInTable("person"));
|
||||
}
|
||||
|
||||
public void testCommitOccurs() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
em.joinTransaction();
|
||||
doInstantiateAndSave(em);
|
||||
|
||||
setComplete();
|
||||
endTransaction(); // Should rollback
|
||||
assertEquals("Tx must have committed back",
|
||||
1, countRowsInTable("person"));
|
||||
|
||||
// Now clean up the database
|
||||
deleteFromTables(new String[] { "person" });
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/*
|
||||
* Copyright 2002-2009 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import java.util.List;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.Query;
|
||||
import javax.persistence.TransactionRequiredException;
|
||||
|
||||
import org.springframework.aop.support.AopUtils;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.support.PersistenceExceptionTranslator;
|
||||
import org.springframework.orm.jpa.domain.Person;
|
||||
import org.springframework.test.annotation.ExpectedException;
|
||||
import org.springframework.test.annotation.NotTransactional;
|
||||
|
||||
/**
|
||||
* Integration tests using in-memory database for container-managed JPA
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @since 2.0
|
||||
*/
|
||||
public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntityManagerFactoryIntegrationTests {
|
||||
|
||||
@NotTransactional
|
||||
public void testExceptionTranslationWithDialectFoundOnIntroducedEntityManagerInfo() throws Exception {
|
||||
doTestExceptionTranslationWithDialectFound(((EntityManagerFactoryInfo) entityManagerFactory).getJpaDialect());
|
||||
}
|
||||
|
||||
@NotTransactional
|
||||
public void testExceptionTranslationWithDialectFoundOnEntityManagerFactoryBean() throws Exception {
|
||||
AbstractEntityManagerFactoryBean aefb =
|
||||
(AbstractEntityManagerFactoryBean) applicationContext.getBean("&entityManagerFactory");
|
||||
assertNotNull("Dialect must have been set", aefb.getJpaDialect());
|
||||
doTestExceptionTranslationWithDialectFound(aefb);
|
||||
}
|
||||
|
||||
protected void doTestExceptionTranslationWithDialectFound(PersistenceExceptionTranslator pet) throws Exception {
|
||||
RuntimeException in1 = new RuntimeException("in1");
|
||||
PersistenceException in2 = new PersistenceException();
|
||||
assertNull("No translation here", pet.translateExceptionIfPossible(in1));
|
||||
DataAccessException dex = pet.translateExceptionIfPossible(in2);
|
||||
assertNotNull(dex);
|
||||
assertSame(in2, dex.getCause());
|
||||
}
|
||||
|
||||
public void testEntityManagerProxyIsProxy() {
|
||||
EntityManager em = createContainerManagedEntityManager();
|
||||
assertTrue(Proxy.isProxyClass(em.getClass()));
|
||||
Query q = em.createQuery("select p from Person as p");
|
||||
List<Person> people = q.getResultList();
|
||||
assertTrue(people.isEmpty());
|
||||
|
||||
assertTrue("Should be open to start with", em.isOpen());
|
||||
try {
|
||||
em.close();
|
||||
fail("Close should not work on container managed EM");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// Ok
|
||||
}
|
||||
assertTrue(em.isOpen());
|
||||
}
|
||||
|
||||
// This would be legal, at least if not actually _starting_ a tx
|
||||
@ExpectedException(IllegalStateException.class)
|
||||
public void testEntityManagerProxyRejectsProgrammaticTxManagement() {
|
||||
createContainerManagedEntityManager().getTransaction();
|
||||
}
|
||||
|
||||
/*
|
||||
* See comments in spec on EntityManager.joinTransaction().
|
||||
* We take the view that this is a valid no op.
|
||||
*/
|
||||
public void testContainerEntityManagerProxyAllowsJoinTransactionInTransaction() {
|
||||
createContainerManagedEntityManager().joinTransaction();
|
||||
}
|
||||
|
||||
@NotTransactional
|
||||
@ExpectedException(TransactionRequiredException.class)
|
||||
public void testContainerEntityManagerProxyRejectsJoinTransactionWithoutTransaction() {
|
||||
createContainerManagedEntityManager().joinTransaction();
|
||||
}
|
||||
|
||||
public void testInstantiateAndSave() {
|
||||
EntityManager em = createContainerManagedEntityManager();
|
||||
doInstantiateAndSave(em);
|
||||
}
|
||||
|
||||
public void doInstantiateAndSave(EntityManager em) {
|
||||
assertEquals("Should be no people from previous transactions",
|
||||
0, countRowsInTable("person"));
|
||||
Person p = new Person();
|
||||
|
||||
p.setFirstName("Tony");
|
||||
p.setLastName("Blair");
|
||||
em.persist(p);
|
||||
|
||||
em.flush();
|
||||
assertEquals("1 row must have been inserted", 1, countRowsInTable("person"));
|
||||
}
|
||||
|
||||
public void testReuseInNewTransaction() {
|
||||
EntityManager em = createContainerManagedEntityManager();
|
||||
doInstantiateAndSave(em);
|
||||
endTransaction();
|
||||
|
||||
//assertFalse(em.getTransaction().isActive());
|
||||
|
||||
startNewTransaction();
|
||||
// Call any method: should cause automatic tx invocation
|
||||
assertFalse(em.contains(new Person()));
|
||||
//assertTrue(em.getTransaction().isActive());
|
||||
|
||||
doInstantiateAndSave(em);
|
||||
setComplete();
|
||||
endTransaction(); // Should rollback
|
||||
assertEquals("Tx must have committed back",
|
||||
1, countRowsInTable("person"));
|
||||
|
||||
// Now clean up the database
|
||||
deleteFromTables(new String[] { "person" });
|
||||
}
|
||||
|
||||
public void testRollbackOccurs() {
|
||||
EntityManager em = createContainerManagedEntityManager();
|
||||
doInstantiateAndSave(em);
|
||||
endTransaction(); // Should rollback
|
||||
assertEquals("Tx must have been rolled back",
|
||||
0, countRowsInTable("person"));
|
||||
}
|
||||
|
||||
public void testCommitOccurs() {
|
||||
EntityManager em = createContainerManagedEntityManager();
|
||||
doInstantiateAndSave(em);
|
||||
setComplete();
|
||||
endTransaction(); // Should rollback
|
||||
assertEquals("Tx must have committed back",
|
||||
1, countRowsInTable("person"));
|
||||
|
||||
// Now clean up the database
|
||||
deleteFromTables(new String[] { "person" });
|
||||
}
|
||||
|
||||
/*
|
||||
* TODO: This displays incorrect behavior in TopLink because of its EJBQLException -
|
||||
* which is not a subclass of PersistenceException but rather of TopLinkException!
|
||||
public void testEntityManagerProxyException() {
|
||||
EntityManager em = entityManagerFactory.createEntityManager();
|
||||
try {
|
||||
em.createQuery("select p from Person p where p.o=0").getResultList();
|
||||
fail("Semantic nonsense should be rejected");
|
||||
}
|
||||
catch (PersistenceException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityTransaction;
|
||||
import javax.persistence.OptimisticLockException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.TransactionException;
|
||||
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Costin Leau
|
||||
*
|
||||
*/
|
||||
public class DefaultJpaDialectTests extends TestCase {
|
||||
JpaDialect dialect;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
dialect = new DefaultJpaDialect();
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
dialect = null;
|
||||
}
|
||||
|
||||
public void testDefaultTransactionDefinition() throws Exception {
|
||||
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
|
||||
definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
|
||||
|
||||
try {
|
||||
dialect.beginTransaction(null, definition);
|
||||
fail("expected exception");
|
||||
}
|
||||
catch (TransactionException e) {
|
||||
// ok
|
||||
}
|
||||
}
|
||||
|
||||
public void testDefaultBeginTransaction() throws Exception {
|
||||
TransactionDefinition definition = new DefaultTransactionDefinition();
|
||||
MockControl entityControl = MockControl.createControl(EntityManager.class);
|
||||
EntityManager entityManager = (EntityManager) entityControl.getMock();
|
||||
|
||||
MockControl txControl = MockControl.createControl(EntityTransaction.class);
|
||||
EntityTransaction entityTx = (EntityTransaction) txControl.getMock();
|
||||
|
||||
entityControl.expectAndReturn(entityManager.getTransaction(), entityTx);
|
||||
entityTx.begin();
|
||||
|
||||
entityControl.replay();
|
||||
txControl.replay();
|
||||
|
||||
dialect.beginTransaction(entityManager, definition);
|
||||
|
||||
entityControl.verify();
|
||||
txControl.verify();
|
||||
}
|
||||
|
||||
public void testTranslateException() {
|
||||
OptimisticLockException ex = new OptimisticLockException();
|
||||
assertEquals(
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex).getCause(),
|
||||
dialect.translateExceptionIfPossible(ex).getCause());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class EntityManagerFactoryBeanSupportTests extends AbstractEntityManagerFactoryBeanTests {
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
mockEmf.close();
|
||||
emfMc.setVoidCallable();
|
||||
emfMc.replay();
|
||||
}
|
||||
|
||||
public void testHookIsCalled() throws Exception {
|
||||
DummyEntityManagerFactoryBean demf = new DummyEntityManagerFactoryBean(mockEmf);
|
||||
|
||||
demf.afterPropertiesSet();
|
||||
|
||||
checkInvariants(demf);
|
||||
|
||||
// Should trigger close method expected by EntityManagerFactory mock
|
||||
demf.destroy();
|
||||
|
||||
emfMc.verify();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import javax.persistence.EntityExistsException;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.EntityNotFoundException;
|
||||
import javax.persistence.NoResultException;
|
||||
import javax.persistence.NonUniqueResultException;
|
||||
import javax.persistence.OptimisticLockException;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.TransactionRequiredException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.EmptyResultDataAccessException;
|
||||
import org.springframework.dao.IncorrectResultSizeDataAccessException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Costin Leau
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class EntityManagerFactoryUtilsTests extends TestCase {
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetEntityManager(EntityManagerFactory)'
|
||||
*/
|
||||
public void testDoGetEntityManager() {
|
||||
// test null assertion
|
||||
try {
|
||||
EntityManagerFactoryUtils.doGetTransactionalEntityManager(null, null);
|
||||
fail("expected exception");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// it's okay
|
||||
}
|
||||
MockControl mockControl = MockControl.createControl(EntityManagerFactory.class);
|
||||
EntityManagerFactory factory = (EntityManagerFactory) mockControl.getMock();
|
||||
|
||||
mockControl.replay();
|
||||
// no tx active
|
||||
assertNull(EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
|
||||
mockControl.verify();
|
||||
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
}
|
||||
|
||||
public void testDoGetEntityManagerWithTx() throws Exception {
|
||||
try {
|
||||
MockControl mockControl = MockControl.createControl(EntityManagerFactory.class);
|
||||
EntityManagerFactory factory = (EntityManagerFactory) mockControl.getMock();
|
||||
|
||||
MockControl managerControl = MockControl.createControl(EntityManager.class);
|
||||
EntityManager manager = (EntityManager) managerControl.getMock();
|
||||
|
||||
TransactionSynchronizationManager.initSynchronization();
|
||||
mockControl.expectAndReturn(factory.createEntityManager(), manager);
|
||||
|
||||
mockControl.replay();
|
||||
// no tx active
|
||||
assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
|
||||
assertSame(manager, ((EntityManagerHolder)TransactionSynchronizationManager.unbindResource(factory)).getEntityManager());
|
||||
|
||||
mockControl.verify();
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.clearSynchronization();
|
||||
}
|
||||
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
}
|
||||
|
||||
public void testTranslatesIllegalStateException() {
|
||||
IllegalStateException ise = new IllegalStateException();
|
||||
DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ise);
|
||||
assertSame(ise, dex.getCause());
|
||||
assertTrue(dex instanceof InvalidDataAccessApiUsageException);
|
||||
}
|
||||
|
||||
public void testTranslatesIllegalArgumentException() {
|
||||
IllegalArgumentException iae = new IllegalArgumentException();
|
||||
DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(iae);
|
||||
assertSame(iae, dex.getCause());
|
||||
assertTrue(dex instanceof InvalidDataAccessApiUsageException);
|
||||
}
|
||||
|
||||
/**
|
||||
* We do not convert unknown exceptions. They may result from user code.
|
||||
*/
|
||||
public void testDoesNotTranslateUnfamiliarException() {
|
||||
UnsupportedOperationException userRuntimeException = new UnsupportedOperationException();
|
||||
assertNull(
|
||||
"Exception should not be wrapped",
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(userRuntimeException));
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessException(PersistenceException)'
|
||||
*/
|
||||
public void testConvertJpaPersistenceException() {
|
||||
EntityNotFoundException entityNotFound = new EntityNotFoundException();
|
||||
assertSame(JpaObjectRetrievalFailureException.class,
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());
|
||||
|
||||
NoResultException noResult = new NoResultException();
|
||||
assertSame(EmptyResultDataAccessException.class,
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());
|
||||
|
||||
NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
|
||||
assertSame(IncorrectResultSizeDataAccessException.class,
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());
|
||||
|
||||
OptimisticLockException optimisticLock = new OptimisticLockException();
|
||||
assertSame(JpaOptimisticLockingFailureException.class,
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());
|
||||
|
||||
EntityExistsException entityExists = new EntityExistsException("foo");
|
||||
assertSame(DataIntegrityViolationException.class,
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());
|
||||
|
||||
TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
|
||||
assertSame(InvalidDataAccessApiUsageException.class,
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());
|
||||
|
||||
PersistenceException unknown = new PersistenceException() {
|
||||
};
|
||||
assertSame(JpaSystemException.class,
|
||||
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Method;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.aopalliance.intercept.Interceptor;
|
||||
import org.aopalliance.intercept.Invocation;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Costin Leau
|
||||
*/
|
||||
public class JpaInterceptorTests extends TestCase {
|
||||
|
||||
private MockControl factoryControl, managerControl;
|
||||
|
||||
private EntityManagerFactory factory;
|
||||
|
||||
private EntityManager entityManager;
|
||||
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
factoryControl = MockControl.createControl(EntityManagerFactory.class);
|
||||
factory = (EntityManagerFactory) factoryControl.getMock();
|
||||
managerControl = MockControl.createControl(EntityManager.class);
|
||||
entityManager = (EntityManager) managerControl.getMock();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
factoryControl = null;
|
||||
factory = null;
|
||||
managerControl = null;
|
||||
entityManager = null;
|
||||
|
||||
}
|
||||
|
||||
public void testInterceptorWithNewEntityManager() throws PersistenceException {
|
||||
factoryControl.expectAndReturn(factory.createEntityManager(), entityManager);
|
||||
managerControl.expectAndReturn(entityManager.isOpen(), true);
|
||||
entityManager.close();
|
||||
|
||||
factoryControl.replay();
|
||||
managerControl.replay();
|
||||
|
||||
JpaInterceptor interceptor = new JpaInterceptor();
|
||||
interceptor.setEntityManagerFactory(factory);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(factory));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithNewEntityManagerAndLazyFlush() throws PersistenceException {
|
||||
factoryControl.expectAndReturn(factory.createEntityManager(), entityManager);
|
||||
managerControl.expectAndReturn(entityManager.isOpen(), true);
|
||||
entityManager.close();
|
||||
|
||||
factoryControl.replay();
|
||||
managerControl.replay();
|
||||
|
||||
JpaInterceptor interceptor = new JpaInterceptor();
|
||||
interceptor.setFlushEager(false);
|
||||
interceptor.setEntityManagerFactory(factory);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(factory));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBound() {
|
||||
factoryControl.replay();
|
||||
managerControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager));
|
||||
JpaInterceptor interceptor = new JpaInterceptor();
|
||||
interceptor.setEntityManagerFactory(factory);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(factory));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(factory);
|
||||
}
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundAndFlushEager() throws PersistenceException {
|
||||
//entityManager.setFlushMode(FlushModeType.AUTO);
|
||||
entityManager.flush();
|
||||
|
||||
factoryControl.replay();
|
||||
managerControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager));
|
||||
JpaInterceptor interceptor = new JpaInterceptor();
|
||||
interceptor.setFlushEager(true);
|
||||
interceptor.setEntityManagerFactory(factory);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(factory));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(factory);
|
||||
}
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithThreadBoundAndFlushCommit() {
|
||||
//entityManager.setFlushMode(FlushModeType.COMMIT);
|
||||
//entityManager.flush();
|
||||
|
||||
factoryControl.replay();
|
||||
managerControl.replay();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager));
|
||||
JpaInterceptor interceptor = new JpaInterceptor();
|
||||
interceptor.setFlushEager(false);
|
||||
interceptor.setEntityManagerFactory(factory);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(factory));
|
||||
}
|
||||
catch (Throwable t) {
|
||||
fail("Should not have thrown Throwable: " + t.getMessage());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(factory);
|
||||
}
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithFlushFailure() throws Throwable {
|
||||
factoryControl.expectAndReturn(factory.createEntityManager(), entityManager);
|
||||
entityManager.flush();
|
||||
|
||||
PersistenceException exception = new PersistenceException();
|
||||
managerControl.setThrowable(exception, 1);
|
||||
managerControl.expectAndReturn(entityManager.isOpen(), true);
|
||||
entityManager.close();
|
||||
|
||||
factoryControl.replay();
|
||||
managerControl.replay();
|
||||
|
||||
JpaInterceptor interceptor = new JpaInterceptor();
|
||||
interceptor.setFlushEager(true);
|
||||
interceptor.setEntityManagerFactory(factory);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(factory));
|
||||
//fail("Should have thrown JpaSystemException");
|
||||
}
|
||||
catch (JpaSystemException ex) {
|
||||
// expected
|
||||
assertEquals(exception, ex.getCause());
|
||||
}
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
public void testInterceptorWithFlushFailureWithoutConversion() throws Throwable {
|
||||
factoryControl.expectAndReturn(factory.createEntityManager(), entityManager);
|
||||
entityManager.flush();
|
||||
|
||||
PersistenceException exception = new PersistenceException();
|
||||
managerControl.setThrowable(exception, 1);
|
||||
managerControl.expectAndReturn(entityManager.isOpen(), true);
|
||||
entityManager.close();
|
||||
|
||||
factoryControl.replay();
|
||||
managerControl.replay();
|
||||
|
||||
JpaInterceptor interceptor = new JpaInterceptor();
|
||||
interceptor.setFlushEager(true);
|
||||
interceptor.setExceptionConversionEnabled(false);
|
||||
interceptor.setEntityManagerFactory(factory);
|
||||
try {
|
||||
interceptor.invoke(new TestInvocation(factory));
|
||||
//fail("Should have thrown JpaSystemException");
|
||||
}
|
||||
catch (PersistenceException ex) {
|
||||
// expected
|
||||
assertEquals(exception, ex);
|
||||
}
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
|
||||
private static class TestInvocation implements MethodInvocation {
|
||||
|
||||
private EntityManagerFactory entityManagerFactory;
|
||||
|
||||
public TestInvocation(EntityManagerFactory entityManagerFactory) {
|
||||
this.entityManagerFactory = entityManagerFactory;
|
||||
}
|
||||
|
||||
public Object proceed() throws Throwable {
|
||||
if (!TransactionSynchronizationManager.hasResource(this.entityManagerFactory)) {
|
||||
throw new IllegalStateException("Session not bound");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public int getCurrentInterceptorIndex() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getNumberOfInterceptors() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Interceptor getInterceptor(int i) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Method getMethod() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public AccessibleObject getStaticPart() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object getArgument(int i) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object[] getArguments() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setArgument(int i, Object handler) {
|
||||
}
|
||||
|
||||
public int getArgumentCount() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Object getThis() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object getProxy() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Invocation cloneInstance() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void release() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Costin Leau
|
||||
*/
|
||||
public class JpaTemplateTests extends TestCase {
|
||||
|
||||
private JpaTemplate template;
|
||||
|
||||
private MockControl factoryControl, managerControl;
|
||||
|
||||
private EntityManager manager;
|
||||
|
||||
private EntityManagerFactory factory;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
template = new JpaTemplate();
|
||||
|
||||
factoryControl = MockControl.createControl(EntityManagerFactory.class);
|
||||
factory = (EntityManagerFactory) factoryControl.getMock();
|
||||
managerControl = MockControl.createControl(EntityManager.class);
|
||||
manager = (EntityManager) managerControl.getMock();
|
||||
|
||||
template.setEntityManager(manager);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
template = null;
|
||||
factoryControl = null;
|
||||
managerControl = null;
|
||||
manager = null;
|
||||
factory = null;
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.JpaTemplate(EntityManagerFactory)'
|
||||
*/
|
||||
public void testJpaTemplateEntityManagerFactory() {
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.JpaTemplate(EntityManager)'
|
||||
*/
|
||||
public void testJpaTemplateEntityManager() {
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.execute(JpaCallback)'
|
||||
*/
|
||||
public void testExecuteJpaCallback() {
|
||||
template.setExposeNativeEntityManager(true);
|
||||
template.setEntityManager(manager);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
template.execute(new JpaCallback() {
|
||||
|
||||
public Object doInJpa(EntityManager em) throws PersistenceException {
|
||||
assertSame(em, manager);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
template.setExposeNativeEntityManager(false);
|
||||
template.execute(new JpaCallback() {
|
||||
|
||||
public Object doInJpa(EntityManager em) throws PersistenceException {
|
||||
assertNotSame(em, manager);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.executeFind(JpaCallback)'
|
||||
*/
|
||||
public void testExecuteFind() {
|
||||
template.setEntityManager(manager);
|
||||
template.setExposeNativeEntityManager(true);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
try {
|
||||
template.executeFind(new JpaCallback() {
|
||||
|
||||
public Object doInJpa(EntityManager em) throws PersistenceException {
|
||||
assertSame(em, manager);
|
||||
return new Object();
|
||||
}
|
||||
});
|
||||
fail("should have thrown exception");
|
||||
}
|
||||
catch (DataAccessException e) {
|
||||
// expected
|
||||
}
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.execute(JpaCallback, boolean)'
|
||||
*/
|
||||
public void testExecuteJpaCallbackBoolean() {
|
||||
template = new JpaTemplate();
|
||||
template.setExposeNativeEntityManager(false);
|
||||
template.setEntityManagerFactory(factory);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
factoryControl.expectAndReturn(factory.createEntityManager(), manager);
|
||||
managerControl.expectAndReturn(manager.isOpen(), true);
|
||||
manager.close();
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
template.execute(new JpaCallback() {
|
||||
public Object doInJpa(EntityManager em) throws PersistenceException {
|
||||
assertSame(em, manager);
|
||||
return null;
|
||||
}
|
||||
}, true);
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
public void testExecuteJpaCallbackBooleanWithPrebound() {
|
||||
template.setExposeNativeEntityManager(false);
|
||||
template.setEntityManagerFactory(factory);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
try {
|
||||
template.execute(new JpaCallback() {
|
||||
|
||||
public Object doInJpa(EntityManager em) throws PersistenceException {
|
||||
assertSame(em, manager);
|
||||
return null;
|
||||
}
|
||||
}, true);
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(factory);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.createSharedEntityManager(EntityManager)'
|
||||
*/
|
||||
public void testCreateEntityManagerProxy() {
|
||||
manager.clear();
|
||||
managerControl.replay();
|
||||
|
||||
EntityManager proxy = template.createEntityManagerProxy(manager);
|
||||
assertNotSame(manager, proxy);
|
||||
assertFalse(manager.equals(proxy));
|
||||
assertFalse(manager.hashCode() == proxy.hashCode());
|
||||
// close call not propagated to the em
|
||||
proxy.close();
|
||||
proxy.clear();
|
||||
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.find(Class<T>,
|
||||
* Object) <T>'
|
||||
*/
|
||||
public void testFindClassOfTObject() {
|
||||
Integer result = new Integer(1);
|
||||
Object id = new Object();
|
||||
managerControl.expectAndReturn(manager.find(Number.class, id), result);
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
assertSame(result, template.find(Number.class, id));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.getReference(Class<T>, Object)
|
||||
* <T>'
|
||||
*/
|
||||
public void testGetReference() {
|
||||
Integer reference = new Integer(1);
|
||||
Object id = new Object();
|
||||
managerControl.expectAndReturn(manager.getReference(Number.class, id), reference);
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
assertSame(reference, template.getReference(Number.class, id));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.contains(Object)'
|
||||
*/
|
||||
public void testContains() {
|
||||
boolean result = true;
|
||||
Object entity = new Object();
|
||||
managerControl.expectAndReturn(manager.contains(entity), result);
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
assertSame(result, template.contains(entity));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.refresh(Object)'
|
||||
*/
|
||||
public void testRefresh() {
|
||||
Object entity = new Object();
|
||||
manager.refresh(entity);
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
template.refresh(entity);
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.persist(Object)'
|
||||
*/
|
||||
public void testPersist() {
|
||||
Object entity = new Object();
|
||||
manager.persist(entity);
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
template.persist(entity);
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.merge(T) <T>'
|
||||
*/
|
||||
public void testMerge() {
|
||||
Object result = new Object();
|
||||
Object entity = new Object();
|
||||
managerControl.expectAndReturn(manager.merge(entity), result);
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
assertSame(result, template.merge(entity));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.remove(Object)'
|
||||
*/
|
||||
public void testRemove() {
|
||||
Object entity = new Object();
|
||||
manager.remove(entity);
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
template.remove(entity);
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.flush()'
|
||||
*/
|
||||
public void testFlush() {
|
||||
manager.flush();
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
template.flush();
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String)'
|
||||
*/
|
||||
public void testFindString() {
|
||||
String queryString = "some query";
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
List result = new ArrayList();
|
||||
|
||||
managerControl.expectAndReturn(manager.createQuery(queryString), query);
|
||||
queryControl.expectAndReturn(query.getResultList(), result);
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
assertSame(result, template.find(queryString));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String,
|
||||
* Object...)'
|
||||
*/
|
||||
public void testFindStringObjectArray() {
|
||||
String queryString = "some query";
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
List result = new ArrayList();
|
||||
Object param1 = new Object();
|
||||
Object param2 = new Object();
|
||||
Object[] params = new Object[] { param1, param2 };
|
||||
|
||||
managerControl.expectAndReturn(manager.createQuery(queryString), query);
|
||||
queryControl.expectAndReturn(query.setParameter(1, param1), null);
|
||||
queryControl.expectAndReturn(query.setParameter(2, param2), null);
|
||||
|
||||
queryControl.expectAndReturn(query.getResultList(), result);
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
assertSame(result, template.find(queryString, params));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String, Map<String,
|
||||
* Object>)'
|
||||
*/
|
||||
public void testFindStringMapOfStringObject() {
|
||||
String queryString = "some query";
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
List result = new ArrayList();
|
||||
Object param1 = new Object();
|
||||
Object param2 = new Object();
|
||||
Map<String, Object> params = new HashMap<String, Object>();
|
||||
params.put("param1", param1);
|
||||
params.put("param2", param2);
|
||||
|
||||
managerControl.expectAndReturn(manager.createQuery(queryString), query);
|
||||
queryControl.expectAndReturn(query.setParameter("param1", param1), null);
|
||||
queryControl.expectAndReturn(query.setParameter("param2", param2), null);
|
||||
|
||||
queryControl.expectAndReturn(query.getResultList(), result);
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
assertSame(result, template.findByNamedParams(queryString, params));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String)'
|
||||
*/
|
||||
public void testFindByNamedQueryString() {
|
||||
String queryName = "some query name";
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
List result = new ArrayList();
|
||||
|
||||
managerControl.expectAndReturn(manager.createNamedQuery(queryName), query);
|
||||
|
||||
queryControl.expectAndReturn(query.getResultList(), result);
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
assertSame(result, template.findByNamedQuery(queryName));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String,
|
||||
* Object...)'
|
||||
*/
|
||||
public void testFindByNamedQueryStringObjectArray() {
|
||||
String queryName = "some query name";
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
List result = new ArrayList();
|
||||
Object param1 = new Object();
|
||||
Object param2 = new Object();
|
||||
Object[] params = new Object[] { param1, param2 };
|
||||
|
||||
managerControl.expectAndReturn(manager.createNamedQuery(queryName), query);
|
||||
queryControl.expectAndReturn(query.setParameter(1, param1), null);
|
||||
queryControl.expectAndReturn(query.setParameter(2, param2), null);
|
||||
|
||||
queryControl.expectAndReturn(query.getResultList(), result);
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
assertSame(result, template.findByNamedQuery(queryName, params));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String, Map<String,
|
||||
* Object>)'
|
||||
*/
|
||||
public void testFindByNamedQueryStringMapOfStringObject() {
|
||||
String queryName = "some query name";
|
||||
MockControl queryControl = MockControl.createControl(Query.class);
|
||||
Query query = (Query) queryControl.getMock();
|
||||
List result = new ArrayList();
|
||||
Object param1 = new Object();
|
||||
Object param2 = new Object();
|
||||
Map<String, Object> params = new HashMap<String, Object>();
|
||||
params.put("param1", param1);
|
||||
params.put("param2", param2);
|
||||
|
||||
managerControl.expectAndReturn(manager.createNamedQuery(queryName), query);
|
||||
queryControl.expectAndReturn(query.setParameter("param1", param1), null);
|
||||
queryControl.expectAndReturn(query.setParameter("param2", param2), null);
|
||||
|
||||
queryControl.expectAndReturn(query.getResultList(), result);
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
queryControl.replay();
|
||||
|
||||
assertSame(result, template.findByNamedQueryAndNamedParams(queryName, params));
|
||||
|
||||
managerControl.verify();
|
||||
factoryControl.verify();
|
||||
queryControl.verify();
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,405 @@
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.EntityTransaction;
|
||||
import javax.persistence.OptimisticLockException;
|
||||
import javax.persistence.PersistenceException;
|
||||
import javax.persistence.spi.PersistenceProvider;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
import javax.persistence.spi.PersistenceUnitTransactionType;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.OptimisticLockingFailureException;
|
||||
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
|
||||
import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
|
||||
import org.springframework.util.SerializationTestUtils;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityManagerFactoryBeanTests {
|
||||
|
||||
// Static fields set by inner class DummyPersistenceProvider
|
||||
|
||||
private static Map actualProps;
|
||||
|
||||
private static PersistenceUnitInfo actualPui;
|
||||
|
||||
|
||||
public void testValidPersistenceUnit() throws Exception {
|
||||
parseValidPersistenceUnit();
|
||||
}
|
||||
|
||||
public void testExceptionTranslationWithNoDialect() throws Exception {
|
||||
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
|
||||
EntityManagerFactory emf = cefb.getObject();
|
||||
assertNull("No dialect set", cefb.getJpaDialect());
|
||||
|
||||
RuntimeException in1 = new RuntimeException("in1");
|
||||
PersistenceException in2 = new PersistenceException();
|
||||
assertNull("No translation here", cefb.translateExceptionIfPossible(in1));
|
||||
DataAccessException dex = cefb.translateExceptionIfPossible(in2);
|
||||
assertNotNull(dex);
|
||||
assertSame(in2, dex.getCause());
|
||||
}
|
||||
|
||||
public void testEntityManagerFactoryIsProxied() throws Exception {
|
||||
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
|
||||
EntityManagerFactory emf = cefb.getObject();
|
||||
assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
|
||||
|
||||
assertNotSame("EMF must be proxied", mockEmf, emf);
|
||||
assertTrue(emf.equals(emf));
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
bf.setSerializationId("emf-bf");
|
||||
bf.registerSingleton("emf", cefb);
|
||||
cefb.setBeanFactory(bf);
|
||||
cefb.setBeanName("emf");
|
||||
assertNotNull(SerializationTestUtils.serializeAndDeserialize(emf));
|
||||
}
|
||||
|
||||
public void testApplicationManagedEntityManagerWithoutTransaction() throws Exception {
|
||||
Object testEntity = new Object();
|
||||
|
||||
MockControl emMc = MockControl.createControl(EntityManager.class);
|
||||
EntityManager mockEm = (EntityManager) emMc.getMock();
|
||||
mockEm.contains(testEntity);
|
||||
emMc.setReturnValue(false);
|
||||
emMc.replay();
|
||||
|
||||
// finish recording mock calls
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(mockEm);
|
||||
mockEmf.close();
|
||||
emfMc.setVoidCallable();
|
||||
emfMc.replay();
|
||||
|
||||
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
|
||||
EntityManagerFactory emf = cefb.getObject();
|
||||
assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
|
||||
|
||||
assertNotSame("EMF must be proxied", mockEmf, emf);
|
||||
EntityManager em = emf.createEntityManager();
|
||||
assertFalse(em.contains(testEntity));
|
||||
|
||||
cefb.destroy();
|
||||
|
||||
emfMc.verify();
|
||||
emMc.verify();
|
||||
}
|
||||
|
||||
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
|
||||
Object testEntity = new Object();
|
||||
|
||||
MockControl tmMc = MockControl.createControl(EntityTransaction.class);
|
||||
EntityTransaction mockTx = (EntityTransaction) tmMc.getMock();
|
||||
mockTx.isActive();
|
||||
tmMc.setReturnValue(false);
|
||||
mockTx.begin();
|
||||
tmMc.setVoidCallable();
|
||||
mockTx.commit();
|
||||
tmMc.setVoidCallable();
|
||||
tmMc.replay();
|
||||
|
||||
// This one's for the tx (shared)
|
||||
MockControl sharedEmMc = MockControl.createControl(EntityManager.class);
|
||||
EntityManager sharedEm = (EntityManager) sharedEmMc.getMock();
|
||||
sharedEm.getTransaction();
|
||||
sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3);
|
||||
sharedEm.close();
|
||||
sharedEmMc.setVoidCallable();
|
||||
sharedEmMc.replay();
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(sharedEm);
|
||||
|
||||
// This is the application-specific one
|
||||
MockControl emMc = MockControl.createControl(EntityManager.class);
|
||||
EntityManager mockEm = (EntityManager) emMc.getMock();
|
||||
mockEm.getTransaction();
|
||||
emMc.setReturnValue(mockTx, 3);
|
||||
mockEm.contains(testEntity);
|
||||
emMc.setReturnValue(false);
|
||||
emMc.replay();
|
||||
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(mockEm);
|
||||
mockEmf.close();
|
||||
emfMc.setVoidCallable();
|
||||
emfMc.replay();
|
||||
|
||||
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
|
||||
|
||||
JpaTransactionManager jpatm = new JpaTransactionManager();
|
||||
jpatm.setEntityManagerFactory(cefb.getObject());
|
||||
|
||||
TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
|
||||
|
||||
EntityManagerFactory emf = cefb.getObject();
|
||||
assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
|
||||
|
||||
assertNotSame("EMF must be proxied", mockEmf, emf);
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.joinTransaction();
|
||||
assertFalse(em.contains(testEntity));
|
||||
|
||||
jpatm.commit(txStatus);
|
||||
|
||||
cefb.destroy();
|
||||
|
||||
emfMc.verify();
|
||||
emMc.verify();
|
||||
tmMc.verify();
|
||||
}
|
||||
|
||||
public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception {
|
||||
Object testEntity = new Object();
|
||||
|
||||
MockControl tmMc = MockControl.createControl(EntityTransaction.class);
|
||||
EntityTransaction mockTx = (EntityTransaction) tmMc.getMock();
|
||||
mockTx.isActive();
|
||||
tmMc.setReturnValue(false);
|
||||
mockTx.begin();
|
||||
tmMc.setVoidCallable();
|
||||
mockTx.commit();
|
||||
tmMc.setThrowable(new OptimisticLockException());
|
||||
tmMc.replay();
|
||||
|
||||
// This one's for the tx (shared)
|
||||
MockControl sharedEmMc = MockControl.createControl(EntityManager.class);
|
||||
EntityManager sharedEm = (EntityManager) sharedEmMc.getMock();
|
||||
sharedEm.getTransaction();
|
||||
sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3);
|
||||
sharedEm.close();
|
||||
sharedEmMc.setVoidCallable();
|
||||
sharedEmMc.replay();
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(sharedEm);
|
||||
|
||||
// This is the application-specific one
|
||||
MockControl emMc = MockControl.createControl(EntityManager.class);
|
||||
EntityManager mockEm = (EntityManager) emMc.getMock();
|
||||
mockEm.getTransaction();
|
||||
emMc.setReturnValue(mockTx, 3);
|
||||
mockEm.contains(testEntity);
|
||||
emMc.setReturnValue(false);
|
||||
emMc.replay();
|
||||
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(mockEm);
|
||||
mockEmf.close();
|
||||
emfMc.setVoidCallable();
|
||||
emfMc.replay();
|
||||
|
||||
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
|
||||
|
||||
JpaTransactionManager jpatm = new JpaTransactionManager();
|
||||
jpatm.setEntityManagerFactory(cefb.getObject());
|
||||
|
||||
TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
|
||||
|
||||
EntityManagerFactory emf = cefb.getObject();
|
||||
assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
|
||||
|
||||
assertNotSame("EMF must be proxied", mockEmf, emf);
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.joinTransaction();
|
||||
assertFalse(em.contains(testEntity));
|
||||
|
||||
try {
|
||||
jpatm.commit(txStatus);
|
||||
fail("Should have thrown OptimisticLockingFailureException");
|
||||
}
|
||||
catch (OptimisticLockingFailureException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
cefb.destroy();
|
||||
|
||||
emfMc.verify();
|
||||
emMc.verify();
|
||||
tmMc.verify();
|
||||
}
|
||||
|
||||
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
|
||||
Object testEntity = new Object();
|
||||
|
||||
// This one's for the tx (shared)
|
||||
MockControl sharedEmMc = MockControl.createControl(EntityManager.class);
|
||||
EntityManager sharedEm = (EntityManager) sharedEmMc.getMock();
|
||||
sharedEm.getTransaction();
|
||||
sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3);
|
||||
sharedEm.close();
|
||||
sharedEmMc.setVoidCallable(1);
|
||||
sharedEmMc.replay();
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(sharedEm);
|
||||
|
||||
// This is the application-specific one
|
||||
MockControl emMc = MockControl.createControl(EntityManager.class);
|
||||
EntityManager mockEm = (EntityManager) emMc.getMock();
|
||||
mockEm.joinTransaction();
|
||||
emMc.setVoidCallable(1);
|
||||
mockEm.contains(testEntity);
|
||||
emMc.setReturnValue(false);
|
||||
emMc.replay();
|
||||
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(mockEm);
|
||||
mockEmf.close();
|
||||
emfMc.setVoidCallable();
|
||||
emfMc.replay();
|
||||
|
||||
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
|
||||
MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
|
||||
pui.setTransactionType(PersistenceUnitTransactionType.JTA);
|
||||
|
||||
JpaTransactionManager jpatm = new JpaTransactionManager();
|
||||
jpatm.setEntityManagerFactory(cefb.getObject());
|
||||
|
||||
TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
|
||||
|
||||
EntityManagerFactory emf = cefb.getObject();
|
||||
assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
|
||||
|
||||
assertNotSame("EMF must be proxied", mockEmf, emf);
|
||||
EntityManager em = emf.createEntityManager();
|
||||
em.joinTransaction();
|
||||
assertFalse(em.contains(testEntity));
|
||||
|
||||
jpatm.commit(txStatus);
|
||||
|
||||
cefb.destroy();
|
||||
|
||||
emfMc.verify();
|
||||
emMc.verify();
|
||||
}
|
||||
|
||||
public LocalContainerEntityManagerFactoryBean parseValidPersistenceUnit() throws Exception {
|
||||
LocalContainerEntityManagerFactoryBean emfb = createEntityManagerFactoryBean(
|
||||
"org/springframework/orm/jpa/domain/persistence.xml", null,
|
||||
"Person");
|
||||
return emfb;
|
||||
}
|
||||
|
||||
public void testInvalidPersistenceUnitName() throws Exception {
|
||||
try {
|
||||
createEntityManagerFactoryBean("org/springframework/orm/jpa/domain/persistence.xml", null, "call me Bob");
|
||||
fail("Should not create factory with this name");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
protected LocalContainerEntityManagerFactoryBean createEntityManagerFactoryBean(
|
||||
String persistenceXml, Properties props, String entityManagerName) throws Exception {
|
||||
|
||||
// This will be set by DummyPersistenceProvider
|
||||
actualPui = null;
|
||||
actualProps = null;
|
||||
|
||||
LocalContainerEntityManagerFactoryBean containerEmfb = new LocalContainerEntityManagerFactoryBean();
|
||||
|
||||
containerEmfb.setPersistenceUnitName(entityManagerName);
|
||||
containerEmfb.setPersistenceProviderClass(DummyContainerPersistenceProvider.class);
|
||||
if (props != null) {
|
||||
containerEmfb.setJpaProperties(props);
|
||||
}
|
||||
containerEmfb.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
|
||||
containerEmfb.setPersistenceXmlLocation(persistenceXml);
|
||||
containerEmfb.afterPropertiesSet();
|
||||
|
||||
assertEquals(entityManagerName, actualPui.getPersistenceUnitName());
|
||||
if (props != null) {
|
||||
assertEquals(props, actualProps);
|
||||
}
|
||||
//checkInvariants(containerEmfb);
|
||||
|
||||
return containerEmfb;
|
||||
|
||||
//containerEmfb.destroy();
|
||||
//emfMc.verify();
|
||||
}
|
||||
|
||||
public void testRejectsMissingPersistenceUnitInfo() throws Exception {
|
||||
LocalContainerEntityManagerFactoryBean containerEmfb = new LocalContainerEntityManagerFactoryBean();
|
||||
String entityManagerName = "call me Bob";
|
||||
|
||||
containerEmfb.setPersistenceUnitName(entityManagerName);
|
||||
containerEmfb.setPersistenceProviderClass(DummyContainerPersistenceProvider.class);
|
||||
|
||||
try {
|
||||
containerEmfb.afterPropertiesSet();
|
||||
fail();
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class DummyContainerPersistenceProvider implements PersistenceProvider {
|
||||
|
||||
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo pui, Map map) {
|
||||
actualPui = pui;
|
||||
actualProps = map;
|
||||
return mockEmf;
|
||||
}
|
||||
|
||||
public EntityManagerFactory createEntityManagerFactory(String emfName, Map properties) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class NoOpEntityTransaction implements EntityTransaction {
|
||||
|
||||
public void begin() {
|
||||
}
|
||||
|
||||
public void commit() {
|
||||
}
|
||||
|
||||
public void rollback() {
|
||||
}
|
||||
|
||||
public void setRollbackOnly() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean getRollbackOnly() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.spi.PersistenceProvider;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class LocalEntityManagerFactoryBeanTests extends AbstractEntityManagerFactoryBeanTests {
|
||||
|
||||
// Static fields set by inner class DummyPersistenceProvider
|
||||
|
||||
private static String actualName;
|
||||
|
||||
private static Map actualProps;
|
||||
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
mockEmf.close();
|
||||
emfMc.setVoidCallable();
|
||||
emfMc.replay();
|
||||
}
|
||||
|
||||
public void testValidUsageWithDefaultProperties() throws Exception {
|
||||
testValidUsage(null);
|
||||
}
|
||||
|
||||
public void testValidUsageWithExplicitProperties() throws Exception {
|
||||
testValidUsage(new Properties());
|
||||
}
|
||||
|
||||
protected void testValidUsage(Properties props) throws Exception {
|
||||
// This will be set by DummyPersistenceProvider
|
||||
actualName = null;
|
||||
actualProps = null;
|
||||
|
||||
LocalEntityManagerFactoryBean lemfb = new LocalEntityManagerFactoryBean();
|
||||
String entityManagerName = "call me Bob";
|
||||
|
||||
lemfb.setPersistenceUnitName(entityManagerName);
|
||||
lemfb.setPersistenceProviderClass(DummyPersistenceProvider.class);
|
||||
if (props != null) {
|
||||
lemfb.setJpaProperties(props);
|
||||
}
|
||||
lemfb.afterPropertiesSet();
|
||||
|
||||
assertSame(entityManagerName, actualName);
|
||||
if (props != null) {
|
||||
assertEquals(props, actualProps);
|
||||
}
|
||||
checkInvariants(lemfb);
|
||||
|
||||
lemfb.destroy();
|
||||
|
||||
emfMc.verify();
|
||||
}
|
||||
|
||||
|
||||
protected static class DummyPersistenceProvider implements PersistenceProvider {
|
||||
|
||||
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo pui, Map map) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public EntityManagerFactory createEntityManagerFactory(String emfName, Map properties) {
|
||||
actualName = emfName;
|
||||
actualProps = properties;
|
||||
return mockEmf;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
|
||||
|
||||
<persistence-unit name="OrderManagement"/>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.domain;
|
||||
|
||||
import javax.persistence.Basic;
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToOne;
|
||||
import javax.persistence.PersistenceContext;
|
||||
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.annotation.Configurable;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
@Entity
|
||||
@Configurable
|
||||
public class ContextualPerson {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
private transient TestBean testBean;
|
||||
|
||||
// Lazy relationship to force use of instrumentation in JPA implementation.
|
||||
// TopLink, at least, will not instrument classes unless absolutely necessary.
|
||||
@OneToOne(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST)
|
||||
@JoinColumn(name="DRIVERS_LICENSE_ID")
|
||||
private DriversLicense driversLicense;
|
||||
|
||||
private String first_name;
|
||||
|
||||
@Basic(fetch=FetchType.LAZY)
|
||||
private String last_name;
|
||||
|
||||
@PersistenceContext
|
||||
public transient EntityManager entityManager;
|
||||
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setTestBean(TestBean testBean) {
|
||||
this.testBean = testBean;
|
||||
}
|
||||
|
||||
public TestBean getTestBean() {
|
||||
return testBean;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.first_name = firstName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return this.first_name;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.last_name = lastName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return this.last_name;
|
||||
}
|
||||
|
||||
public void setDriversLicense(DriversLicense driversLicense) {
|
||||
this.driversLicense = driversLicense;
|
||||
}
|
||||
|
||||
public DriversLicense getDriversLicense() {
|
||||
return this.driversLicense;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getName() + ":(" + hashCode() + ") id=" + id +
|
||||
"; firstName=" + first_name + "; lastName=" + last_name + "; testBean=" + testBean;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.domain;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="DRIVERS_LICENSE")
|
||||
public class DriversLicense {
|
||||
|
||||
@Id
|
||||
private int id;
|
||||
|
||||
private String serial_number;
|
||||
|
||||
|
||||
protected DriversLicense() {
|
||||
}
|
||||
|
||||
public DriversLicense(String serialNumber) {
|
||||
this.serial_number = serialNumber;
|
||||
}
|
||||
|
||||
public String getSerialNumber() {
|
||||
return serial_number;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.domain;
|
||||
|
||||
import javax.persistence.Basic;
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.annotation.Configurable;
|
||||
|
||||
/**
|
||||
* Simple JavaBean domain object representing an person.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
@Entity
|
||||
@Configurable
|
||||
public class Person {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
private transient TestBean testBean;
|
||||
|
||||
// Lazy relationship to force use of instrumentation in JPA implementation.
|
||||
// TopLink, at least, will not instrument classes unless absolutely necessary.
|
||||
@OneToOne(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST)
|
||||
@JoinColumn(name="DRIVERS_LICENSE_ID")
|
||||
private DriversLicense driversLicense;
|
||||
|
||||
private String first_name;
|
||||
|
||||
@Basic(fetch=FetchType.LAZY)
|
||||
private String last_name;
|
||||
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setTestBean(TestBean testBean) {
|
||||
this.testBean = testBean;
|
||||
}
|
||||
|
||||
public TestBean getTestBean() {
|
||||
return testBean;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.first_name = firstName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return this.first_name;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.last_name = lastName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return this.last_name;
|
||||
}
|
||||
|
||||
public void setDriversLicense(DriversLicense driversLicense) {
|
||||
this.driversLicense = driversLicense;
|
||||
}
|
||||
|
||||
public DriversLicense getDriversLicense() {
|
||||
return this.driversLicense;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getName() + ":(" + hashCode() + ") id=" + id +
|
||||
"; firstName=" + first_name + "; lastName=" + last_name + "; testBean=" + testBean;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="Person" transaction-type="RESOURCE_LOCAL">
|
||||
<class>org.springframework.orm.jpa.domain.ContextualPerson</class>
|
||||
<class>org.springframework.orm.jpa.domain.DriversLicense</class>
|
||||
<class>org.springframework.orm.jpa.domain.Person</class>
|
||||
<exclude-unlisted-classes/>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,17 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="Drivers" transaction-type="RESOURCE_LOCAL">
|
||||
<class>org.springframework.orm.jpa.domain.Person</class>
|
||||
<class>org.springframework.orm.jpa.domain.DriversLicense</class>
|
||||
<exclude-unlisted-classes/>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="Test" transaction-type="RESOURCE_LOCAL">
|
||||
<class>org.springframework.beans.TestBean</class>
|
||||
<exclude-unlisted-classes/>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,12 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="Person" transaction-type="RESOURCE_LOCAL">
|
||||
<class>org.springframework.orm.jpa.domain.Person</class>
|
||||
<class>org.springframework.orm.jpa.domain.DriversLicense</class>
|
||||
<exclude-unlisted-classes/>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.eclipselink;
|
||||
|
||||
import org.eclipse.persistence.jpa.JpaEntityManager;
|
||||
|
||||
import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests;
|
||||
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
|
||||
|
||||
/**
|
||||
* EclipseLink-specific JPA tests.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class EclipseLinkEntityManagerFactoryIntegrationTests extends AbstractContainerEntityManagerFactoryIntegrationTests {
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
return ECLIPSELINK_CONFIG_LOCATIONS;
|
||||
}
|
||||
|
||||
|
||||
public void testCanCastNativeEntityManagerFactoryToTopLinkEntityManagerFactoryImpl() {
|
||||
EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory;
|
||||
assertTrue(emfi.getNativeEntityManagerFactory().getClass().getName().endsWith("EntityManagerFactoryImpl"));
|
||||
}
|
||||
|
||||
public void testCanCastSharedEntityManagerProxyToTopLinkEntityManager() {
|
||||
assertTrue(sharedEntityManager instanceof JpaEntityManager);
|
||||
JpaEntityManager eclipselinkEntityManager = (JpaEntityManager) sharedEntityManager;
|
||||
assertNotNull(eclipselinkEntityManager.getActiveSession());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
||||
<property name="persistenceXmlLocation" value="org/springframework/orm/jpa/domain/persistence.xml"/>
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="jpaVendorAdapter">
|
||||
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
|
||||
<property name="database" value="HSQL"/>
|
||||
<property name="showSql" value="true"/>
|
||||
<property name="generateDdl" value="true"/>
|
||||
</bean>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.hibernate;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.ejb.HibernateEntityManager;
|
||||
import org.hibernate.ejb.HibernateEntityManagerFactory;
|
||||
import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests;
|
||||
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
|
||||
import org.springframework.orm.jpa.domain.Person;
|
||||
import org.springframework.test.annotation.IfProfileValue;
|
||||
|
||||
/**
|
||||
* Hibernate-specific JPA tests.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
// Essentially @Ignore-d since AnnotationBeanConfigurerAspect cannot be found
|
||||
@IfProfileValue(name="test-group", value="broken")
|
||||
public class HibernateEntityManagerFactoryIntegrationTests extends
|
||||
AbstractContainerEntityManagerFactoryIntegrationTests {
|
||||
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
|
||||
public void setSessionFactory(SessionFactory sessionFactory) {
|
||||
this.sessionFactory = sessionFactory;
|
||||
}
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
return HIBERNATE_CONFIG_LOCATIONS;
|
||||
}
|
||||
|
||||
|
||||
public void testCanCastNativeEntityManagerFactoryToHibernateEntityManagerFactoryImpl() {
|
||||
EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory;
|
||||
assertTrue(emfi.getNativeEntityManagerFactory() instanceof HibernateEntityManagerFactory);
|
||||
}
|
||||
|
||||
public void testCanCastSharedEntityManagerProxyToHibernateEntityManager() {
|
||||
assertTrue(sharedEntityManager instanceof HibernateEntityManager);
|
||||
HibernateEntityManager hibernateEntityManager = (HibernateEntityManager) sharedEntityManager;
|
||||
assertNotNull(hibernateEntityManager.getSession());
|
||||
}
|
||||
|
||||
public void testWithHibernateSessionFactory() {
|
||||
// Add with JDBC
|
||||
String firstName = "Tony";
|
||||
insertPerson(firstName);
|
||||
|
||||
Query q = this.sessionFactory.getCurrentSession().createQuery("select p from Person as p");
|
||||
List<Person> people = q.list();
|
||||
|
||||
assertEquals(1, people.size());
|
||||
assertEquals(firstName, people.get(0).getFirstName());
|
||||
}
|
||||
|
||||
public void testConfigurablePerson() {
|
||||
Query q = this.sessionFactory.getCurrentSession().createQuery("select p from ContextualPerson as p");
|
||||
assertEquals(0, q.list().size());
|
||||
//assertNotNull(new ContextualPerson().entityManager); TODO
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.hibernate;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
|
||||
import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests;
|
||||
|
||||
/**
|
||||
* Hibernate-specific JPA tests with multiple EntityManagerFactory instances.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
@org.junit.Ignore // until we work out JPA 1 vs 2 classpath issues in .orm
|
||||
public class HibernateMultiEntityManagerFactoryIntegrationTests extends
|
||||
AbstractContainerEntityManagerFactoryIntegrationTests {
|
||||
|
||||
private EntityManagerFactory entityManagerFactory2;
|
||||
|
||||
|
||||
public HibernateMultiEntityManagerFactoryIntegrationTests() {
|
||||
setAutowireMode(AUTOWIRE_BY_NAME);
|
||||
}
|
||||
|
||||
public void setEntityManagerFactory2(EntityManagerFactory entityManagerFactory2) {
|
||||
this.entityManagerFactory2 = entityManagerFactory2;
|
||||
}
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
return new String[] {
|
||||
"/org/springframework/orm/jpa/hibernate/hibernate-manager-multi.xml",
|
||||
"/org/springframework/orm/jpa/memdb.xml",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
public void testEntityManagerFactory2() {
|
||||
EntityManager em = this.entityManagerFactory2.createEntityManager();
|
||||
try {
|
||||
em.createQuery("select tb from TestBean");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
}
|
||||
finally {
|
||||
em.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<import resource="classpath:/org/springframework/orm/jpa/multi-jpa-emf.xml"/>
|
||||
|
||||
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
|
||||
<property name="database" value="HSQL"/>
|
||||
<property name="showSql" value="true"/>
|
||||
<property name="generateDdl" value="true"/>
|
||||
</bean>
|
||||
|
||||
<bean id="jpaProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
|
||||
<property name="properties">
|
||||
<props>
|
||||
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,41 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
|
||||
|
||||
<context:load-time-weaver aspectj-weaving="on"/>
|
||||
|
||||
<context:annotation-config/>
|
||||
|
||||
<context:spring-configured/>
|
||||
|
||||
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
|
||||
depends-on="org.springframework.context.config.internalBeanConfigurerAspect">
|
||||
<property name="persistenceXmlLocation" value="org/springframework/orm/jpa/domain/persistence-context.xml"/>
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="jpaVendorAdapter">
|
||||
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
|
||||
<property name="database" value="HSQL"/>
|
||||
<property name="showSql" value="true"/>
|
||||
<property name="generateDdl" value="true"/>
|
||||
</bean>
|
||||
</property>
|
||||
<property name="jpaPropertyMap">
|
||||
<props>
|
||||
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
|
||||
<!--
|
||||
<prop key="hibernate.ejb.use_class_enhancer">true</prop>
|
||||
-->
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="packagesToScan" value="org.springframework.orm.jpa.domain"/>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
|
||||
|
||||
<context:annotation-config/>
|
||||
|
||||
<bean id="dao" class="org.springframework.orm.jpa.support.PersistenceInjectionTests$DefaultPublicPersistenceUnitSetterNamedPerson"/>
|
||||
|
||||
<bean class="org.springframework.orm.jpa.support.PersistenceInjectionTests$DefaultPublicPersistenceContextSetter"/>
|
||||
|
||||
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor">
|
||||
<property name="proxyTargetClass" value="true"/>
|
||||
</bean>
|
||||
|
||||
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" lazy-init="true">
|
||||
<property name="targetObject" ref="dao"/>
|
||||
<property name="targetMethod" value="toString"/>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,2 @@
|
||||
INSERT INTO PERSON (ID, FIRST_NAME, LAST_NAME) VALUES (1, 'Tony', 'Blair');
|
||||
INSERT INTO DRIVERS_LICENSE (ID, SERIAL_NUMBER) VALUES (1, '8439DK');
|
||||
Binary file not shown.
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
|
||||
<property name="entityManagerFactory" ref="entityManagerFactory"/>
|
||||
</bean>
|
||||
|
||||
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
|
||||
<property name="entityManagerFactory" ref="entityManagerFactory"/>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
|
||||
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
|
||||
<property name="url" value="jdbc:hsqldb:mem:xdb"/>
|
||||
<property name="username" value="sa"/>
|
||||
<property name="password" value=""/>
|
||||
</bean>
|
||||
|
||||
<!-- Datasource for using an existing database. make sure you turn off generateDLL otherwise
|
||||
on multiple runs it will break it.
|
||||
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
|
||||
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
|
||||
<property name="url" value="jdbc:hsqldb:file:target/classes/db/test"/>
|
||||
<property name="username" value="sa"/>
|
||||
<property name="password" value=""/>
|
||||
</bean>
|
||||
-->
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
|
||||
<property name="persistenceXmlLocations" value="org/springframework/orm/jpa/domain/persistence-multi.xml"/>
|
||||
<property name="defaultDataSource" ref="dataSource"/>
|
||||
</bean>
|
||||
|
||||
<bean id="abstractEMF" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" abstract="true">
|
||||
<property name="persistenceUnitManager" ref="persistenceUnitManager"/>
|
||||
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
|
||||
<property name="jpaProperties" ref="jpaProperties"/>
|
||||
</bean>
|
||||
|
||||
<bean id="entityManagerFactory" parent="abstractEMF">
|
||||
<property name="persistenceUnitName" value="Drivers"/>
|
||||
</bean>
|
||||
|
||||
<bean id="entityManagerFactory2" parent="abstractEMF">
|
||||
<property name="persistenceUnitName" value="Test"/>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.openjpa;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.FlushModeType;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.apache.openjpa.persistence.OpenJPAEntityManager;
|
||||
import org.apache.openjpa.persistence.OpenJPAEntityManagerFactory;
|
||||
|
||||
import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests;
|
||||
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
|
||||
import org.springframework.orm.jpa.SharedEntityManagerCreator;
|
||||
import org.springframework.orm.jpa.domain.Person;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
/**
|
||||
* OpenJPA-specific JPA tests.
|
||||
*
|
||||
* @author Costin Leau
|
||||
*/
|
||||
public class OpenJpaEntityManagerFactoryIntegrationTests extends AbstractContainerEntityManagerFactoryIntegrationTests {
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
return OPENJPA_CONFIG_LOCATIONS;
|
||||
}
|
||||
|
||||
public void testCanCastNativeEntityManagerFactoryToOpenJpaEntityManagerFactoryImpl() {
|
||||
EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory;
|
||||
assertTrue("native EMF expected", emfi.getNativeEntityManagerFactory() instanceof OpenJPAEntityManagerFactory);
|
||||
}
|
||||
|
||||
public void testCanCastSharedEntityManagerProxyToOpenJpaEntityManager() {
|
||||
assertTrue("native EM expected", sharedEntityManager instanceof OpenJPAEntityManager);
|
||||
}
|
||||
|
||||
public void testCanGetSharedOpenJpaEntityManagerProxy() {
|
||||
OpenJPAEntityManager openJPAEntityManager = (OpenJPAEntityManager) SharedEntityManagerCreator.createSharedEntityManager(
|
||||
entityManagerFactory, null, OpenJPAEntityManager.class);
|
||||
assertNotNull(openJPAEntityManager.getDelegate());
|
||||
}
|
||||
|
||||
public void testSavepoint() {
|
||||
TransactionTemplate tt = new TransactionTemplate(transactionManager);
|
||||
tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_NESTED);
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) {
|
||||
Person tony = new Person();
|
||||
tony.setFirstName("Tony");
|
||||
sharedEntityManager.merge(tony);
|
||||
Query q = sharedEntityManager.createQuery("select p from Person as p");
|
||||
q.setFlushMode(FlushModeType.COMMIT);
|
||||
List<Person> people = q.getResultList();
|
||||
assertEquals(1, people.size());
|
||||
assertEquals("Tony", people.get(0).getFirstName());
|
||||
status.setRollbackOnly();
|
||||
}
|
||||
});
|
||||
Query q = sharedEntityManager.createQuery("select p from Person as p");
|
||||
List<Person> people = q.getResultList();
|
||||
assertEquals(0, people.size());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.openjpa;
|
||||
|
||||
/**
|
||||
* Test that AspectJ weaving (in particular the currently shipped aspects) work with JPA (see SPR-3873 for more details).
|
||||
*
|
||||
* @author Ramnivas Laddad
|
||||
*/
|
||||
@org.junit.Ignore // TODO this test causes gradle to hang. uncomment and figure out why
|
||||
public class OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests extends OpenJpaEntityManagerFactoryIntegrationTests {
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
return new String[] {
|
||||
"/org/springframework/orm/jpa/openjpa/openjpa-manager-aspectj-weaving.xml",
|
||||
"/org/springframework/orm/jpa/memdb.xml",
|
||||
"/org/springframework/orm/jpa/inject.xml"};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
|
||||
|
||||
<context:load-time-weaver aspectj-weaving="on"/>
|
||||
|
||||
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
||||
<property name="persistenceXmlLocation" value="org/springframework/orm/jpa/domain/persistence.xml"/>
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="jpaVendorAdapter">
|
||||
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
|
||||
<property name="database" value="HSQL"/>
|
||||
<property name="showSql" value="true"/>
|
||||
<property name="generateDdl" value="true"/>
|
||||
</bean>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
||||
<property name="persistenceXmlLocation" value="org/springframework/orm/jpa/domain/persistence.xml"/>
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="jpaVendorAdapter">
|
||||
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
|
||||
<property name="database" value="HSQL"/>
|
||||
<property name="showSql" value="true"/>
|
||||
<property name="generateDdl" value="true"/>
|
||||
</bean>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,30 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL">
|
||||
<description>
|
||||
This unit manages inventory for auto parts. It depends on
|
||||
features provided by the com.acme.persistence
|
||||
implementation.
|
||||
</description>
|
||||
<provider> com.acme.AcmePersistence</provider>
|
||||
<jta-data-source>jdbc/MyPartDB</jta-data-source>
|
||||
<mapping-file> ormap2.xml</mapping-file>
|
||||
<jar-file> order.jar </jar-file>
|
||||
<properties>
|
||||
<property name="com.acme.persistence.sql-logging" value="on"/>
|
||||
<property name="foo" value="bar" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="pu2" transaction-type="JTA">
|
||||
<provider> com.acme.AcmePersistence </provider>
|
||||
<non-jta-data-source>jdbc/MyDB </non-jta-data-source>
|
||||
<mapping-file>order2.xml </mapping-file>
|
||||
<jar-file> order-*.jar</jar-file>
|
||||
<exclude-unlisted-classes />
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,8 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
|
||||
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="OrderManagement" />
|
||||
</persistence>
|
||||
@@ -0,0 +1,10 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="OrderManagement2">
|
||||
<mapping-file>mappings.xml</mapping-file>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,11 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="OrderManagement3">
|
||||
<jar-file>order.jar</jar-file>
|
||||
<jar-file>order-supplemental.jar</jar-file>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,18 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="OrderManagement4"
|
||||
transaction-type="RESOURCE_LOCAL">
|
||||
<non-jta-data-source>jdbc/MyDB</non-jta-data-source>
|
||||
<mapping-file>order-mappings.xml</mapping-file>
|
||||
|
||||
<class>com.acme.Order</class>
|
||||
<class>com.acme.Customer</class>
|
||||
<class>com.acme.Item</class>
|
||||
<exclude-unlisted-classes />
|
||||
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,14 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="OrderManagement5">
|
||||
<provider>com.acme.AcmePersistence</provider>
|
||||
<mapping-file>order1.xml</mapping-file>
|
||||
<mapping-file>order2.xml</mapping-file>
|
||||
<jar-file>order.jar</jar-file>
|
||||
<jar-file>order-supplemental.jar</jar-file>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,11 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit name="pu">
|
||||
<properties>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,8 @@
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
|
||||
version="1.0">
|
||||
|
||||
<persistence-unit/>
|
||||
|
||||
</persistence>
|
||||
@@ -0,0 +1,3 @@
|
||||
<persistence>
|
||||
<persistence-unit name="pu1"/>
|
||||
</persistence>
|
||||
@@ -0,0 +1,285 @@
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.persistenceunit;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
import javax.persistence.spi.PersistenceUnitTransactionType;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
|
||||
import org.springframework.jdbc.datasource.lookup.MapDataSourceLookup;
|
||||
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
|
||||
|
||||
/**
|
||||
* Unit and integration tests for the JPA XML resource parsing support.
|
||||
*
|
||||
* @author Costin Leau
|
||||
*/
|
||||
public class PersistenceXmlParsingTests {
|
||||
|
||||
@Test
|
||||
public void testExample1() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
String resource = "/org/springframework/orm/jpa/persistence-example1.xml";
|
||||
PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
|
||||
|
||||
assertNotNull(info);
|
||||
assertEquals(1, info.length);
|
||||
assertEquals("OrderManagement", info[0].getPersistenceUnitName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExample2() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
String resource = "/org/springframework/orm/jpa/persistence-example2.xml";
|
||||
PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
|
||||
|
||||
assertNotNull(info);
|
||||
assertEquals(1, info.length);
|
||||
|
||||
assertEquals("OrderManagement2", info[0].getPersistenceUnitName());
|
||||
|
||||
assertEquals(1, info[0].getMappingFileNames().size());
|
||||
assertEquals("mappings.xml", info[0].getMappingFileNames().get(0));
|
||||
assertEquals(0, info[0].getProperties().keySet().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExample3() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
String resource = "/org/springframework/orm/jpa/persistence-example3.xml";
|
||||
PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
|
||||
|
||||
assertNotNull(info);
|
||||
assertEquals(1, info.length);
|
||||
assertEquals("OrderManagement3", info[0].getPersistenceUnitName());
|
||||
|
||||
assertEquals(2, info[0].getJarFileUrls().size());
|
||||
assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
|
||||
assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));
|
||||
assertEquals(0, info[0].getProperties().keySet().size());
|
||||
assertNull(info[0].getJtaDataSource());
|
||||
assertNull(info[0].getNonJtaDataSource());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExample4() throws Exception {
|
||||
SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
|
||||
DataSource ds = new DriverManagerDataSource();
|
||||
builder.bind("java:comp/env/jdbc/MyDB", ds);
|
||||
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
String resource = "/org/springframework/orm/jpa/persistence-example4.xml";
|
||||
PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
|
||||
|
||||
assertNotNull(info);
|
||||
assertEquals(1, info.length);
|
||||
assertEquals("OrderManagement4", info[0].getPersistenceUnitName());
|
||||
|
||||
assertEquals(1, info[0].getMappingFileNames().size());
|
||||
assertEquals("order-mappings.xml", info[0].getMappingFileNames().get(0));
|
||||
|
||||
assertEquals(3, info[0].getManagedClassNames().size());
|
||||
assertEquals("com.acme.Order", info[0].getManagedClassNames().get(0));
|
||||
assertEquals("com.acme.Customer", info[0].getManagedClassNames().get(1));
|
||||
assertEquals("com.acme.Item", info[0].getManagedClassNames().get(2));
|
||||
|
||||
assertTrue(info[0].excludeUnlistedClasses());
|
||||
|
||||
assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, info[0].getTransactionType());
|
||||
assertEquals(0, info[0].getProperties().keySet().size());
|
||||
|
||||
// TODO this is undefined as yet. Do we look up Spring datasource?
|
||||
// assertNotNull(info[0].getNonJtaDataSource());
|
||||
//
|
||||
// assertEquals(ds .toString(),
|
||||
// info[0].getNonJtaDataSource().toString());
|
||||
|
||||
builder.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExample5() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
String resource = "/org/springframework/orm/jpa/persistence-example5.xml";
|
||||
PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
|
||||
|
||||
assertNotNull(info);
|
||||
assertEquals(1, info.length);
|
||||
assertEquals("OrderManagement5", info[0].getPersistenceUnitName());
|
||||
|
||||
assertEquals(2, info[0].getMappingFileNames().size());
|
||||
assertEquals("order1.xml", info[0].getMappingFileNames().get(0));
|
||||
assertEquals("order2.xml", info[0].getMappingFileNames().get(1));
|
||||
|
||||
assertEquals(2, info[0].getJarFileUrls().size());
|
||||
assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
|
||||
assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));
|
||||
|
||||
assertEquals("com.acme.AcmePersistence", info[0].getPersistenceProviderClassName());
|
||||
assertEquals(0, info[0].getProperties().keySet().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExampleComplex() throws Exception {
|
||||
DataSource ds = new DriverManagerDataSource();
|
||||
|
||||
String resource = "/org/springframework/orm/jpa/persistence-complex.xml";
|
||||
MapDataSourceLookup dataSourceLookup = new MapDataSourceLookup();
|
||||
Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
|
||||
dataSources.put("jdbc/MyPartDB", ds);
|
||||
dataSources.put("jdbc/MyDB", ds);
|
||||
dataSourceLookup.setDataSources(dataSources);
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), dataSourceLookup);
|
||||
PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
|
||||
|
||||
assertEquals(2, info.length);
|
||||
|
||||
PersistenceUnitInfo pu1 = info[0];
|
||||
|
||||
assertEquals("pu1", pu1.getPersistenceUnitName());
|
||||
|
||||
assertEquals("com.acme.AcmePersistence", pu1.getPersistenceProviderClassName());
|
||||
|
||||
assertEquals(1, pu1.getMappingFileNames().size());
|
||||
assertEquals("ormap2.xml", pu1.getMappingFileNames().get(0));
|
||||
|
||||
assertEquals(1, pu1.getJarFileUrls().size());
|
||||
assertEquals(new ClassPathResource("order.jar").getURL(), pu1.getJarFileUrls().get(0));
|
||||
|
||||
// TODO need to check the default? Where is this defined
|
||||
assertFalse(pu1.excludeUnlistedClasses());
|
||||
|
||||
assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, pu1.getTransactionType());
|
||||
|
||||
Properties props = pu1.getProperties();
|
||||
assertEquals(2, props.keySet().size());
|
||||
assertEquals("on", props.getProperty("com.acme.persistence.sql-logging"));
|
||||
assertEquals("bar", props.getProperty("foo"));
|
||||
|
||||
assertNull(pu1.getNonJtaDataSource());
|
||||
|
||||
assertSame(ds, pu1.getJtaDataSource());
|
||||
|
||||
PersistenceUnitInfo pu2 = info[1];
|
||||
|
||||
assertSame(PersistenceUnitTransactionType.JTA, pu2.getTransactionType());
|
||||
assertEquals("com.acme.AcmePersistence", pu2.getPersistenceProviderClassName());
|
||||
|
||||
assertEquals(1, pu2.getMappingFileNames().size());
|
||||
assertEquals("order2.xml", pu2.getMappingFileNames().get(0));
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
Ignore ignore; // the following assertions fail only during coverage runs
|
||||
/*
|
||||
assertEquals(1, pu2.getJarFileUrls().size());
|
||||
assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), pu2.getJarFileUrls().get(0));
|
||||
assertTrue(pu2.excludeUnlistedClasses());
|
||||
|
||||
assertNull(pu2.getJtaDataSource());
|
||||
|
||||
// TODO need to define behaviour with non jta datasource
|
||||
assertEquals(ds, pu2.getNonJtaDataSource());
|
||||
*/
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExample6() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
String resource = "/org/springframework/orm/jpa/persistence-example6.xml";
|
||||
PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
|
||||
assertEquals(1, info.length);
|
||||
assertEquals("pu", info[0].getPersistenceUnitName());
|
||||
assertEquals(0, info[0].getProperties().keySet().size());
|
||||
}
|
||||
|
||||
@Ignore // not doing schema parsing anymore for JPA 2.0 compatibility
|
||||
@Test
|
||||
public void testInvalidPersistence() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
String resource = "/org/springframework/orm/jpa/persistence-invalid.xml";
|
||||
try {
|
||||
reader.readPersistenceUnitInfos(resource);
|
||||
fail("expected invalid document exception");
|
||||
}
|
||||
catch (RuntimeException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
@Ignore // not doing schema parsing anymore for JPA 2.0 compatibility
|
||||
@Test
|
||||
public void testNoSchemaPersistence() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
String resource = "/org/springframework/orm/jpa/persistence-no-schema.xml";
|
||||
try {
|
||||
reader.readPersistenceUnitInfos(resource);
|
||||
fail("expected invalid document exception");
|
||||
}
|
||||
catch (RuntimeException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPersistenceUnitRootUrl() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
|
||||
URL url = reader.determinePersistenceUnitRootUrl(new ClassPathResource(
|
||||
"/org/springframework/orm/jpa/persistence-no-schema.xml"));
|
||||
assertNull(url);
|
||||
|
||||
url = reader.determinePersistenceUnitRootUrl(new ClassPathResource("/org/springframework/orm/jpa/META-INF/persistence.xml"));
|
||||
assertTrue("the containing folder should have been returned", url.toString().endsWith("/org/springframework/orm/jpa/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPersistenceUnitRootUrlWithJar() throws Exception {
|
||||
PersistenceUnitReader reader = new PersistenceUnitReader(
|
||||
new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
|
||||
|
||||
ClassPathResource archive = new ClassPathResource("/org/springframework/orm/jpa/jpa-archive.jar");
|
||||
String newRoot = "jar:" + archive.getURL().toExternalForm() + "!/META-INF/persist.xml";
|
||||
Resource insideArchive = new UrlResource(newRoot);
|
||||
// make sure the location actually exists
|
||||
assertTrue(insideArchive.exists());
|
||||
URL url = reader.determinePersistenceUnitRootUrl(insideArchive);
|
||||
assertTrue("the archive location should have been returned", archive.getURL().sameFile(url));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.orm.jpa.support;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.springframework.orm.jpa.JpaTemplate;
|
||||
|
||||
/**
|
||||
* @author Costin Leau
|
||||
*
|
||||
*/
|
||||
public class JpaDaoSupportTests extends TestCase {
|
||||
|
||||
public void testJpaDaoSupportWithEntityManager() throws Exception {
|
||||
MockControl mockControl = MockControl.createControl(EntityManager.class);
|
||||
EntityManager entityManager = (EntityManager) mockControl.getMock();
|
||||
mockControl.replay();
|
||||
final List test = new ArrayList();
|
||||
JpaDaoSupport dao = new JpaDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setEntityManager(entityManager);
|
||||
dao.afterPropertiesSet();
|
||||
assertNotNull("jpa template not created", dao.getJpaTemplate());
|
||||
assertEquals("incorrect entity manager", entityManager, dao.getJpaTemplate().getEntityManager());
|
||||
assertEquals("initDao not called", test.size(), 1);
|
||||
mockControl.verify();
|
||||
}
|
||||
|
||||
public void testJpaDaoSupportWithEntityManagerFactory() throws Exception {
|
||||
MockControl mockControl = MockControl.createControl(EntityManagerFactory.class);
|
||||
EntityManagerFactory entityManagerFactory = (EntityManagerFactory) mockControl.getMock();
|
||||
mockControl.replay();
|
||||
final List test = new ArrayList();
|
||||
JpaDaoSupport dao = new JpaDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setEntityManagerFactory(entityManagerFactory);
|
||||
dao.afterPropertiesSet();
|
||||
assertNotNull("jpa template not created", dao.getJpaTemplate());
|
||||
assertEquals("incorrect entity manager factory", entityManagerFactory,
|
||||
dao.getJpaTemplate().getEntityManagerFactory());
|
||||
assertEquals("initDao not called", test.size(), 1);
|
||||
mockControl.verify();
|
||||
}
|
||||
|
||||
public void testJpaDaoSupportWithJpaTemplate() throws Exception {
|
||||
JpaTemplate template = new JpaTemplate();
|
||||
final List test = new ArrayList();
|
||||
JpaDaoSupport dao = new JpaDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setJpaTemplate(template);
|
||||
dao.afterPropertiesSet();
|
||||
assertNotNull("jpa template not created", dao.getJpaTemplate());
|
||||
assertEquals("incorrect JpaTemplate", template, dao.getJpaTemplate());
|
||||
assertEquals("initDao not called", test.size(), 1);
|
||||
}
|
||||
|
||||
public void testInvalidJpaTemplate() throws Exception {
|
||||
JpaDaoSupport dao = new JpaDaoSupport() {
|
||||
};
|
||||
try {
|
||||
dao.afterPropertiesSet();
|
||||
fail("expected exception");
|
||||
}
|
||||
catch (IllegalArgumentException iae) {
|
||||
// okay
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.mock.web.MockFilterConfig;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.mock.web.PassThroughFilterChain;
|
||||
import org.springframework.orm.jpa.JpaTemplate;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.request.ServletWebRequest;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
|
||||
/**
|
||||
* @author Costin Leau
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
*/
|
||||
public class OpenEntityManagerInViewTests extends TestCase {
|
||||
|
||||
private MockControl factoryControl, managerControl;
|
||||
|
||||
private EntityManager manager;
|
||||
|
||||
private EntityManagerFactory factory;
|
||||
|
||||
private JpaTemplate template;
|
||||
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
factoryControl = MockControl.createControl(EntityManagerFactory.class);
|
||||
factory = (EntityManagerFactory) factoryControl.getMock();
|
||||
managerControl = MockControl.createControl(EntityManager.class);
|
||||
manager = (EntityManager) managerControl.getMock();
|
||||
|
||||
template = new JpaTemplate(factory);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
factoryControl.expectAndReturn(factory.createEntityManager(), manager);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
}
|
||||
|
||||
public void testOpenEntityManagerInViewInterceptor() throws Exception {
|
||||
OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor();
|
||||
interceptor.setEntityManagerFactory(factory);
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(factory));
|
||||
|
||||
// check that further invocations simply participate
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
interceptor.preHandle(new ServletWebRequest(request));
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
|
||||
managerControl.reset();
|
||||
factoryControl.reset();
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
interceptor.postHandle(new ServletWebRequest(request), null);
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(factory));
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
|
||||
managerControl.reset();
|
||||
factoryControl.reset();
|
||||
|
||||
managerControl.expectAndReturn(manager.isOpen(), true);
|
||||
manager.close();
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
interceptor.afterCompletion(new ServletWebRequest(request), null);
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(factory));
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
}
|
||||
|
||||
public void testOpenEntityManagerInViewFilter() throws Exception {
|
||||
managerControl.expectAndReturn(manager.isOpen(), true);
|
||||
manager.close();
|
||||
|
||||
managerControl.replay();
|
||||
factoryControl.replay();
|
||||
|
||||
MockControl factoryControl2 = MockControl.createControl(EntityManagerFactory.class);
|
||||
final EntityManagerFactory factory2 = (EntityManagerFactory) factoryControl2.getMock();
|
||||
|
||||
MockControl managerControl2 = MockControl.createControl(EntityManager.class);
|
||||
EntityManager manager2 = (EntityManager) managerControl2.getMock();
|
||||
|
||||
factoryControl2.expectAndReturn(factory2.createEntityManager(), manager2);
|
||||
managerControl2.expectAndReturn(manager2.isOpen(), true);
|
||||
manager2.close();
|
||||
|
||||
factoryControl2.replay();
|
||||
managerControl2.replay();
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", factory);
|
||||
wac.getDefaultListableBeanFactory().registerSingleton("myEntityManagerFactory", factory2);
|
||||
wac.refresh();
|
||||
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(sc);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
|
||||
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
|
||||
filterConfig2.addInitParameter("entityManagerFactoryBeanName", "myEntityManagerFactory");
|
||||
|
||||
final OpenEntityManagerInViewFilter filter = new OpenEntityManagerInViewFilter();
|
||||
filter.init(filterConfig);
|
||||
final OpenEntityManagerInViewFilter filter2 = new OpenEntityManagerInViewFilter();
|
||||
filter2.init(filterConfig2);
|
||||
|
||||
final FilterChain filterChain = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(factory));
|
||||
servletRequest.setAttribute("invoked", Boolean.TRUE);
|
||||
}
|
||||
};
|
||||
|
||||
final FilterChain filterChain2 = new FilterChain() {
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
|
||||
throws IOException, ServletException {
|
||||
assertTrue(TransactionSynchronizationManager.hasResource(factory2));
|
||||
filter.doFilter(servletRequest, servletResponse, filterChain);
|
||||
}
|
||||
};
|
||||
|
||||
FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
|
||||
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(factory));
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(factory2));
|
||||
filter2.doFilter(request, response, filterChain3);
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(factory));
|
||||
assertFalse(TransactionSynchronizationManager.hasResource(factory2));
|
||||
assertNotNull(request.getAttribute("invoked"));
|
||||
|
||||
factoryControl.verify();
|
||||
managerControl.verify();
|
||||
factoryControl2.verify();
|
||||
managerControl2.verify();
|
||||
|
||||
wac.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.support;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.orm.jpa.AbstractEntityManagerFactoryIntegrationTests;
|
||||
import org.springframework.orm.jpa.support.PersistenceInjectionTests.DefaultPublicPersistenceContextSetter;
|
||||
import org.springframework.orm.jpa.support.PersistenceInjectionTests.DefaultPublicPersistenceUnitSetterNamedPerson;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class PersistenceInjectionIntegrationTests extends AbstractEntityManagerFactoryIntegrationTests {
|
||||
|
||||
@Autowired
|
||||
private DefaultPublicPersistenceContextSetter defaultSetterInjected;
|
||||
|
||||
private DefaultPublicPersistenceUnitSetterNamedPerson namedSetterInjected;
|
||||
|
||||
|
||||
public PersistenceInjectionIntegrationTests() {
|
||||
setAutowireMode(AUTOWIRE_NO);
|
||||
setDependencyCheck(false);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private void init(DefaultPublicPersistenceUnitSetterNamedPerson namedSetterInjected) {
|
||||
this.namedSetterInjected = namedSetterInjected;
|
||||
}
|
||||
|
||||
|
||||
public void testDefaultSetterInjection() {
|
||||
EntityManager injectedEm = defaultSetterInjected.getEntityManager();
|
||||
assertNotNull("Default PersistenceContext Setter was injected", injectedEm);
|
||||
}
|
||||
|
||||
public void testInjectedEntityManagerImplmentsPortableEntityManagerPlus() {
|
||||
EntityManager injectedEm = defaultSetterInjected.getEntityManager();
|
||||
assertNotNull("Default PersistenceContext Setter was injected", injectedEm);
|
||||
}
|
||||
|
||||
public void testSetterInjectionOfNamedPersistenceContext() {
|
||||
assertNotNull("Named PersistenceContext Setter was injected", namedSetterInjected.getEntityManagerFactory());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,894 @@
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.support;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.PersistenceContextType;
|
||||
import javax.persistence.PersistenceProperty;
|
||||
import javax.persistence.PersistenceUnit;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.hibernate.ejb.HibernateEntityManager;
|
||||
import org.junit.Ignore;
|
||||
|
||||
import org.springframework.beans.factory.FactoryBean;
|
||||
import org.springframework.beans.factory.config.SimpleMapScope;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
import org.springframework.mock.jndi.ExpectedLookupTemplate;
|
||||
import org.springframework.orm.jpa.AbstractEntityManagerFactoryBeanTests;
|
||||
import org.springframework.orm.jpa.DefaultJpaDialect;
|
||||
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
|
||||
import org.springframework.orm.jpa.EntityManagerHolder;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.util.SerializationTestUtils;
|
||||
|
||||
/**
|
||||
* Unit tests for persistence context and persistence unit injection.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanTests {
|
||||
|
||||
public void testPrivatePersistenceContextField() throws Exception {
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
gac.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(),
|
||||
new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
|
||||
gac.registerBeanDefinition(FactoryBeanWithPersistenceContextField.class.getName(),
|
||||
new RootBeanDefinition(FactoryBeanWithPersistenceContextField.class));
|
||||
gac.refresh();
|
||||
|
||||
DefaultPrivatePersistenceContextField bean = (DefaultPrivatePersistenceContextField) gac.getBean(
|
||||
DefaultPrivatePersistenceContextField.class.getName());
|
||||
FactoryBeanWithPersistenceContextField bean2 = (FactoryBeanWithPersistenceContextField) gac.getBean(
|
||||
"&" + FactoryBeanWithPersistenceContextField.class.getName());
|
||||
assertNotNull(bean.em);
|
||||
assertNotNull(bean2.em);
|
||||
|
||||
assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em));
|
||||
assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean2.em));
|
||||
}
|
||||
|
||||
public void testPrivateVendorSpecificPersistenceContextField() {
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
gac.registerBeanDefinition(DefaultVendorSpecificPrivatePersistenceContextField.class.getName(),
|
||||
new RootBeanDefinition(DefaultVendorSpecificPrivatePersistenceContextField.class));
|
||||
gac.refresh();
|
||||
|
||||
DefaultVendorSpecificPrivatePersistenceContextField bean = (DefaultVendorSpecificPrivatePersistenceContextField)
|
||||
gac.getBean(DefaultVendorSpecificPrivatePersistenceContextField.class.getName());
|
||||
assertNotNull(bean.em);
|
||||
}
|
||||
|
||||
public void testPublicExtendedPersistenceContextSetter() throws Exception {
|
||||
EntityManager mockEm = MockControl.createControl(EntityManager.class).getMock();
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(mockEm, 1);
|
||||
emfMc.replay();
|
||||
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
|
||||
gac.refresh();
|
||||
|
||||
DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
|
||||
DefaultPublicPersistenceContextSetter.class.getName());
|
||||
assertNotNull(bean.em);
|
||||
emfMc.verify();
|
||||
}
|
||||
|
||||
public void testPublicSpecificExtendedPersistenceContextSetter() throws Exception {
|
||||
emfMc.replay();
|
||||
|
||||
MockControl<EntityManagerFactory> emfMc2 = MockControl.createControl(EntityManagerFactory.class);
|
||||
EntityManagerFactory mockEmf2 = emfMc2.getMock();
|
||||
MockControl<EntityManager> emMc2 = MockControl.createControl(EntityManager.class);
|
||||
EntityManager mockEm2 = emMc2.getMock();
|
||||
mockEm2.getTransaction();
|
||||
emMc2.setReturnValue(null, 1);
|
||||
mockEm2.flush();
|
||||
emMc2.setVoidCallable(1);
|
||||
emMc2.replay();
|
||||
mockEmf2.createEntityManager();
|
||||
emfMc2.setReturnValue(mockEm2, 1);
|
||||
emfMc2.replay();
|
||||
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("unit2", mockEmf2);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
gac.registerBeanDefinition(SpecificPublicPersistenceContextSetter.class.getName(),
|
||||
new RootBeanDefinition(SpecificPublicPersistenceContextSetter.class));
|
||||
gac.refresh();
|
||||
|
||||
SpecificPublicPersistenceContextSetter bean = (SpecificPublicPersistenceContextSetter) gac.getBean(
|
||||
SpecificPublicPersistenceContextSetter.class.getName());
|
||||
assertNotNull(bean.getEntityManager());
|
||||
bean.getEntityManager().flush();
|
||||
emfMc.verify();
|
||||
emfMc2.verify();
|
||||
}
|
||||
|
||||
public void testPublicExtendedPersistenceContextSetterWithSerialization() throws Exception {
|
||||
DummyInvocationHandler ih = new DummyInvocationHandler();
|
||||
Object mockEm = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {EntityManager.class}, ih);
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(mockEm, 1);
|
||||
emfMc.replay();
|
||||
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
SimpleMapScope myScope = new SimpleMapScope();
|
||||
gac.getDefaultListableBeanFactory().registerScope("myScope", myScope);
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
RootBeanDefinition bd = new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class);
|
||||
bd.setScope("myScope");
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(), bd);
|
||||
gac.refresh();
|
||||
|
||||
DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
|
||||
DefaultPublicPersistenceContextSetter.class.getName());
|
||||
assertNotNull(bean.em);
|
||||
assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em));
|
||||
|
||||
SimpleMapScope serialized = (SimpleMapScope) SerializationTestUtils.serializeAndDeserialize(myScope);
|
||||
serialized.close();
|
||||
assertTrue(DummyInvocationHandler.closed);
|
||||
DummyInvocationHandler.closed = false;
|
||||
emfMc.verify();
|
||||
}
|
||||
|
||||
public void testPublicExtendedPersistenceContextSetterWithEntityManagerInfoAndSerialization() throws Exception {
|
||||
Object mockEm = Proxy.newProxyInstance(
|
||||
getClass().getClassLoader(), new Class[] {EntityManager.class}, new DummyInvocationHandler());
|
||||
MockControl emfMc = MockControl.createControl(EntityManagerFactoryWithInfo.class);
|
||||
EntityManagerFactoryWithInfo mockEmf = (EntityManagerFactoryWithInfo) emfMc.getMock();
|
||||
mockEmf.getNativeEntityManagerFactory();
|
||||
emfMc.setReturnValue(mockEmf);
|
||||
mockEmf.getPersistenceUnitInfo();
|
||||
emfMc.setReturnValue(null);
|
||||
mockEmf.getJpaDialect();
|
||||
emfMc.setReturnValue(new DefaultJpaDialect());
|
||||
mockEmf.getEntityManagerInterface();
|
||||
emfMc.setReturnValue(EntityManager.class);
|
||||
mockEmf.getBeanClassLoader();
|
||||
emfMc.setReturnValue(getClass().getClassLoader());
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(mockEm);
|
||||
emfMc.replay();
|
||||
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
|
||||
gac.refresh();
|
||||
|
||||
DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
|
||||
DefaultPublicPersistenceContextSetter.class.getName());
|
||||
assertNotNull(bean.em);
|
||||
assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em));
|
||||
emfMc.verify();
|
||||
}
|
||||
|
||||
public void testPublicExtendedPersistenceContextSetterWithOverriding() {
|
||||
EntityManager mockEm2 = MockControl.createControl(EntityManager.class).getMock();
|
||||
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
RootBeanDefinition bd = new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class);
|
||||
bd.getPropertyValues().add("entityManager", mockEm2);
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(), bd);
|
||||
gac.refresh();
|
||||
|
||||
DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean(
|
||||
DefaultPublicPersistenceContextSetter.class.getName());
|
||||
assertSame(mockEm2, bean.em);
|
||||
}
|
||||
|
||||
public void testPrivatePersistenceUnitField() {
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
gac.registerBeanDefinition(DefaultPrivatePersistenceUnitField.class.getName(),
|
||||
new RootBeanDefinition(DefaultPrivatePersistenceUnitField.class));
|
||||
gac.refresh();
|
||||
|
||||
DefaultPrivatePersistenceUnitField bean = (DefaultPrivatePersistenceUnitField) gac.getBean(
|
||||
DefaultPrivatePersistenceUnitField.class.getName());
|
||||
assertSame(mockEmf, bean.emf);
|
||||
}
|
||||
|
||||
public void testPublicPersistenceUnitSetter() {
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class));
|
||||
gac.refresh();
|
||||
|
||||
DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter) gac.getBean(
|
||||
DefaultPublicPersistenceUnitSetter.class.getName());
|
||||
assertSame(mockEmf, bean.emf);
|
||||
}
|
||||
|
||||
public void testPublicPersistenceUnitSetterWithOverriding() {
|
||||
EntityManagerFactory mockEmf2 =
|
||||
(EntityManagerFactory) MockControl.createControl(EntityManagerFactory.class).getMock();
|
||||
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.registerBeanDefinition("annotationProcessor",
|
||||
new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
|
||||
RootBeanDefinition bd = new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class);
|
||||
bd.getPropertyValues().add("emf", mockEmf2);
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(), bd);
|
||||
gac.refresh();
|
||||
|
||||
DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter) gac.getBean(
|
||||
DefaultPublicPersistenceUnitSetter.class.getName());
|
||||
assertSame(mockEmf2, bean.emf);
|
||||
}
|
||||
|
||||
public void testPublicPersistenceUnitSetterWithUnitIdentifiedThroughBeanName() {
|
||||
EntityManagerFactory mockEmf2 =
|
||||
(EntityManagerFactory) MockControl.createControl(EntityManagerFactory.class).getMock();
|
||||
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory2", mockEmf2);
|
||||
gac.registerAlias("entityManagerFactory2", "Person");
|
||||
RootBeanDefinition processorDef = new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class);
|
||||
processorDef.getPropertyValues().add("defaultPersistenceUnitName", "entityManagerFactory");
|
||||
gac.registerBeanDefinition("annotationProcessor", processorDef);
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class));
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class));
|
||||
gac.refresh();
|
||||
|
||||
DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter)
|
||||
gac.getBean(DefaultPublicPersistenceUnitSetter.class.getName());
|
||||
DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson)
|
||||
gac.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName());
|
||||
assertSame(mockEmf, bean.emf);
|
||||
assertSame(mockEmf2, bean2.emf);
|
||||
}
|
||||
|
||||
public void testPublicPersistenceUnitSetterWithMultipleUnitsIdentifiedThroughUnitName() {
|
||||
MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class);
|
||||
EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock();
|
||||
mockEmf2.getPersistenceUnitName();
|
||||
emf2Mc.setReturnValue("Person", 2);
|
||||
emf2Mc.replay();
|
||||
|
||||
GenericApplicationContext gac = new GenericApplicationContext();
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
|
||||
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory2", mockEmf2);
|
||||
RootBeanDefinition processorDef = new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class);
|
||||
processorDef.getPropertyValues().add("defaultPersistenceUnitName", "entityManagerFactory");
|
||||
gac.registerBeanDefinition("annotationProcessor", processorDef);
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class));
|
||||
gac.registerBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class));
|
||||
gac.refresh();
|
||||
|
||||
DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter)
|
||||
gac.getBean(DefaultPublicPersistenceUnitSetter.class.getName());
|
||||
DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson)
|
||||
gac.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName());
|
||||
assertSame(mockEmf, bean.emf);
|
||||
assertSame(mockEmf2, bean2.emf);
|
||||
|
||||
emf2Mc.verify();
|
||||
}
|
||||
|
||||
@Ignore
|
||||
public void ignoreTestPersistenceUnitsFromJndi() {
|
||||
mockEmf.createEntityManager();
|
||||
Object mockEm = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
emfMc.setReturnValue(mockEm, 1);
|
||||
emfMc.replay();
|
||||
|
||||
MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class);
|
||||
EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock();
|
||||
|
||||
Map<String, String> persistenceUnits = new HashMap<String, String>();
|
||||
persistenceUnits.put("", "pu1");
|
||||
persistenceUnits.put("Person", "pu2");
|
||||
ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
|
||||
jt.addObject("java:comp/env/pu1", mockEmf);
|
||||
jt.addObject("java:comp/env/pu2", mockEmf2);
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
bpp.setPersistenceUnits(persistenceUnits);
|
||||
bpp.setJndiTemplate(jt);
|
||||
bf.addBeanPostProcessor(bpp);
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class));
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class));
|
||||
bf.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(),
|
||||
new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
|
||||
|
||||
DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter)
|
||||
bf.getBean(DefaultPublicPersistenceUnitSetter.class.getName());
|
||||
DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson)
|
||||
bf.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName());
|
||||
DefaultPrivatePersistenceContextField bean3 = (DefaultPrivatePersistenceContextField)
|
||||
bf.getBean(DefaultPrivatePersistenceContextField.class.getName());
|
||||
DefaultPublicPersistenceContextSetter bean4 = (DefaultPublicPersistenceContextSetter)
|
||||
bf.getBean(DefaultPublicPersistenceContextSetter.class.getName());
|
||||
assertSame(mockEmf, bean.emf);
|
||||
assertSame(mockEmf2, bean2.emf);
|
||||
assertNotNull(bean3.em);
|
||||
assertNotNull(bean4.em);
|
||||
|
||||
emfMc.verify();
|
||||
}
|
||||
|
||||
public void testPersistenceUnitsFromJndiWithDefaultUnit() {
|
||||
MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class);
|
||||
EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock();
|
||||
|
||||
Map<String, String> persistenceUnits = new HashMap<String, String>();
|
||||
persistenceUnits.put("System", "pu1");
|
||||
persistenceUnits.put("Person", "pu2");
|
||||
ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
|
||||
jt.addObject("java:comp/env/pu1", mockEmf);
|
||||
jt.addObject("java:comp/env/pu2", mockEmf2);
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
bpp.setPersistenceUnits(persistenceUnits);
|
||||
bpp.setDefaultPersistenceUnitName("System");
|
||||
bpp.setJndiTemplate(jt);
|
||||
bf.addBeanPostProcessor(bpp);
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class));
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class));
|
||||
|
||||
DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter)
|
||||
bf.getBean(DefaultPublicPersistenceUnitSetter.class.getName());
|
||||
DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson)
|
||||
bf.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName());
|
||||
assertSame(mockEmf, bean.emf);
|
||||
assertSame(mockEmf2, bean2.emf);
|
||||
}
|
||||
|
||||
public void testSinglePersistenceUnitFromJndi() {
|
||||
Map<String, String> persistenceUnits = new HashMap<String, String>();
|
||||
persistenceUnits.put("Person", "pu1");
|
||||
ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
|
||||
jt.addObject("java:comp/env/pu1", mockEmf);
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
bpp.setPersistenceUnits(persistenceUnits);
|
||||
bpp.setJndiTemplate(jt);
|
||||
bf.addBeanPostProcessor(bpp);
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetter.class));
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceUnitSetterNamedPerson.class));
|
||||
|
||||
DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter)
|
||||
bf.getBean(DefaultPublicPersistenceUnitSetter.class.getName());
|
||||
DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson)
|
||||
bf.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName());
|
||||
assertSame(mockEmf, bean.emf);
|
||||
assertSame(mockEmf, bean2.emf);
|
||||
}
|
||||
|
||||
public void testPersistenceContextsFromJndi() {
|
||||
Object mockEm = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
Object mockEm2 = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
Object mockEm3 = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
|
||||
Map<String, String> persistenceContexts = new HashMap<String, String>();
|
||||
persistenceContexts.put("", "pc1");
|
||||
persistenceContexts.put("Person", "pc2");
|
||||
Map<String, String> extendedPersistenceContexts = new HashMap<String, String>();
|
||||
extendedPersistenceContexts .put("", "pc3");
|
||||
ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
|
||||
jt.addObject("java:comp/env/pc1", mockEm);
|
||||
jt.addObject("java:comp/env/pc2", mockEm2);
|
||||
jt.addObject("java:comp/env/pc3", mockEm3);
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
bpp.setPersistenceContexts(persistenceContexts);
|
||||
bpp.setExtendedPersistenceContexts(extendedPersistenceContexts);
|
||||
bpp.setJndiTemplate(jt);
|
||||
bf.addBeanPostProcessor(bpp);
|
||||
bf.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(),
|
||||
new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
|
||||
bf.registerBeanDefinition(DefaultPrivatePersistenceContextFieldNamedPerson.class.getName(),
|
||||
new RootBeanDefinition(DefaultPrivatePersistenceContextFieldNamedPerson.class));
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
|
||||
|
||||
DefaultPrivatePersistenceContextField bean1 = (DefaultPrivatePersistenceContextField)
|
||||
bf.getBean(DefaultPrivatePersistenceContextField.class.getName());
|
||||
DefaultPrivatePersistenceContextFieldNamedPerson bean2 = (DefaultPrivatePersistenceContextFieldNamedPerson)
|
||||
bf.getBean(DefaultPrivatePersistenceContextFieldNamedPerson.class.getName());
|
||||
DefaultPublicPersistenceContextSetter bean3 = (DefaultPublicPersistenceContextSetter)
|
||||
bf.getBean(DefaultPublicPersistenceContextSetter.class.getName());
|
||||
assertSame(mockEm, bean1.em);
|
||||
assertSame(mockEm2, bean2.em);
|
||||
assertSame(mockEm3, bean3.em);
|
||||
}
|
||||
|
||||
public void testPersistenceContextsFromJndiWithDefaultUnit() {
|
||||
Object mockEm = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
Object mockEm2 = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
Object mockEm3 = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
|
||||
Map<String, String> persistenceContexts = new HashMap<String, String>();
|
||||
persistenceContexts.put("System", "pc1");
|
||||
persistenceContexts.put("Person", "pc2");
|
||||
Map<String, String> extendedPersistenceContexts = new HashMap<String, String>();
|
||||
extendedPersistenceContexts .put("System", "pc3");
|
||||
ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
|
||||
jt.addObject("java:comp/env/pc1", mockEm);
|
||||
jt.addObject("java:comp/env/pc2", mockEm2);
|
||||
jt.addObject("java:comp/env/pc3", mockEm3);
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
bpp.setPersistenceContexts(persistenceContexts);
|
||||
bpp.setExtendedPersistenceContexts(extendedPersistenceContexts);
|
||||
bpp.setDefaultPersistenceUnitName("System");
|
||||
bpp.setJndiTemplate(jt);
|
||||
bf.addBeanPostProcessor(bpp);
|
||||
bf.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(),
|
||||
new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
|
||||
bf.registerBeanDefinition(DefaultPrivatePersistenceContextFieldNamedPerson.class.getName(),
|
||||
new RootBeanDefinition(DefaultPrivatePersistenceContextFieldNamedPerson.class));
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
|
||||
|
||||
DefaultPrivatePersistenceContextField bean1 = (DefaultPrivatePersistenceContextField)
|
||||
bf.getBean(DefaultPrivatePersistenceContextField.class.getName());
|
||||
DefaultPrivatePersistenceContextFieldNamedPerson bean2 = (DefaultPrivatePersistenceContextFieldNamedPerson)
|
||||
bf.getBean(DefaultPrivatePersistenceContextFieldNamedPerson.class.getName());
|
||||
DefaultPublicPersistenceContextSetter bean3 = (DefaultPublicPersistenceContextSetter)
|
||||
bf.getBean(DefaultPublicPersistenceContextSetter.class.getName());
|
||||
assertSame(mockEm, bean1.em);
|
||||
assertSame(mockEm2, bean2.em);
|
||||
assertSame(mockEm3, bean3.em);
|
||||
}
|
||||
|
||||
public void testSinglePersistenceContextFromJndi() {
|
||||
Object mockEm = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
Object mockEm2 = (EntityManager) MockControl.createControl(EntityManager.class).getMock();
|
||||
|
||||
Map<String, String> persistenceContexts = new HashMap<String, String>();
|
||||
persistenceContexts.put("System", "pc1");
|
||||
Map<String, String> extendedPersistenceContexts = new HashMap<String, String>();
|
||||
extendedPersistenceContexts .put("System", "pc2");
|
||||
ExpectedLookupTemplate jt = new ExpectedLookupTemplate();
|
||||
jt.addObject("java:comp/env/pc1", mockEm);
|
||||
jt.addObject("java:comp/env/pc2", mockEm2);
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
PersistenceAnnotationBeanPostProcessor bpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
bpp.setPersistenceContexts(persistenceContexts);
|
||||
bpp.setExtendedPersistenceContexts(extendedPersistenceContexts);
|
||||
bpp.setJndiTemplate(jt);
|
||||
bf.addBeanPostProcessor(bpp);
|
||||
bf.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(),
|
||||
new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
|
||||
bf.registerBeanDefinition(DefaultPublicPersistenceContextSetter.class.getName(),
|
||||
new RootBeanDefinition(DefaultPublicPersistenceContextSetter.class));
|
||||
|
||||
DefaultPrivatePersistenceContextField bean1 = (DefaultPrivatePersistenceContextField)
|
||||
bf.getBean(DefaultPrivatePersistenceContextField.class.getName());
|
||||
DefaultPublicPersistenceContextSetter bean2 = (DefaultPublicPersistenceContextSetter)
|
||||
bf.getBean(DefaultPublicPersistenceContextSetter.class.getName());
|
||||
assertSame(mockEm, bean1.em);
|
||||
assertSame(mockEm2, bean2.em);
|
||||
}
|
||||
|
||||
public void testFieldOfWrongTypeAnnotatedWithPersistenceUnit() {
|
||||
PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
try {
|
||||
babpp.postProcessPropertyValues(null, null, new FieldOfWrongTypeAnnotatedWithPersistenceUnit(), null);
|
||||
fail("Can't inject this field");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
public void testSetterOfWrongTypeAnnotatedWithPersistenceUnit() {
|
||||
PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
try {
|
||||
babpp.postProcessPropertyValues(null, null, new SetterOfWrongTypeAnnotatedWithPersistenceUnit(), null);
|
||||
fail("Can't inject this setter");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
public void testSetterWithNoArgs() {
|
||||
PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor();
|
||||
try {
|
||||
babpp.postProcessPropertyValues(null, null, new SetterWithNoArgs(), null);
|
||||
fail("Can't inject this setter");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
@Ignore
|
||||
public void ignoreTestNoPropertiesPassedIn() {
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(MockControl.createControl(EntityManager.class).getMock(), 1);
|
||||
emfMc.replay();
|
||||
|
||||
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
|
||||
DefaultPrivatePersistenceContextFieldExtended dppcf = new DefaultPrivatePersistenceContextFieldExtended();
|
||||
babpp.postProcessAfterInstantiation(dppcf, "bean name does not matter");
|
||||
assertNotNull(dppcf.em);
|
||||
emfMc.verify();
|
||||
}
|
||||
|
||||
@Ignore
|
||||
public void ignoreTestPropertiesPassedIn() {
|
||||
Properties props = new Properties();
|
||||
props.put("foo", "bar");
|
||||
mockEmf.createEntityManager(props);
|
||||
emfMc.setReturnValue(MockControl.createControl(EntityManager.class).getMock(), 1);
|
||||
emfMc.replay();
|
||||
|
||||
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
|
||||
DefaultPrivatePersistenceContextFieldExtendedWithProps dppcf =
|
||||
new DefaultPrivatePersistenceContextFieldExtendedWithProps();
|
||||
babpp.postProcessAfterInstantiation(dppcf, "bean name does not matter");
|
||||
assertNotNull(dppcf.em);
|
||||
emfMc.verify();
|
||||
}
|
||||
|
||||
public void testPropertiesForTransactionalEntityManager() {
|
||||
Properties props = new Properties();
|
||||
props.put("foo", "bar");
|
||||
MockControl emC = MockControl.createControl(EntityManager.class);
|
||||
EntityManager em = (EntityManager) emC.getMock();
|
||||
emfMc.expectAndReturn(mockEmf.createEntityManager(props), em);
|
||||
emC.expectAndReturn(em.getDelegate(), new Object());
|
||||
emC.expectAndReturn(em.isOpen(), true);
|
||||
em.close();
|
||||
|
||||
emfMc.replay();
|
||||
emC.replay();
|
||||
|
||||
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
|
||||
DefaultPrivatePersistenceContextFieldWithProperties transactionalField =
|
||||
new DefaultPrivatePersistenceContextFieldWithProperties();
|
||||
babpp.postProcessPropertyValues(null, null, transactionalField, null);
|
||||
|
||||
assertNotNull(transactionalField.em);
|
||||
assertNotNull(transactionalField.em.getDelegate());
|
||||
|
||||
emfMc.verify();
|
||||
emC.verify();
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds an EMF to the thread and tests if EM with different properties
|
||||
* generate new EMs or not.
|
||||
*/
|
||||
public void testPropertiesForSharedEntityManager1() {
|
||||
Properties props = new Properties();
|
||||
props.put("foo", "bar");
|
||||
MockControl emC = MockControl.createControl(EntityManager.class);
|
||||
EntityManager em = (EntityManager) emC.getMock();
|
||||
// only one call made - the first EM definition wins (in this case the one w/ the properties)
|
||||
emfMc.expectAndReturn(mockEmf.createEntityManager(props), em);
|
||||
emC.expectAndReturn(em.getDelegate(), new Object(), 2);
|
||||
emC.expectAndReturn(em.isOpen(), true);
|
||||
em.close();
|
||||
|
||||
emfMc.replay();
|
||||
emC.replay();
|
||||
|
||||
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
|
||||
DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties =
|
||||
new DefaultPrivatePersistenceContextFieldWithProperties();
|
||||
DefaultPrivatePersistenceContextField transactionalField = new DefaultPrivatePersistenceContextField();
|
||||
|
||||
babpp.postProcessPropertyValues(null, null, transactionalFieldWithProperties, null);
|
||||
babpp.postProcessPropertyValues(null, null, transactionalField, null);
|
||||
|
||||
assertNotNull(transactionalFieldWithProperties.em);
|
||||
assertNotNull(transactionalField.em);
|
||||
// the EM w/ properties will be created
|
||||
assertNotNull(transactionalFieldWithProperties.em.getDelegate());
|
||||
// bind em to the thread now since it's created
|
||||
try {
|
||||
TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em));
|
||||
assertNotNull(transactionalField.em.getDelegate());
|
||||
emfMc.verify();
|
||||
emC.verify();
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(mockEmf);
|
||||
}
|
||||
}
|
||||
|
||||
public void testPropertiesForSharedEntityManager2() {
|
||||
Properties props = new Properties();
|
||||
props.put("foo", "bar");
|
||||
MockControl emC = MockControl.createControl(EntityManager.class);
|
||||
EntityManager em = (EntityManager) emC.getMock();
|
||||
// only one call made - the first EM definition wins (in this case the one w/o the properties)
|
||||
emfMc.expectAndReturn(mockEmf.createEntityManager(), em);
|
||||
emC.expectAndReturn(em.getDelegate(), new Object(), 2);
|
||||
emC.expectAndReturn(em.isOpen(), true);
|
||||
em.close();
|
||||
|
||||
emfMc.replay();
|
||||
emC.replay();
|
||||
|
||||
PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor();
|
||||
DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties =
|
||||
new DefaultPrivatePersistenceContextFieldWithProperties();
|
||||
DefaultPrivatePersistenceContextField transactionalField = new DefaultPrivatePersistenceContextField();
|
||||
|
||||
babpp.postProcessPropertyValues(null, null, transactionalFieldWithProperties, null);
|
||||
babpp.postProcessPropertyValues(null, null, transactionalField, null);
|
||||
|
||||
assertNotNull(transactionalFieldWithProperties.em);
|
||||
assertNotNull(transactionalField.em);
|
||||
// the EM w/o properties will be created
|
||||
assertNotNull(transactionalField.em.getDelegate());
|
||||
// bind em to the thread now since it's created
|
||||
try {
|
||||
TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em));
|
||||
assertNotNull(transactionalFieldWithProperties.em.getDelegate());
|
||||
emfMc.verify();
|
||||
emC.verify();
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(mockEmf);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class MockPersistenceAnnotationBeanPostProcessor extends PersistenceAnnotationBeanPostProcessor {
|
||||
|
||||
@Override
|
||||
protected EntityManagerFactory findEntityManagerFactory(String emfName, String requestingBeanName) {
|
||||
return mockEmf;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class DefaultPrivatePersistenceContextField {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
}
|
||||
|
||||
|
||||
public static class DefaultVendorSpecificPrivatePersistenceContextField {
|
||||
|
||||
@PersistenceContext
|
||||
private HibernateEntityManager em;
|
||||
}
|
||||
|
||||
|
||||
public static class FactoryBeanWithPersistenceContextField implements FactoryBean {
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
public Object getObject() throws Exception {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Class getObjectType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isSingleton() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class DefaultPrivatePersistenceContextFieldNamedPerson {
|
||||
|
||||
@PersistenceContext(unitName = "Person")
|
||||
private EntityManager em;
|
||||
}
|
||||
|
||||
|
||||
public static class DefaultPrivatePersistenceContextFieldWithProperties {
|
||||
|
||||
@PersistenceContext(properties = { @PersistenceProperty(name = "foo", value = "bar") })
|
||||
private EntityManager em;
|
||||
}
|
||||
|
||||
|
||||
@Repository
|
||||
public static class DefaultPublicPersistenceContextSetter implements Serializable {
|
||||
|
||||
private EntityManager em;
|
||||
|
||||
@PersistenceContext(type = PersistenceContextType.EXTENDED)
|
||||
public void setEntityManager(EntityManager em) {
|
||||
if (this.em != null) {
|
||||
throw new IllegalStateException("Already called");
|
||||
}
|
||||
this.em = em;
|
||||
}
|
||||
|
||||
public EntityManager getEntityManager() {
|
||||
return em;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class SpecificPublicPersistenceContextSetter extends DefaultPublicPersistenceContextSetter {
|
||||
|
||||
@PersistenceContext(unitName="unit2", type = PersistenceContextType.EXTENDED)
|
||||
public void setEntityManager(EntityManager em) {
|
||||
super.setEntityManager(em);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class DefaultPrivatePersistenceUnitField {
|
||||
|
||||
@PersistenceUnit
|
||||
private EntityManagerFactory emf;
|
||||
}
|
||||
|
||||
|
||||
public static class DefaultPublicPersistenceUnitSetter {
|
||||
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@PersistenceUnit
|
||||
public void setEmf(EntityManagerFactory emf) {
|
||||
if (this.emf != null) {
|
||||
throw new IllegalStateException("Already called");
|
||||
}
|
||||
this.emf = emf;
|
||||
}
|
||||
|
||||
public EntityManagerFactory getEmf() {
|
||||
return emf;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Repository
|
||||
public static class DefaultPublicPersistenceUnitSetterNamedPerson {
|
||||
|
||||
private EntityManagerFactory emf;
|
||||
|
||||
@PersistenceUnit(unitName = "Person")
|
||||
public void setEmf(EntityManagerFactory emf) {
|
||||
this.emf = emf;
|
||||
}
|
||||
|
||||
public EntityManagerFactory getEntityManagerFactory() {
|
||||
return emf;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class FieldOfWrongTypeAnnotatedWithPersistenceUnit {
|
||||
|
||||
@PersistenceUnit
|
||||
public String thisFieldIsOfTheWrongType;
|
||||
}
|
||||
|
||||
|
||||
public static class SetterOfWrongTypeAnnotatedWithPersistenceUnit {
|
||||
|
||||
@PersistenceUnit
|
||||
public void setSomething(Comparable c) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class SetterWithNoArgs {
|
||||
|
||||
@PersistenceUnit
|
||||
public void setSomething() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class DefaultPrivatePersistenceContextFieldExtended {
|
||||
|
||||
@PersistenceContext(type = PersistenceContextType.EXTENDED)
|
||||
private EntityManager em;
|
||||
}
|
||||
|
||||
|
||||
public static class DefaultPrivatePersistenceContextFieldExtendedWithProps {
|
||||
|
||||
@PersistenceContext(type = PersistenceContextType.EXTENDED, properties = { @PersistenceProperty(name = "foo", value = "bar") })
|
||||
private EntityManager em;
|
||||
}
|
||||
|
||||
|
||||
private interface EntityManagerFactoryWithInfo extends EntityManagerFactory, EntityManagerFactoryInfo {
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static class DummyInvocationHandler implements InvocationHandler, Serializable {
|
||||
|
||||
public static boolean closed;
|
||||
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
if ("isOpen".equals(method.getName())) {
|
||||
return true;
|
||||
}
|
||||
if ("close".equals(method.getName())) {
|
||||
closed = true;
|
||||
return null;
|
||||
}
|
||||
if ("toString".equals(method.getName())) {
|
||||
return "";
|
||||
}
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.support;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.orm.jpa.EntityManagerHolder;
|
||||
import org.springframework.orm.jpa.EntityManagerProxy;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class SharedEntityManagerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void testValidUsage() {
|
||||
Object o = new Object();
|
||||
|
||||
MockControl emMc = MockControl.createControl(EntityManager.class);
|
||||
EntityManager mockEm = (EntityManager) emMc.getMock();
|
||||
|
||||
mockEm.contains(o);
|
||||
emMc.setReturnValue(false, 1);
|
||||
|
||||
emMc.expectAndReturn(mockEm.isOpen(), true);
|
||||
mockEm.close();
|
||||
emMc.setVoidCallable(1);
|
||||
emMc.replay();
|
||||
|
||||
MockControl emfMc = MockControl.createControl(EntityManagerFactory.class);
|
||||
EntityManagerFactory mockEmf = (EntityManagerFactory) emfMc.getMock();
|
||||
mockEmf.createEntityManager();
|
||||
emfMc.setReturnValue(mockEm, 1);
|
||||
emfMc.replay();
|
||||
|
||||
SharedEntityManagerBean proxyFactoryBean = new SharedEntityManagerBean();
|
||||
proxyFactoryBean.setEntityManagerFactory(mockEmf);
|
||||
proxyFactoryBean.afterPropertiesSet();
|
||||
|
||||
assertTrue(EntityManager.class.isAssignableFrom(proxyFactoryBean.getObjectType()));
|
||||
assertTrue(proxyFactoryBean.isSingleton());
|
||||
|
||||
EntityManager proxy = (EntityManager) proxyFactoryBean.getObject();
|
||||
assertSame(proxy, proxyFactoryBean.getObject());
|
||||
assertFalse(proxy.contains(o));
|
||||
|
||||
assertTrue(proxy instanceof EntityManagerProxy);
|
||||
EntityManagerProxy emProxy = (EntityManagerProxy) proxy;
|
||||
try {
|
||||
emProxy.getTargetEntityManager();
|
||||
fail("Should have thrown IllegalStateException outside of transaction");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(mockEm));
|
||||
try {
|
||||
assertSame(mockEm, emProxy.getTargetEntityManager());
|
||||
}
|
||||
finally {
|
||||
TransactionSynchronizationManager.unbindResource(mockEmf);
|
||||
}
|
||||
|
||||
emfMc.verify();
|
||||
emMc.verify();
|
||||
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.toplink;
|
||||
|
||||
import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests;
|
||||
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
|
||||
|
||||
/**
|
||||
* TopLink-specific JPA tests.
|
||||
*
|
||||
* @author Costin Leau
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class TopLinkEntityManagerFactoryIntegrationTests extends AbstractContainerEntityManagerFactoryIntegrationTests {
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
return TOPLINK_CONFIG_LOCATIONS;
|
||||
}
|
||||
|
||||
|
||||
public void testCanCastNativeEntityManagerFactoryToTopLinkEntityManagerFactoryImpl() {
|
||||
EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory;
|
||||
assertTrue(emfi.getNativeEntityManagerFactory().getClass().getName().endsWith("EntityManagerFactoryImpl"));
|
||||
}
|
||||
|
||||
public void testCanCastSharedEntityManagerProxyToTopLinkEntityManager() {
|
||||
assertTrue(sharedEntityManager instanceof oracle.toplink.essentials.ejb.cmp3.EntityManager);
|
||||
oracle.toplink.essentials.ejb.cmp3.EntityManager toplinkEntityManager =
|
||||
(oracle.toplink.essentials.ejb.cmp3.EntityManager) sharedEntityManager;
|
||||
assertNotNull(toplinkEntityManager.getActiveSession());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.orm.jpa.toplink;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
|
||||
import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests;
|
||||
|
||||
/**
|
||||
* Toplink-specific JPA tests with multiple EntityManagerFactory instances.
|
||||
*
|
||||
* @author Costin Leau
|
||||
*/
|
||||
@org.junit.Ignore // TODO this test causes gradle to hang. uncomment and figure out why
|
||||
public class TopLinkMultiEntityManagerFactoryIntegrationTests extends
|
||||
AbstractContainerEntityManagerFactoryIntegrationTests {
|
||||
|
||||
private EntityManagerFactory entityManagerFactory2;
|
||||
|
||||
|
||||
public TopLinkMultiEntityManagerFactoryIntegrationTests() {
|
||||
setAutowireMode(AUTOWIRE_BY_NAME);
|
||||
}
|
||||
|
||||
public void setEntityManagerFactory2(EntityManagerFactory entityManagerFactory2) {
|
||||
this.entityManagerFactory2 = entityManagerFactory2;
|
||||
}
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
return new String[] {
|
||||
"/org/springframework/orm/jpa/toplink/toplink-manager-multi.xml",
|
||||
"/org/springframework/orm/jpa/memdb.xml"
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
public void testEntityManagerFactory2() {
|
||||
EntityManager em = this.entityManagerFactory2.createEntityManager();
|
||||
try {
|
||||
em.createQuery("select tb from TestBean");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
}
|
||||
finally {
|
||||
em.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<import resource="classpath:/org/springframework/orm/jpa/multi-jpa-emf.xml"/>
|
||||
|
||||
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
|
||||
<property name="database" value="HSQL"/>
|
||||
<property name="showSql" value="true"/>
|
||||
<property name="generateDdl" value="true"/>
|
||||
</bean>
|
||||
|
||||
<bean id="jpaProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
||||
<property name="persistenceXmlLocation" value="org/springframework/orm/jpa/domain/persistence.xml"/>
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="jpaVendorAdapter">
|
||||
<bean class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
|
||||
<property name="database" value="HSQL"/>
|
||||
<property name="showSql" value="true"/>
|
||||
<property name="generateDdl" value="true"/>
|
||||
</bean>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,292 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Convenient superclass for JUnit 3.8 based tests depending on a Spring
|
||||
* context. The test instance itself is populated by Dependency Injection.
|
||||
* </p>
|
||||
* <p>
|
||||
* Really for integration testing, not unit testing. You should <i>not</i>
|
||||
* normally use the Spring container for unit tests: simply populate your POJOs
|
||||
* in plain JUnit tests!
|
||||
* </p>
|
||||
* <p>
|
||||
* This supports two modes of populating the test:
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>Via Setter Dependency Injection. Simply express dependencies on objects
|
||||
* in the test fixture, and they will be satisfied by autowiring by type.
|
||||
* <li>Via Field Injection. Declare protected variables of the required type
|
||||
* which match named beans in the context. This is autowire by name, rather than
|
||||
* type. This approach is based on an approach originated by Ara Abrahmian.
|
||||
* Setter Dependency Injection is the default: set the
|
||||
* <code>populateProtectedVariables</code> property to <code>true</code> in
|
||||
* the constructor to switch on Field Injection.
|
||||
* </ul>
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Rob Harrop
|
||||
* @author Rick Evans
|
||||
* @author Sam Brannen
|
||||
* @since 1.1.1
|
||||
* @see #setDirty
|
||||
* @see #contextKey
|
||||
* @see #getContext
|
||||
* @see #getConfigLocations
|
||||
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
|
||||
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract class AbstractDependencyInjectionSpringContextTests extends AbstractSingleSpringContextTests {
|
||||
|
||||
/**
|
||||
* Constant that indicates no autowiring at all.
|
||||
*
|
||||
* @see #setAutowireMode
|
||||
*/
|
||||
public static final int AUTOWIRE_NO = 0;
|
||||
|
||||
/**
|
||||
* Constant that indicates autowiring bean properties by name.
|
||||
*
|
||||
* @see #setAutowireMode
|
||||
*/
|
||||
public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
|
||||
|
||||
/**
|
||||
* Constant that indicates autowiring bean properties by type.
|
||||
*
|
||||
* @see #setAutowireMode
|
||||
*/
|
||||
public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
|
||||
|
||||
private boolean populateProtectedVariables = false;
|
||||
|
||||
private int autowireMode = AUTOWIRE_BY_TYPE;
|
||||
|
||||
private boolean dependencyCheck = true;
|
||||
|
||||
private String[] managedVariableNames;
|
||||
|
||||
|
||||
/**
|
||||
* Default constructor for AbstractDependencyInjectionSpringContextTests.
|
||||
*/
|
||||
public AbstractDependencyInjectionSpringContextTests() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor for AbstractDependencyInjectionSpringContextTests with a
|
||||
* JUnit name.
|
||||
* @param name the name of this text fixture
|
||||
*/
|
||||
public AbstractDependencyInjectionSpringContextTests(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Set whether to populate protected variables of this test case. Default is
|
||||
* <code>false</code>.
|
||||
*/
|
||||
public final void setPopulateProtectedVariables(boolean populateFields) {
|
||||
this.populateProtectedVariables = populateFields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether to populate protected variables of this test case.
|
||||
*/
|
||||
public final boolean isPopulateProtectedVariables() {
|
||||
return this.populateProtectedVariables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the autowire mode for test properties set by Dependency Injection.
|
||||
* <p>The default is {@link #AUTOWIRE_BY_TYPE}. Can be set to
|
||||
* {@link #AUTOWIRE_BY_NAME} or {@link #AUTOWIRE_NO} instead.
|
||||
* @see #AUTOWIRE_BY_TYPE
|
||||
* @see #AUTOWIRE_BY_NAME
|
||||
* @see #AUTOWIRE_NO
|
||||
*/
|
||||
public final void setAutowireMode(final int autowireMode) {
|
||||
this.autowireMode = autowireMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the autowire mode for test properties set by Dependency Injection.
|
||||
*/
|
||||
public final int getAutowireMode() {
|
||||
return this.autowireMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether or not dependency checking should be performed for test
|
||||
* properties set by Dependency Injection.
|
||||
* <p>The default is <code>true</code>, meaning that tests cannot be run
|
||||
* unless all properties are populated.
|
||||
*/
|
||||
public final void setDependencyCheck(final boolean dependencyCheck) {
|
||||
this.dependencyCheck = dependencyCheck;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether or not dependency checking should be performed for test
|
||||
* properties set by Dependency Injection.
|
||||
*/
|
||||
public final boolean isDependencyCheck() {
|
||||
return this.dependencyCheck;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare this test instance, injecting dependencies into its protected
|
||||
* fields and its bean properties.
|
||||
* <p>Note: if the {@link ApplicationContext} for this test instance has not
|
||||
* been configured (e.g., is <code>null</code>), dependency injection
|
||||
* will naturally <strong>not</strong> be performed, but an informational
|
||||
* message will be written to the log.
|
||||
* @see #injectDependencies()
|
||||
*/
|
||||
protected void prepareTestInstance() throws Exception {
|
||||
if (getApplicationContext() == null) {
|
||||
if (this.logger.isInfoEnabled()) {
|
||||
this.logger.info("ApplicationContext has not been configured for test [" + getClass().getName()
|
||||
+ "]: dependency injection will NOT be performed.");
|
||||
}
|
||||
}
|
||||
else {
|
||||
injectDependencies();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject dependencies into 'this' instance (that is, this test instance).
|
||||
* <p>The default implementation populates protected variables if the
|
||||
* {@link #populateProtectedVariables() appropriate flag is set}, else uses
|
||||
* autowiring if autowiring is switched on (which it is by default).
|
||||
* <p>Override this method if you need full control over how dependencies are
|
||||
* injected into the test instance.
|
||||
* @throws Exception in case of dependency injection failure
|
||||
* @throws IllegalStateException if the {@link ApplicationContext} for this
|
||||
* test instance has not been configured
|
||||
* @see #populateProtectedVariables()
|
||||
*/
|
||||
protected void injectDependencies() throws Exception {
|
||||
Assert.state(getApplicationContext() != null,
|
||||
"injectDependencies() called without first configuring an ApplicationContext");
|
||||
if (isPopulateProtectedVariables()) {
|
||||
if (this.managedVariableNames == null) {
|
||||
initManagedVariableNames();
|
||||
}
|
||||
populateProtectedVariables();
|
||||
}
|
||||
getApplicationContext().getBeanFactory().autowireBeanProperties(this, getAutowireMode(), isDependencyCheck());
|
||||
}
|
||||
|
||||
private void initManagedVariableNames() throws IllegalAccessException {
|
||||
List managedVarNames = new LinkedList();
|
||||
Class clazz = getClass();
|
||||
do {
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("Found " + fields.length + " fields on " + clazz);
|
||||
}
|
||||
for (int i = 0; i < fields.length; i++) {
|
||||
Field field = fields[i];
|
||||
field.setAccessible(true);
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("Candidate field: " + field);
|
||||
}
|
||||
if (isProtectedInstanceField(field)) {
|
||||
Object oldValue = field.get(this);
|
||||
if (oldValue == null) {
|
||||
managedVarNames.add(field.getName());
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("Added managed variable '" + field.getName() + "'");
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("Rejected managed variable '" + field.getName() + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
clazz = clazz.getSuperclass();
|
||||
} while (!clazz.equals(AbstractDependencyInjectionSpringContextTests.class));
|
||||
|
||||
this.managedVariableNames = (String[]) managedVarNames.toArray(new String[managedVarNames.size()]);
|
||||
}
|
||||
|
||||
private boolean isProtectedInstanceField(Field field) {
|
||||
int modifiers = field.getModifiers();
|
||||
return !Modifier.isStatic(modifiers) && Modifier.isProtected(modifiers);
|
||||
}
|
||||
|
||||
private void populateProtectedVariables() throws IllegalAccessException {
|
||||
for (int i = 0; i < this.managedVariableNames.length; i++) {
|
||||
String varName = this.managedVariableNames[i];
|
||||
Object bean = null;
|
||||
try {
|
||||
Field field = findField(getClass(), varName);
|
||||
bean = getApplicationContext().getBean(varName, field.getType());
|
||||
field.setAccessible(true);
|
||||
field.set(this, bean);
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("Populated field: " + field);
|
||||
}
|
||||
}
|
||||
catch (NoSuchFieldException ex) {
|
||||
if (this.logger.isWarnEnabled()) {
|
||||
this.logger.warn("No field with name '" + varName + "'");
|
||||
}
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException ex) {
|
||||
if (this.logger.isWarnEnabled()) {
|
||||
this.logger.warn("No bean with name '" + varName + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Field findField(Class clazz, String name) throws NoSuchFieldException {
|
||||
try {
|
||||
return clazz.getDeclaredField(name);
|
||||
}
|
||||
catch (NoSuchFieldException ex) {
|
||||
Class superclass = clazz.getSuperclass();
|
||||
if (superclass != AbstractSpringContextTests.class) {
|
||||
return findField(superclass, name);
|
||||
}
|
||||
else {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.test;
|
||||
|
||||
import org.springframework.beans.factory.support.BeanDefinitionReader;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.ResourceUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Abstract JUnit 3.8 test class that holds and exposes a single Spring
|
||||
* {@link org.springframework.context.ApplicationContext ApplicationContext}.
|
||||
* </p>
|
||||
* <p>
|
||||
* This class will cache contexts based on a <i>context key</i>: normally the
|
||||
* config locations String array describing the Spring resource descriptors
|
||||
* making up the context. Unless the {@link #setDirty()} method is called by a
|
||||
* test, the context will not be reloaded, even across different subclasses of
|
||||
* this test. This is particularly beneficial if your context is slow to
|
||||
* construct, for example if you are using Hibernate and the time taken to load
|
||||
* the mappings is an issue.
|
||||
* </p>
|
||||
* <p>
|
||||
* For such standard usage, simply override the {@link #getConfigLocations()}
|
||||
* method and provide the desired config files. For alternative configuration
|
||||
* options, see {@link #getConfigPath()} and {@link #getConfigPaths()}.
|
||||
* </p>
|
||||
* <p>
|
||||
* If you don't want to load a standard context from an array of config
|
||||
* locations, you can override the {@link #contextKey()} method. In conjunction
|
||||
* with this you typically need to override the {@link #loadContext(Object)}
|
||||
* method, which by default loads the locations specified in the
|
||||
* {@link #getConfigLocations()} method.
|
||||
* </p>
|
||||
* <p>
|
||||
* <b>WARNING:</b> When doing integration tests from within Eclipse, only use
|
||||
* classpath resource URLs. Else, you may see misleading failures when changing
|
||||
* context locations.
|
||||
* </p>
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
* @author Sam Brannen
|
||||
* @since 2.0
|
||||
* @see #getConfigLocations()
|
||||
* @see #contextKey()
|
||||
* @see #loadContext(Object)
|
||||
* @see #getApplicationContext()
|
||||
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
|
||||
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
|
||||
*/
|
||||
@Deprecated
|
||||
public abstract class AbstractSingleSpringContextTests extends AbstractSpringContextTests {
|
||||
|
||||
/** Application context this test will run against */
|
||||
protected ConfigurableApplicationContext applicationContext;
|
||||
|
||||
private int loadCount = 0;
|
||||
|
||||
|
||||
/**
|
||||
* Default constructor for AbstractSingleSpringContextTests.
|
||||
*/
|
||||
public AbstractSingleSpringContextTests() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor for AbstractSingleSpringContextTests with a JUnit name.
|
||||
* @param name the name of this text fixture
|
||||
*/
|
||||
public AbstractSingleSpringContextTests(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* This implementation is final. Override <code>onSetUp</code> for custom behavior.
|
||||
* @see #onSetUp()
|
||||
*/
|
||||
protected final void setUp() throws Exception {
|
||||
// lazy load, in case getApplicationContext() has not yet been called.
|
||||
if (this.applicationContext == null) {
|
||||
this.applicationContext = getContext(contextKey());
|
||||
}
|
||||
prepareTestInstance();
|
||||
onSetUp();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare this test instance, for example populating its fields.
|
||||
* The context has already been loaded at the time of this callback.
|
||||
* <p>The default implementation does nothing.
|
||||
* @throws Exception in case of preparation failure
|
||||
*/
|
||||
protected void prepareTestInstance() throws Exception {
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses can override this method in place of the <code>setUp()</code>
|
||||
* method, which is final in this class.
|
||||
* <p>The default implementation does nothing.
|
||||
* @throws Exception simply let any exception propagate
|
||||
*/
|
||||
protected void onSetUp() throws Exception {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to say that the "applicationContext" instance variable is dirty
|
||||
* and should be reloaded. We need to do this if a test has modified the
|
||||
* context (for example, by replacing a bean definition).
|
||||
*/
|
||||
protected void setDirty() {
|
||||
setDirty(contextKey());
|
||||
}
|
||||
|
||||
/**
|
||||
* This implementation is final. Override <code>onTearDown</code> for
|
||||
* custom behavior.
|
||||
* @see #onTearDown()
|
||||
*/
|
||||
protected final void tearDown() throws Exception {
|
||||
onTearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses can override this to add custom behavior on teardown.
|
||||
* @throws Exception simply let any exception propagate
|
||||
*/
|
||||
protected void onTearDown() throws Exception {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a key for this context. Default is the config location array as
|
||||
* determined by {@link #getConfigLocations()}.
|
||||
* <p>If you override this method, you will typically have to override
|
||||
* {@link #loadContext(Object)} as well, being able to handle the key type
|
||||
* that this method returns.
|
||||
* @return the context key
|
||||
* @see #getConfigLocations()
|
||||
*/
|
||||
protected Object contextKey() {
|
||||
return getConfigLocations();
|
||||
}
|
||||
|
||||
/**
|
||||
* This implementation assumes a key of type String array and loads a
|
||||
* context from the given locations.
|
||||
* <p>If you override {@link #contextKey()}, you will typically have to
|
||||
* override this method as well, being able to handle the key type that
|
||||
* <code>contextKey()</code> returns.
|
||||
* @see #getConfigLocations()
|
||||
*/
|
||||
protected ConfigurableApplicationContext loadContext(Object key) throws Exception {
|
||||
return loadContextLocations((String[]) key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a Spring ApplicationContext from the given config locations.
|
||||
* <p>The default implementation creates a standard
|
||||
* {@link #createApplicationContext GenericApplicationContext}, allowing
|
||||
* for customizing the internal bean factory through
|
||||
* {@link #customizeBeanFactory}.
|
||||
* @param locations the config locations (as Spring resource locations,
|
||||
* e.g. full classpath locations or any kind of URL)
|
||||
* @return the corresponding ApplicationContext instance (potentially cached)
|
||||
* @throws Exception if context loading failed
|
||||
* @see #createApplicationContext(String[])
|
||||
*/
|
||||
protected ConfigurableApplicationContext loadContextLocations(String[] locations) throws Exception {
|
||||
++this.loadCount;
|
||||
if (this.logger.isInfoEnabled()) {
|
||||
this.logger.info("Loading context for locations: " + StringUtils.arrayToCommaDelimitedString(locations));
|
||||
}
|
||||
return createApplicationContext(locations);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Spring {@link ConfigurableApplicationContext} for use by this test.
|
||||
* <p>The default implementation creates a standard {@link GenericApplicationContext}
|
||||
* instance, calls the {@link #prepareApplicationContext} prepareApplicationContext}
|
||||
* method and the {@link #customizeBeanFactory customizeBeanFactory} method to allow
|
||||
* for customizing the context and its DefaultListableBeanFactory, populates the
|
||||
* context from the specified config <code>locations</code> through the configured
|
||||
* {@link #createBeanDefinitionReader(GenericApplicationContext) BeanDefinitionReader},
|
||||
* and finally {@link ConfigurableApplicationContext#refresh() refreshes} the context.
|
||||
* @param locations the config locations (as Spring resource locations,
|
||||
* e.g. full classpath locations or any kind of URL)
|
||||
* @return the GenericApplicationContext instance
|
||||
* @see #loadContextLocations(String[])
|
||||
* @see #customizeBeanFactory(DefaultListableBeanFactory)
|
||||
* @see #createBeanDefinitionReader(GenericApplicationContext)
|
||||
*/
|
||||
protected ConfigurableApplicationContext createApplicationContext(String[] locations) {
|
||||
GenericApplicationContext context = new GenericApplicationContext();
|
||||
prepareApplicationContext(context);
|
||||
customizeBeanFactory(context.getDefaultListableBeanFactory());
|
||||
createBeanDefinitionReader(context).loadBeanDefinitions(locations);
|
||||
context.refresh();
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the GenericApplicationContext used by this test.
|
||||
* Called before bean definitions are read.
|
||||
* <p>The default implementation is empty. Can be overridden in subclasses to
|
||||
* customize GenericApplicationContext's standard settings.
|
||||
* @param context the context for which the BeanDefinitionReader should be created
|
||||
* @see #createApplicationContext
|
||||
* @see org.springframework.context.support.GenericApplicationContext#setResourceLoader
|
||||
* @see org.springframework.context.support.GenericApplicationContext#setId
|
||||
*/
|
||||
protected void prepareApplicationContext(GenericApplicationContext context) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Customize the internal bean factory of the ApplicationContext used by
|
||||
* this test. Called before bean definitions are read.
|
||||
* <p>The default implementation is empty. Can be overridden in subclasses to
|
||||
* customize DefaultListableBeanFactory's standard settings.
|
||||
* @param beanFactory the newly created bean factory for this context
|
||||
* @see #loadContextLocations
|
||||
* @see #createApplicationContext
|
||||
* @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding
|
||||
* @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowEagerClassLoading
|
||||
* @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences
|
||||
* @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping
|
||||
*/
|
||||
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method for creating new {@link BeanDefinitionReader}s for
|
||||
* loading bean definitions into the supplied
|
||||
* {@link GenericApplicationContext context}.
|
||||
* <p>The default implementation creates a new {@link XmlBeanDefinitionReader}.
|
||||
* Can be overridden in subclasses to provide a different
|
||||
* BeanDefinitionReader implementation.
|
||||
* @param context the context for which the BeanDefinitionReader should be created
|
||||
* @return a BeanDefinitionReader for the supplied context
|
||||
* @see #createApplicationContext(String[])
|
||||
* @see BeanDefinitionReader
|
||||
* @see XmlBeanDefinitionReader
|
||||
*/
|
||||
protected BeanDefinitionReader createBeanDefinitionReader(GenericApplicationContext context) {
|
||||
return new XmlBeanDefinitionReader(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses can override this method to return the locations of their
|
||||
* config files, unless they override {@link #contextKey()} and
|
||||
* {@link #loadContext(Object)} instead.
|
||||
* <p>A plain path will be treated as class path location, e.g.:
|
||||
* "org/springframework/whatever/foo.xml". Note however that you may prefix
|
||||
* path locations with standard Spring resource prefixes. Therefore, a
|
||||
* config location path prefixed with "classpath:" with behave the same as a
|
||||
* plain path, but a config location such as
|
||||
* "file:/some/path/path/location/appContext.xml" will be treated as a
|
||||
* filesystem location.
|
||||
* <p>The default implementation builds config locations for the config paths
|
||||
* specified through {@link #getConfigPaths()}.
|
||||
* @return an array of config locations
|
||||
* @see #getConfigPaths()
|
||||
* @see org.springframework.core.io.ResourceLoader#getResource(String)
|
||||
*/
|
||||
protected String[] getConfigLocations() {
|
||||
String[] paths = getConfigPaths();
|
||||
String[] locations = new String[paths.length];
|
||||
for (int i = 0; i < paths.length; i++) {
|
||||
String path = paths[i];
|
||||
if (path.startsWith("/")) {
|
||||
locations[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
|
||||
}
|
||||
else {
|
||||
locations[i] = ResourceUtils.CLASSPATH_URL_PREFIX +
|
||||
StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(getClass()) + "/" + path);
|
||||
}
|
||||
}
|
||||
return locations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses can override this method to return paths to their config
|
||||
* files, relative to the concrete test class.
|
||||
* <p>A plain path, e.g. "context.xml", will be loaded as classpath resource
|
||||
* from the same package that the concrete test class is defined in. A path
|
||||
* starting with a slash is treated as fully qualified class path location,
|
||||
* e.g.: "/org/springframework/whatever/foo.xml".
|
||||
* <p>The default implementation builds an array for the config path specified
|
||||
* through {@link #getConfigPath()}.
|
||||
* @return an array of config locations
|
||||
* @see #getConfigPath()
|
||||
* @see java.lang.Class#getResource(String)
|
||||
*/
|
||||
protected String[] getConfigPaths() {
|
||||
String path = getConfigPath();
|
||||
return (path != null ? new String[] { path } : new String[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses can override this method to return a single path to a config
|
||||
* file, relative to the concrete test class.
|
||||
* <p>A plain path, e.g. "context.xml", will be loaded as classpath resource
|
||||
* from the same package that the concrete test class is defined in. A path
|
||||
* starting with a slash is treated as fully qualified class path location,
|
||||
* e.g.: "/org/springframework/whatever/foo.xml".
|
||||
* <p>The default implementation simply returns <code>null</code>.
|
||||
* @return an array of config locations
|
||||
* @see #getConfigPath()
|
||||
* @see java.lang.Class#getResource(String)
|
||||
*/
|
||||
protected String getConfigPath() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the ApplicationContext that this base class manages; may be
|
||||
* <code>null</code>.
|
||||
*/
|
||||
public final ConfigurableApplicationContext getApplicationContext() {
|
||||
// lazy load, in case setUp() has not yet been called.
|
||||
if (this.applicationContext == null) {
|
||||
try {
|
||||
this.applicationContext = getContext(contextKey());
|
||||
}
|
||||
catch (Exception e) {
|
||||
// log and continue...
|
||||
if (this.logger.isDebugEnabled()) {
|
||||
this.logger.debug("Caught exception while retrieving the ApplicationContext for test [" +
|
||||
getClass().getName() + "." + getName() + "].", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.applicationContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current number of context load attempts.
|
||||
*/
|
||||
public final int getLoadCount() {
|
||||
return this.loadCount;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user