i need to invoke the method base on the cron pattern. this is my java code .where i included one method and this method i need to call.i try in google but not getting any idea how to call.
public class Schedule {
int i;
public String show()
{
return "hi"+i++;
}
public static void main(String args[])throws Exception
{
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure() {
from("quartz2://myGroup/myfirstrigger?cron=0/2+*+*+*+*+?").to(new Schedule().show());
}
});
context.start();
}
}
i am not sure also this is right or not
You should look at the documentation on bean binding (Here). I think your route would be better like the following:
from("quartz2://myGroup/myfirstrigger?cron=0/2+*+*+*+*+?")
.bean(Schedule.class, "show");
Related
I want to make periodical REST request with a Dropwizard Backend. More concretely I want to make an GET request to an external REST API every minute and process the result.
I used the quartz here and now I try to use the jersey client to make a REST request. I use guice as my dependency injection.
My application class has the following methods
#Override
public void initialize(final Bootstrap<DockerwizardConfiguration> bootstrap) {
Job everyJob = new EveryTestJob();
bootstrap.addBundle(new JobsBundle(everyJob));
}
#Override
public void run(final DockerwizardConfiguration configuration,
final Environment environment) {
Injector injector = Guice.createInjector(new AbstractModule() {
#Override
protected void configure() {
bind(HelloWorldParameter.class)
.annotatedWith(Names.named("helloWorldParameter"))
.toInstance(configuration.getHelloWorldParameter());
}
});
JerseyClientConfiguration conf = configuration.getJerseyClientConfiguration();
conf.setChunkedEncodingEnabled(false);
final Client client = new JerseyClientBuilder(environment).using(conf).build(getName());
environment.jersey().register(new ExternalServiceResource(client)); // How should that be implented with guice
environment.jersey().register(injector.getInstance(HelloWorldResource.class));
}
And my EveryTestJob class is implemented as follows
#Every("1s")
public class EveryTestJob extends Job {
#Override
public void doJob(JobExecutionContext context) throws JobExecutionException {
// logic run every time and time again
}
}
I am unsure how I this can be organized.
I've been trying to figure this out for a while, and this is what I have found out:
The JobBundle is added before any Resources so the JobExecutionContext will not include the client (https://www.dropwizard.io/0.9.2/docs/manual/internals.html)
Tried using the injector but didn't work either (https://github.com/HubSpot/dropwizard-guice)
Finally I stumbled on Jersey 2.0: Create repeating job which showed how to add the client into the context!
Here's my solution:
In the resource class,
#Path("/myPath")
public class myResource {
#Inject
public myResource() {
try {
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.getContext().put"myResource", this); // Inserts myResource into the context
} catch (SchedulerException e) {
// Handle exception
}
}
// Other stuff for api
}
Then in the job class (I'm using Dropwizard-jobs 2.0.1 where doJobs doesn't take in any arguments so I used execute instead),
#Every("10s")
public class myJob extends Job {
#Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
myResource res = (myResource) context.getScheduler().getContext().get("myResource");
// Do stuff with your resource
} catch (SchedulerException e) {
// Handle exception
}
}
}
Not sure if you have access to the ExternalServiceResource, but I hope this helps!
I have method which every now and then generates a string. I would like to register method as uri and produce a exchange method which will be used as input for a route.
The method is call by a different class
SampleClass sc = new SampleClass();
sc.sampleMethod("Hello");
Eg:
public class SampleClass{
#Produce(uri = "direct:consumerMethod")
ProducerTemplate producer;
public sampleMethod(Object obj){
producer.sendBody(object);
}
}
The route is defined as below:
#Override
public void configure() {
from("direct:consumerMethod").process(new GenerateD());
}
But the route doesnt call GenerateD class when i produce using the sampleMethod. Is this not feasible or am i doing something wrong?
Finally this is what worked for my use case.
Starting camelcontext as below:
CamelContext camelContext = new DefaultCamelContext();
camelContext.addRoutes(new SampleRoute());
camelContext.start();
My routebuilder class :
class SampleRoute extends RouteBuilder {
#Override
public void configure() {
try
{
from("direct:consumerMethod").process(new DDT());
}catch(Exception e)
{
e.printStackTrace();
}
}
}
I then create a interface which has a sendMessage method.
public interface DDTConsumer {
public String sendMessage(Object object);
}
Now i implement this method to create an endpoint of this interface and send a message to the endpoint.
DDTConsumer ddt;
try {
ddt = new ProxyBuilder(camelContext).endpoint("direct:consumerMethod").build(DDTConsumer.class);
ddt.sendMessage(msg.getValue());
} catch (Exception e) {
e.printStackTrace();
}
This solved my problem and the route is working fine now. Hope it helps others as well.
In your class where you have the sampleMethod(Object) add the following field:
#Produce(uri = "direct:consumerMethod")
ProducerTemplate template;
In your sampleMethod(Object) you can use the previously added template like this:
public sampleMethod(Object obj){
template.sendBody(object);
}
And it should send a Message to the direct:consumerMethod route.
Use something like this, if you want to call somemethod
#Override
public void configure() {
from("direct:consumerMethod").log(simple("${bean:generateD?method=generateDMethod}"));
}
The above expression will call the generateDMethod of generateD object (bean) and log the methods output to console (the default log writer).
To make above expression work, you have to store generateD bean in the Registry, which will be further associated with your application's CamelContext. You can do the same as follows
#Autowired
private GenerateD generateD;
#Override
protected CamelContext createCamelContext() throws Exception {
SimpleRegistry registry = new SimpleRegistry();
registry.put("generateD", generateD); //the generateD bean,which can be used anywhere in the camelcontext
SpringCamelContext camelContext = new SpringCamelContext();
camelContext.setRegistry(registry); //add the registry
camelContext.setApplicationContext(getApplicationContext());
camelContext.start();
return camelContext;
}
This adds the bean to camelContext. Please check my answer at this link to have complete example.
I am using Play Framework and using Java as the language of choice. I have a Controller which makes a REST call to an external service. I intend to mock the external service, so that I can test the functionality of my controller. To achieve this, I have created my test cases as shown below (sample). I am embedding a server within my test to mock the external service.
public class SomeControllerTest extends WithApplication {
private static Server SERVER;
#Override
protected Application provideApplication() {
final Module testModule = new AbstractModule() {
#Override
public void configure() {
bind(AppDao.class).to(MockAppDaoImpl.class);
}
};
return new GuiceApplicationBuilder().in(Environment.simple()).overrides(testModule).build();
}
#BeforeClass
public static void setup() {
Router router = new RoutingDsl()
.POST("/api/users")
.routeTo(() -> created())
.build();
SERVER = Server.forRouter(router, 33373);
PORT = SERVER.httpPort();
}
#AfterClass
public static void tearDown() {
SERVER.stop();
}
#Test
public void testCreateUser() {
ObjectNode obj = Json.newObject();
obj.put("name", "John Doe");
obj.put("email", "john.doe#example.com");
Http.RequestBuilder request = new Http.RequestBuilder()
.method(POST)
.bodyJson(obj)
.uri("/some/url/here");
Result result = route(request);
assertEquals(ERR_MSG_STATUS_CODE, CREATED, result.status());
assertEquals(ERR_MSG_CONTENT_TYPE, Http.MimeTypes.JSON, result.contentType().get());
}
My expectation is that when I run the test, the mock server would run and based on my application's test configuration, my controller will make a call to the mock server which would return 201 and my test case would pass.
But, this doesn't happen, because as soon as setup() method completes, the mock server is killed, and my controller cannot make a call to it.
What am I doing wrong here?
Testing of controller should be rather done by inheritance from WithApplication
public class TestController extends WithApplication {
#Test
public void testSomething() {
Helpers.running(Helpers.fakeApplication(), () -> {
// put test stuff
// put asserts
});
}
}
In order to test a controller method use Helpers.fakeRequest and reverse routing.
The external service may be just mocked with mockito or other mocking framework you like.
You can find here several examples.
Is anyone aware of any examples of testing a Java based Play Framework controller by setting mock objects?
I am using Spring in my Play project so all my controller methods are not static.
Testing the tradional way, Play shows my controller as having static methods and I just cant see a way of how I can inject mocks into my object
Result result = callAction(
controllers.routes.ref.LoginController.authenticate(),
fakeRequest().withFormUrlEncodedBody(TestUtils.SUCCESSFUL_LOGIN_MAP)
);
I have a number of services that need to be called in the LoginController and I would like to set those up as mocks
Any help is greatly appreciated
Thanks
Damien
I was looking for the solution of the same problem. So far the best result I was able to achieve is this:
public class MyObjectControllerTest{
private final MyObjectDAO dao = mock(MyObjectDAO.class);
private final MyObjectController controller = new MyObjectController(dao);
public static FakeApplication fakeApplication;
#BeforeClass
public static void startApp() {
fakeApplication = Helpers.fakeApplication();
Helpers.start(fakeApplication);
}
#AfterClass
public static void stopApp() {
Helpers.stop(fakeApplication);
}
#Test(expected = NotFoundException.class)
public void testFailWithUnknownMyObjectKey() throws Throwable {
when(dao.getByKey(any(UUID.class), any(UUID.class), any(Boolean.class))).thenReturn(null);
controller.get(CassandraUUIDs.timeBased());
}
#Test
public void testGetSuccess(){
MyObject deletedObject = MyObjectTestGenerator.generateMyObject();
deletedObject.setDeleted(true);
when(dao.getByKey(any(UUID.class), any(UUID.class), any(Boolean.class))).thenReturn(deletedObject);
try {
Result result = controller.get(CassandraUUIDs.timeBased());
assertThat(status(result)).isEqualTo(Http.Status.GONE);
assertThat(contentType(result)).isEqualTo(Http.MimeTypes.JSON);
assertThat(contentAsString(result)).isEqualTo(ErrorMsg.OBJECT_DELETED.toJson().toString());
} catch (MyObjectsException e) {
e.printStackTrace();
fail("Failed to send MyObject.get request.");
}
}
}
What I do here is instantiate an instance of the controller class and pass mocked DAO instance. Please note that I don't use static controller methods in my code as well.
One issue with this workaround I found so far is that Action (I have custom one) is not working. But Action can (and probably must) be tested separately.
Is it possible to use callbacks with Spring to that they are managed by application context?
My problem is when a service is used from outer by #Autowired, but within that service there is a callback defined using new operator.
The following example executes a method that is worth retrying. Spring offers a RetryCallback for this case (I know this could be acchieved differently, but just to illustrate my callback problem).
#Service
class MyService {
//main method invoked
void run(DataVO dataVO) {
//new operator not usable in spring context
RetryCallback<Object> retryCallback = new RetryCallback<Object>() {
#Override
public Object doWithRetry(RetryContext context) throws Exception {
return createBooking(dataVO);
}
};
}
private Object createBooking(DataVO dataVO) {
//creates the booking, worth retry on specific failures
//uses further injected/autowired services here
}
}
Is it possible to refactor this snippet so that the callback is managed by spring/injected/autowired?
Make your service implement the callback interface :
#Service
class MyService implements RetryCallback<Object> {
//main method invoked
void run(DataVO dataVO) {
}
#Override
public Object doWithRetry(RetryContext context) throws Exception {
return createBooking(dataVO);
}
private Object createBooking(DataVO dataVO) {
//creates the booking, worth retry on specific failures
//uses further injected/autowired services here
}
}