I would like to do an ESB solution, where I want to use a generic based webservice.
I can do the definition, generate all needed classes, the service exists, but the wsdl deficient. Missing the "generic part", that part what defined by generic type.
The ancestor:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(propOrder = { "header", "body" })
public abstract class WSRequest<T> {
protected RequestHeader header;
protected T body;
public RequestHeader getHeader()
{
return header;
}
public void setHeader(RequestHeader header)
{
this.header = header;
}
public T getBody()
{
return body;
}
public void setBody(T body)
{
this.body = body;
}
}
And the descendant:
public class PartnerRequest extends WSRequest<PartnerData>
{
}
The service work correctly, but the generated wsdl doesn't contain the PartnerData structure.
I'm new in WS part, so that is the real possibility it is impossible.
Please help me to solve the problem (or reject this idea)
Thx!
Feri
So, the problem was that, the base XSD was too complex. (I generated it by an XML, and th generator program made very elegant xsd, what was unusable! :-( )
Too complex mean:
....
<xs:element ref="ugyfelKod"/>
...
<xs:element name="ugyfelKod" type="xs:NCName"/>
...
Related
I am a Dagger newbie.
TL;DR:
If an Android Service has any fields injected into it using Dagger, then in order to actually perform the injection, I need to have an instance of that Service.
In Robolectric tests, this corresponds to MyService service = Robolectric.buildService(MyService.class).get(). And then, objectGraph.inject(service);
However, rest of the code that actually starts MyService still uses context.startService(context, MyService.class);.
Question: What is the idiomatic way in Dagger to address this mismatch?
Let's say I have a Service as follows:
public class MyService {
#Inject Parser parser;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String data = intent.getStringExtra("data_to_be_parsed");
parser.parse(data);
}
}
Elsewhere in my code, I have an ApiClient class that does this:
public class ApiClient{
public static void parseInBackground(Context context, String data){
//This service does not have its fields injected
context.startService(new Intent(context, MyService.class).putExtra("data_to_be_parsed", data));
}
}
That parseInBackground method will be called from an Activity in response to user interaction.
Now, I'm following TDD and hence, I haven't yet written the Application Module for this. Here's the test module:
#Module(injects = MyService.class)
public class TestModule {
#Provides #Singleton Parser provideParser(){
return new MockParser();
}
}
And finally, the test case:
#RunWith(Robolectric.class)
public class ApiTest {
#Test
public void parseInBackground_ParsesCorrectly(){
//This service has its fields injected
MyService service = Robolectric.buildService(MyService.class).get();
ObjectGraph.create(new TestModule()).inject(service);
ApiClient.parseInBackground(Robolectric.application, "<user><name>droid</name></user>");
//Asserts here
}
}
As you can see, in the test, I retrieve an instance of the service and then inject the MockParser into it. However, the ApiClient class directly starts the service using an Intent. I don't have a chance to perform the injection.
I am aware that I can have MyService perform an injection on itself:
public void onCreate(){
ObjectGraph.create(new TestModule()).inject(this);
}
But then, I am hardcoding the TestModule here.
Is there an existing idiom in Dagger to set up dependencies for such situations?
It's the wrong way to hardcode your modules either in tests or in services. Better approach is to perform creation via your custom Application object which in turn will hold singleton ObjectGraph object. For example:
// in MyService class
#Override public void onCreate() {
super.onCreate();
MyApp.from(context).inject(this);
}
// in MyApp class
public static MyApp from(Context context) {
return (MyApp) context.getApplicationContext();
}
//...
private ObjectGraph objectGraph;
#Override public void onCreate() {
// Perform Injection
objectGraph = ObjectGraph.create(getModules());
objectGraph.inject(this);
}
public void inject(Object object) {
objectGraph.inject(object);
}
protected Object[] getModules() {
// return concrete modules based on build type or any other conditions.
}
Alternatively, you can refactor last method out into separate class and make different implementations for different flavors or build types. Also you may want to set overrides=true in your TestModule's annotation.
I have the following four classes: DataConsumer, DataProducer, SomeQualifier, a META-INF/beans.xml and a test. The class files are coded as follows:
public class DataConsumer {
private boolean loaded = false;
#Inject
#SomeQualifier
private String someString;
public void afterBeanDiscovery(
#Observes final AfterBeanDiscovery afterBeanDiscovery,
final BeanManager manager) {
loaded = true;
}
public boolean getLoaded() {
return loaded;
}
public String sayHello() {
return someString;
}
}
public class DataProducer {
#Produces
#SomeQualifier
private final String sample = "sample";
}
public #interface SomeQualifier {
}
The unit test looks like this.
public class WeldTest {
#Test
public void testHelloWorld() {
final WeldContainer weld = new Weld().initialize();
final DataConsumer consumer = weld.instance()
.select(DataConsumer.class).get();
Assert.assertEquals("sample", consumer.sayHello());
Assert.assertTrue(consumer.getLoaded());
}
}
However, it is failing on the assertTrue with getLoaded() it appears that the #Observes does not get fired.
Take a look at arquillian: www.arquillian.org. It'll take care of all of this for you.
I found a similar question that had answered my question
CDI - Observing Container Events
Although I am unable to use DataConsumer as both an Extension and a CDI managed bean. So it needs a third class just to be the Extension. However, because Extension have no access to managed beans since they are not created yet, I conclude that is no possible solution to use an #Observes AfterBeanDiscovery to modify the bean data. Even the BeanManager that gets passed in cannot find any of the beans.
I have a stateless session bean which is exposed as webservice. There are two methods and both have #webmethod annotation. But, only one of the method is exposed as webservice. Could anyone point out reason for this behaviour, please find the code below:
#WebService(portName = "interfaceSoapHTTPPort", serviceName = "interfaceService", targetNamespace = "http://com.demo.service/interfaceservice", endpointInterface = "com.demo.service.interfacePortType")
#SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
#Stateless(mappedName = "InterfaceBean")
public class InterfaceBean {
#PostConstruct
#PostActivate
public void initializeBean() {
}
#WebMethod
public void processPathEvent(XngEvent pathXngEvent) throws WSException {
}
#WebMethod
public void portAssignmentUpdate(WSHeader wsHeader,
PortAssignmentUpdateRequest portAssignmentUpdateRequest,
Holder<WSResponseHeader> wsResponseHeader,
Holder<PortAssignmentUpdateResponse> portAssignmentUpdateResponse)
throws WSException {
}
}
Only portAssignmentUpdate method is exposed as webservice, but not the processPathEvent method.
Thank you.
I was able to solve the problem.
We have set "endpointInterface" property in #webservice annotation. I had forgotten to added the processPathEvent() method to this interface. Hence, the method was not exposed even when #webmethod annotation is added.
I'm trying to test my Session Beans with JUnit, but I can't. I've tried a lot of method, but still get some exceptions.
Here is what I need:
I have a few Stateless Session Beans I need to test. Each has the same #PersistenceContext and uses an EntityManager
With my test cases I need to test their methods. For instance: if I add an user with username X and then I try to add another one with the same username, I want to catch an Exception.
Can someone provide a simple and short generic test example? I've already read many, but I always get an error (I get NullPointerException for the EntityManager when I call a method like: sessionBean.method() (which does, for instance, entityManager.find(...)), or I am not able to initialize the Context, or other PersistenceException).
You might be interested in one of the latest posts of Antonio Goncalves:
WYTIWYR : What You Test Is What You Run
It tells about testing EJB with EntityManager using:
Mockito,
Embedded EJB Container,
Arquillian.
I solved creating a Stateless Session Bean and injecting its Entity Manager to test classes. I post the code in case someone will need it:
#Stateless(name = "TestProxy")
#Remote({TestProxyRemote.class})
public class TestProxy implements TestProxyRemote {
#PersistenceContext(unitName = "mph")
private EntityManager em;
#Override
public void persist(Object o) {
em.persist(o);
}
#Override
public void clear() {
em.clear();
}
#Override
public void merge(Object o) {
em.merge(o);
}
#Override
#SuppressWarnings({ "rawtypes", "unchecked" })
public Object find(Class classe, String key) {
return em.find(classe, key);
}
#Override
#SuppressWarnings({ "rawtypes", "unchecked" })
public Object find(Class classe, long key) {
return em.find(classe, key);
}
#SuppressWarnings("rawtypes")
#Override
public List getEntityList(String query) {
Query q = em.createQuery(query);
return q.getResultList();
}
}
public class MyTest {
#BeforeClass
public static void setUpBeforeClass() throws NamingException {
Properties env = new Properties();
env.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
env.setProperty(Context.PROVIDER_URL, "localhost:1099");
env.setProperty("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
jndiContext = new InitialContext(env);
try {
proxy = (TestProxyRemote) jndiContext.lookup("TestProxy/remote");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
Then I can use proxy.find() to get the entities I need, o proxy.getEntityList() to execute a query to retrieve all the instance of an Entity. Or I can add other methods if I want.
Unitils provides a really cool support for JPA. Unitils can be used with JUnit or TestNG and in case you need a mocking framework, Unitils provides its own mocking module as well as support for EasyMock.
#JpaEntityManagerFactory(persistenceUnit = "testPersistenceUnit")
#DataSet(loadStrategy = RefreshLoadStrategy.class)
public class TimeTrackerTest extends UnitilsTestNG {
#TestedObject
private TimeTrackerBean cut = new TimeTrackerBean();
#InjectInto(target="cut",property="em")
#PersistenceContext
private EntityManager em;
#Test
#DataSet("TimeTrackerTest.testAddTimeSlot.xml")
public void yourTest() {
...
}
}
#JpaEntityManagerFactory - Used to specify your persistence unit. It automatically picks up the persistence.xml from your project classpath.
#DataSet - Just in case you need to load any test data you can use this.
#TestedObject - Marks your Class Under Test
#PersistenceContext - Automatically creates your EntityManager instance from the configurations made in the persistence.xml - PersistenceUnit.
#InjectInto - Injects the em instance into the target (cut)
For more information refer this.
Hope this helps.
I'm using Needle for this. It works well with Mockito and EasyMock if you want to mock other objects.
First I write a persistencte.xml for tests (src/test/resources/META-INF) like this:
<persistence-unit name="rapPersistenceTest" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/test"/>
...
</properties>
</persistence-unit>
In my Junit-Testclass I write:
public class DaoNeedleTest {
//here Needle will create persistenceContext for your testclass
public static DatabaseRule databaseRule = new DatabaseRule("rapPersistenceTest");
//here you can get the entityManager to manipulate data directly
private final EntityManager entityManager = databaseRule.getEntityManager();
#Rule
public NeedleRule needleRule = new NeedleRule(databaseRule);
//here you can instantiate your daoService
#ObjectUnderTest
DAOService daoService;
#Test
public void test() {
//if your method needs a transaction here you can get it
entityManager.getTransaction().begin();
daoService.yourMethod();
entityManager.getTransaction().commit();
}
You also need a Needle-configuration File in src/test/resources, where you tell what kind of Mock-provider you are using. E.g. I'm using Mockito:
mock.provider=de.akquinet.jbosscc.needle.mock.MockitoProvider
That's it.
I am using Jersey/Java to develop my REST services. I need to return an XML representation for my CarStore :
#XmlRootElement
public class CarStore {
private List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
Here is my Car object :
#XmlRootElement
> public class Car {
private String carName;
private Specs carSpecs;
private Category carCategory;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public Specs getCarSpecs() {
return carSpecs;
}
public void setCarSpecs(Specs carSpecs) {
this.carSpecs = carSpecs;
}
public Category getCarCategory() {
return carCategory;
}
public void setCarCategory(Category carCategory) {
this.carCategory = carCategory;
}
}
Specs and Category are enums like this :
#XmlRootElement
> public enum Category {
SEDANS, COMPACTS, WAGONS, HATCH_HYBRIDS, SUVS, CONVERTIBLES, COMPARABLE;
}
My resource class is :
#GET
#Produces({MediaType.APPLICATION_XML})
public CarStore getCars()
{
return CarStoreModel.instance.getAllCars();
}
My jersey client is :
WebResource service = client.resource(getBaseURI());
System.out.println(service.path("rest").path("cars").accept(
MediaType.APPLICATION_XML).get(String.class));
I am getting Http 204 error on access alongwith client exception :
com.sun.jersey.api.client.UniformInterfaceException
Any ideas ? Thanks !
EDIT : I have yet not developed the model class...I just initialized some car objects as dummy data and put them in carstore. Showing all the classes here would be very clumsy.
BTW, sorry for writing 204 Error..it is just that I am getting an Exception that led me think so.
I'm guessing the exception is not related to the response code (204) because 204 is a success condition that indicates "No Content."
I believe you are getting a UniformInterfaceException because your getCars() function is not returning an HTTP response body. The root problem is that your Car List isn't being converted into XML by JAXB because it is missing the #XmlElement annotation.
Your getCars() function should be:
#GET
#Produces(MediaType.APPLICATION_XML)
public CarStore getCars() {
// myCarStore is an instance of CarStore
return myCarStore.getCars();
}
and your Car List in CarStore should be defined:
#XmlElement(name="car")
private List<Car> cars;
Is what you're returning in xml format? I'm not sure what getAllCars does but you can use something like Fiddler to help you view the traffic and see what is being returned to the client and whether its in proper format etc
In your client code, is the resource path correct? Make sure getBaseURI is returning a value.
Perhaps try:
Client client = new Client();
WebResource resource = client.resource(getBaseURI());
CarStore carStore = resource.path("/rest/cars").accept(MediaType.APPLICATION_XML).get(CarStore.class);
Aren't you missing a #Path annotation on your resource class?
#GET
#Path("cars")
#Produces({ MediaType.APPLICATION_XML })
public CarStore getCars() {
return CarStoreModel.instance.getAllCars();
}
Check if the URL at which your REST WS is mounted the one you expect by putting a breakpoint in your getCars() method (or putting a System.out.println) to make sure it actually gets called.
It seems there is a hard coded check in Jersey to throw a UniformInterfaceException when a HTTP 204 is returned.
The best solution will be to 'fix' the rest server so it never returns a null. e.g. return an Empty list or a Class with not values set.
Else you will need to catch UniformInterfaceException which is really ugly
if (getStatus() == 204) {
throw new UniformInterfaceException(this);
}
More info here :
http://grepcode.com/file/repo1.maven.org/maven2/com.sun.jersey/jersey-client/1.17.1/com/sun/jersey/api/client/ClientResponse.java#ClientResponse.getEntity%28java.lang.Class%2Cjava.lang.reflect.Type%29