service returning null when calling from another model - service

I have created an replication service to publish a page and its assets using replicator...but whenever I am trying to call this service to a util class,it is returning null.Can anyone help me with why I am getting null and how to get the instance of the service?
the service is in .../core/services/ReplicationService
the model is in ../core/utils/ModelUtils
this is how I am calling the service:
#OSGiService
static ReplicationService replicationService;
I tried annotating with #reference also...but of no use...
this is how I created the service:
#Component(service=ReplicationService.class,immediate=true)
public class ReplicationServiceImpl implements ReplicationService{
}

utils is a simple java class...services can be injected with annotations only into components..thats why it is getting null...I have changed my approach and called it from another class which is a workflow process..it is working fine...thanks every one..hope this helps any one..

Related

How to override main application.yml with testing application.yml when testing REST API in an Autowired service class?

I'm writing automated test using TestNG for the REST API of my application. The application has a RestController which contains an #Autowired service class. When the REST endpoint is called with a HTTP GET request, the service looks into a storage directory for XML files, transforms their contents into objects and stores them in a database. The important thing for my question is that the path to the storage directory is stored in /src/main/resources/application.yml (source.storage) and imported via a #Value annotation.
Now, I have the source.storage property also in src/test/resources/application.yml pointing to a different directory within src/test, where I store my testing XML files, and import them to my test class with a #Value annotation again. My test calls the REST endpoint with a HTTP GET. However, it seems that the service still draws the source.storage property the main application.yml, while I would like that value overriden by the one in test application.yml file. In other words, the service tries to import XML files from the application storage directory, rather than from my testing storage.
#ActiveProfiles and #TestPropertySource do not seem to work for me. Scanning the main application.yml for its storage property is not an option, as in the end the application.yml will be drawn from a Spring Cloud Config, and I would not know where the main application.yml would be located.
Is there a way with which I could make the #Autowired service draw the source.storage property from the test application.yml, rather from the main one?
Any advice would be appreciated.
Thanks, Petr
Well, it really depends on what you're trying to build, if it is some sort of unit test of the controller or more likely an integration test. Both approaches are explained in this tutorial.
If you're trying to write integration test, which seems a bit more likely from your question, then #ActiveProfiles or #TestPropertySource should work for you. I would suggest to use profiles, in growing application with a lot of properties it is a bit more convenient to just replace some of the properties for the testing. Below is setup which worked for me when writing integration tests for controller endpoints:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ActiveProfiles("test")
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class AreaControllerTest {
#Autowired
TestRestTemplate rest;
#MockBean
private JobExecutor jobExecutor;
#Test
public void test01_List() {
//
}
#Test
public void test02_Get() {
//
}
// ...
}
There are several important things.
The testing properties are in src/test/resources/application-test.properties and merges with the ones in application.properties as the #ActiveProfiles("test") annotation suggests.
Essential is also #RunWith(SpringRunner.class) which is JUnit specific, for TestNG alternative please refer to this SO question.
Finally the #SpringBootTest annotation will start the whole application context.
#FixMethodOrder and #DirtiesContext are further setup of the testing case and are not really necessary.
Notice also the #MockBean annotation, in this case we did not wanted to use real-life implementation of JobExecutor, so we replaced it with mock.
If you want to write unit test where you want to just check the logic of controller and service on their own, then you have to have two test classes, each testing respective classes. Testing service should be standard unit test, testing controller is a bit trickier and is probably more inclined to partial integration test. If this is your case I would recommend to use MockMvc approach explained in the above mentioned tutorial. Small snippet from there:
#RunWith(SpringRunner.class)
#WebMvcTest(GreetingController.class)
public class WebMockTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private GreetingService service;
#Test
public void greetingShouldReturnMessageFromService() throws Exception {
when(service.greet()).thenReturn("Hello Mock");
this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello Mock")));
}
}
Notice the #MockBean annotation which mocks service where you can specify your own behaviour of mock. This point is critical, because this sort of test does not load whole application context, but only MVC context, so the services are not available. Again as in the integration test the #RunWith(SpringRunner.class) annotation is essential. Finally #WebMvcTest(GreetingController.class) starts only MVC context of the GreetingController class and not the whole application.
You can try supplying the property directly to the spring boot test.
#SpringBootTest(properties= {"source.storage=someValue"})
Regarding the application picking up the wrong property source, You should also check if your application is being built properly.

How to avoid multiple instances of a service in Angular Dart

