I know how to make and work with a Scheduled job in Wildfly as such:
#Stateless
public class MyTasks{
#Schedule(hour = "*", minute = "5")
public void doWork() {
System.out.println("helo world!");
}
}
How do I update the timer or execute this schedule immediately without having to update the code. In JBoss 4, using MBeans and the JMX console I could change the timer and execute the job whenever. Is there something or somewhere that allows me access this task?
What I would ideally like is something like below:
#ManagedBean
public class ManagedTask{
public void executeTask() {
//Not valid
MyTasks mytasks = new MyTasks();
mytasks.setTimer(...):
mytasks.do work();
}
}
#Stateless
public class MyTasks {
#Resource
private javax.ejb.TimerService timerService;
public void scheduleTimer() {
// Pick from a number of createTimer methods. This one expires in 5 seconds
Timer nextTimer = timerService.createTimer(5000, null);
}
#Timeout
public void doWork() {
System.out.println("helo world!");
}
}
Related
I have a WCF Service:
[ServiceTelemetry]
public class MyWCFClass()
{
private TelemetryClient telemetryClient;
public MyWCFClass()
{
telemetryClient = new TelemetryClient()
{
InstrumentationKey = RoleEnvironment.GetConfigurationSettingValue("APPINSIGHTS_INSTRUMENTATIONKEY")
};
}
public string TheMethod()
{
return "Nice";
}
}
Works like a charm. Now I want to unit test this WCF service:
[TestMethod()]
public void DoTest()
{
MyWCFClass theClass = new MyWCFClass();
Assert.AreEqual("Nice", theClass.TheMethod());
}
My problem is, that when I run the test, an SEH exception occurs on the constructor of the WCFClass.
Is there any way to fake the RoleEnvironment part or skip the telemetry part?
Sorry for my english.... May be someone help me find information about using batch job with role-based security in glassfish server?
When I invoke the method from EJB :
#Override
#RolesAllowed({"root_role", "admin_role", "user_role"})
public void execute() {
BatchRuntime.getJobOperator().start(STATISTIC_JOB_NAME, new Properties());
}
I get exception like this:
javax.ejb.AccessLocalException: Client not authorized for this invocation
My job class:
#Dependent
#Named(value = "StatisticJob")
public class StatisticJob extends AbstractBatchlet {
#EJB
private StatisticFacadeLocal sfl;
#Override
public String process() throws Exception {
System.out.println("StatisticJob.process()");
List<StatisticPortEntity> spes = sfl.findAll();
if (spes != null && !spes.isEmpty()) {
for (StatisticPortEntity spe : spes) {
System.out.println(spe);
}
} else {
return "Statistic list is empty.";
}
return "StatisticJob.proccess is done.";
}
}
How use role-based security with batch?
Thank's!
When I add a property in the application.properties files, this can be access from the main class without any problem.
#SpringBootApplication
#ComponentScan(basePackages = "com.example.*")
public class MailTestApplication implements CommandLineRunner {
#Value("${admin.mail}")
String email;
public static void main(String[] args) {
SpringApplication.run(MailTestApplication.class, args);
}
#Override
public void run(String... strings) throws Exception {
System.out.println(email);
Email email = new Email();
email.sendMail();
}
}
However, when I try to access it from any other class it is never retrieved.
#Component
public class Email {
#Autowired
private MailSender sender;
#Value("${admin.mail}")
String email;
public Email() {
}
public void sendMail() {
SimpleMailMessage msg = new SimpleMailMessage();
System.out.println(email);
msg.setTo("sample#email.com");
msg.setSubject("Send mail by Spring Boot");
msg.setText("Send mail by Spring Boot");
sender.send(msg);
}
}
I was reading some of the previous questions other users posted without a clear result for me. I even tried to find some examples with similar resutl.
Could someone give me any clue about this?
Thanks a lot in advance.
The #Value should work (Im asuming your class is under the com.example.* package since you are scanning that package) but if you want to do it another way this is what im using :
public class JpaConfiguration {
public static final String TRANSACTION_MANAGER_NAME = "jpaTransactionManager";
#Autowired
Environment applicationProperties;
Then to use it
#Bean
public DriverManagerDataSource driverManagerDataSource() {
DriverManagerDataSource driverConfig = new DriverManagerDataSource();
driverConfig.setDriverClassName(applicationProperties.getProperty("data.jpa.driverClass"));
driverConfig.setUrl(applicationProperties
.getProperty("data.jpa.connection.url"));
driverConfig.setUsername(applicationProperties
.getProperty("data.jpa.username"));
driverConfig.setPassword(applicationProperties
.getProperty("data.jpa.password"));
return driverConfig;
}
UPDATE AFTER GETTING THE GITHUB REPO
I Don't really know what you are trying to build but :
If you do this:
#Override
public void run(String... strings) throws Exception {
//System.out.println(email);
Email email = new Email();
email.sendMail();
}
Then you are creating the instance of the class, and not spring. so you shouldn't be creating the instance yourself there it should be spring.
That said, i dont know if you are creating a web application a command line application or both.
That said ill give you a minor solution to show you that the dependency injection is in fact working.
1_ add a getter to your email on email class. remove the CommandLine interface (If you want to implement this i would recomend you to put CommandLine implmentations on another package say Controller);
And then run your app like this:
#SpringBootApplication
#ComponentScan(basePackages = "com.example")
public class MailTestApplication {
#Value("${admin.mail}")
String email;
public static void main(String[] args) {
// SpringApplication.run(MailTestApplication.class, args);
final ConfigurableApplicationContext context = new SpringApplicationBuilder(MailTestApplication.class).run(args);
Email e = context.getBean(Email.class);
System.out.println(e.getEmail());
}
The Key thing I want to show is that the instance is created by spring thats why the wiring works. and the email gets printed in the console.
Regarding the email class :
#Component
public class Email {
// #Autowired
// private MailSender sender;
#Value("${admin.mail}")
String email;
public Email() {
}
public void sendMail() {
SimpleMailMessage msg = new SimpleMailMessage();
System.out.println(email);
msg.setTo("sample#email.com");
msg.setSubject("Send mail by Spring Boot");
msg.setText("Send mail by Spring Boot");
// sender.send(msg);
}
public String getEmail() {
return email;
}
}
I Comment out the MailSender since I think you need to configure that too, i have made a custom mailSender that uses gmail and other for mailChimp that i can share with you if you need. but again I dont really know what your intent with the app is.
Hope the info helps you.
I'm playing with a simple handler that implements IWantToRunWhenBusStartsAndStops and in the start, it schedules a task like so:
public void Start()
{
_schedule.Every(TimeSpan.FromSeconds(5), Moo);
}
_schedule is injected via the constructor. The test I'm trying write is to make sure the task is scheduled when the handler starts. But I can't find a way to mock Schedule as it doesn't have a no-arg constructor and it doesn't implement an interface. I tried creating an actual instance of it with a mocked IBuilder but can't figure out what expectations to set on the IBuilder. Also, I looked at the source to see how they were testing Schedule but it looks like we're on an earlier version (v5.0.0 via nuget) because we don't have a DefaultScheduler which appears to be what they use in their current tests.
In fact NServiceBus team has already covered the scheduler with unit/acceptance test, i.e. there is no need to check whether the task was actually scheduled when your handler is executed. Instead you would probably want to unit test your handler itself, thus check if call to scheduler.Every() has been made. Here is simple example of how your unit test might look like:
[TestClass]
public class Tests
{
[TestMethod]
public void When_executing_handler_the_task_should_be_scheduled()
{
//arrange
var scheduler = new FakeSheduler();
//act
var handler = new TestHandler(scheduler);
handler.Start();
//assert
Assert.IsTrue(scheduler.WasCalled);
}
}
The handler itself:
class TestHandler: IWantToRunWhenBusStartsAndStops
{
readonly IMyScheduler _scheduler;
public TestHandler(IMyScheduler scheduler)
{
_scheduler = scheduler;
}
public void Start()
{
_scheduler.Every(TimeSpan.FromSeconds(5), () => { });
}
public void Stop() { }
}
Finally, you have to abstract from direct usage of NServiceBus scheduler in order to make it testable, here is the idea:
interface IMyScheduler
{
void Every(TimeSpan interval, Action action);
}
//your real implementation
class MySheduler: IMyScheduler
{
readonly Schedule _schedule;
public MySheduler(Schedule schedule)
{
_schedule = schedule;
}
public void Every(TimeSpan interval, Action action)
{
_schedule.Every(TimeSpan.FromSeconds(5), () => { });
}
}
//fake for the testing
class FakeSheduler: IMyScheduler
{
public bool WasCalled { get; set; }
public void Every(TimeSpan interval, Action action)
{
WasCalled = true;
}
}
I'm trying to do some performance logging with NServiceBus using a custom IManageUnitsOfWork implementation. Unfortunately, my custom IManageUnitsOfWork is never invoked and I'm not sure why. My current implementation looks like this:
public class UnitsOfWorkManager : IManageUnitsOfWork
{
private readonly Logger logger;
private readonly Stopwatch stopwatch;
public UnitsOfWorkManager()
{
this.logger = LogManager.GetCurrentClassLogger();
this.stopwatch = new Stopwatch();
}
public void Begin()
{
this.stopwatch.Start();
}
public void End(Exception ex = null)
{
this.stopwatch.Stop();
this.logger.Info("HANDLERS ELAPSED DURATION: " + this.stopwatch.ElapsedMilliseconds);
}
}
I have my Unity container registering the object as normal:
container.RegisterType<IManageUnitsOfWork, UnitsOfWorkManager>();
Is there something else I need to do to get this called? I'm using a Windows Service, not the NSB host. I'm currently using version 3.2.8.
Try adding an instance name to the registration:
container.RegisterType<IManageUnitsOfWork, UnitsOfWorkManager>("UnitsOfWorkManager");