It seems that each component that creates its own instance of [a] service. I don't understand why.
I note this AngularJs 2 - multiple instance of service created, but I'm not clear on the correct solution. Do I create the service instance _myService in main:
void main() {
bootstrap(AppComponent,[MyService]);
}
and then copy it to [child] components (because I also remove MyService from the component providers)? This doesn't seem correct, because the components reference _myService before it's instantiated, and I have to check it for being null.
Thanks
Steve
You can use factory constructor pattern like here.
Creating your service in the bootstrap will make sure there is only one instance of it for the app (if you don't provide it again in some component).
You get multiple copies of it only if you provide it in some #Component - then each instance of the component (and all its children) will have a separate instance of the service.

No event context active - RESTeasy, Seam

I'm trying to add a RESTful web service with RESTeasy to our application running on JBoss 7.x, using Seam2.
I wanted to use as little Seam as possible, but I need it for Dependancy Injection.
My REST endpoints are as follows:
#Name("myEndpoint")
#Stateless
#Path("/path")
#Produces(MediaType.APPLICATION_JSON+"; charset=UTF-8")
public class MyEndpoint {
#In private FooService fooService;
#GET
#Path("/foo/{bar}")
public Response foobar(#CookieParam("sessionId") String sessionId,
#PathParam("bar") String bar)
{ ... }
}
I'm using a class extending Application. There is no XML config.
I can use the web service methods and they work, but I always get an IllegalStateException:
Exception processing transaction Synchronization after completion: java.lang.IllegalStateException: No event context active
Complete StackTrace
I did try everything in the documentation, but I can't get it away. If I leave out the #Stateless annotation, I don't get any Injection done. Adding #Scope doesn't do jack. Accessing the service via seam/resource/ doesn't even work (even without the Application class with #ApplicationPath).
It goes away if I don't use Dep. Injection, but instead add to each and every method
fooService = Component.getInstance("fooService");
Lifecycle.beginCall();
...
Lifecycle.endCall();
which isn't really a good solution. Nah, doesn't work either...
I have resolved the issue. For some reason (still not sure why, maybe because I tried to use Annotations and code exclusivly and no XML config), my REST service was availiable under a "non-standard" URL.
Usually it'd be something like "/seam/resources/rest".
Anyway, if you have a "custom" path, Seam doesn't know it should inject a context. You need to add <web:context-filter url-pattern="something" /> to your component.xml.
Specifically we already had this tag, but with the attribute regex-url-pattern and I extended it to match the REST URL.

JAXRS tries to call Interface instead of Implementation

I got a JAXRS application. I have an Interface class (SomeResource) (where i put most of my annotations) and an implementation of this interface (SomeService).
I have registered the SomeService.class in the overriden JaxRSApplication method .getClasses();
All my other services/resources are implemented in the same way, but whenever i try to call this one service (SomeService), i get the following exception:
"Error 500: javax.servlet.ServletException: java.lang.IllegalAccessException: Class org.apache.wink.server.internal.handlers.InvokeMethodHandler can not access a member of class package.api.SomeResource with modifiers "public abstract""
As you can see, for some reason, this one Service tries to call the Resource(Interface) instead of the the Service class with the actual implementation.
Anyone got an idea how to resolve this? (Real classnames hidden because of security).
Be sure to declare the implementation class of the service (SomeService.class) with its full qualified classname and not the interface within your rest service configurationen of your application.
The way you have to do that depends on the implementing framework.
Have a look here:
http://cxf.apache.org/docs/jaxrs-services-configuration.html

Griffon integration tests with jpa

I'm writing a griffon application with JavaFX and the JPA plugin. I have a service I'd like to test - this service makes use of the JPA plugin (withJpa {...}) and it's this database access that I want to test.
So, I want to write this test so it inserts some data, then check that the service produces the right answer thus verifying the sql query is correct.
I've written a simple test:
class ReportServiceTests extends GriffonUnitTestCase {
GriffonApplication app
public void testStats() {
println app.getServices()
println app.getControllers()
}
}
but I cannot get hold of a valid service - both the println statements above produce "[:]".
How do I get hold of the 'ReportService' instance and exercise it against the database? I don't want to mock the database interaction.
Thanks.
There's no need to mock the database. As explained in http://griffon.codehaus.org/guide/latest/guide/testing.html#integrationTesting applications reach the INITIALIZE phase during integration testing. Addons get initialized during this phase. Services on the other hand get initialized lazily as they are pulled in by MVC members when instantiated: they do not get instantiated out-of-the-box if you call app.getServices(). However you can instruct the application to eagerly instantiate all services, this will make your code work as expected; just add the following flag to Config.groovy
griffon.services.eager.instantiation = true
More info on services can be found at http://griffon.codehaus.org/guide/latest/guide/controllersAndServices.html#services