I have modified my Java project(Web service) into Dynamic web module. I'm using Tomcat 7.0.59 as server. While starting server it is getting started without any issues. But once if I tried to access the Web service method then I will end up with the error saying that -"Could not initialize class DataLayer.HibernateAdapter java.lang.NoClassDefFoundError: Could not initialize class DataLayer.HibernateAdapter". Anyone please help me than just marking it a "Duplicate". If code has to be modified, please provide me detail steps. Thanks!!
Console Log:
Mar 10, 2015 2:09:07 PM com.sun.xml.ws.server.sei.EndpointMethodHandler invoke
SEVERE: Could not initialize class DataLayer.HibernateAdapter
java.lang.NoClassDefFoundError: Could not initialize class DataLayer.HibernateAdapter
at DataLayer.DatabaseContext.<init>(DatabaseContext.java:12)
at DataLayer.ConsumerDetails.getConsumerdetails(ConsumerDetail.java:84)
at ManageLayer.Authenticate(AuthenticationManager.java:50)
at ManageLayer.Console.GetProductsList(Console.java:484)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.xml.ws.api.server.InstanceResolver$1.invoke(InstanceResolver.java:246)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:146)
DatabaseContext.java :
public class DatabaseContext
{
private final Session session;
public DatabaseContext() {
this.session = HibernateAdapter.getSessionFactory().openSession();
}
public Session delegate() {
return session;
}
public void close() {
session.flush();
session.close();
}
}
class HibernateAdapter
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try
{
return new AnnotationConfiguration()
.addAnnotatedClass(Consumer.class)
.addAnnotatedClass(Product.class)
.addAnnotatedClass(PriceTag.class)
.addAnnotatedClass(Barcode.class)
.configure().buildSessionFactory();
}
catch (Throwable e)
{
System.err.println("Exception while creating Initial SessionFactory" + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
A NoClassDefFoundError usually indicates that your class path is not correct. Check if you have the right Hibernate libraries in your class path. e.g. in the project settings, if you are using Eclipse. Right now, you are not including the DataLayer.HibernateAdapter class correctly, so Tomcat cannot find it.
Related
I am facing some difficulties in writing junit test to pass the for loop condition to getParts() method from SlingHttpServletRequest.getParts(). There is no problem with the implementation, I am able to process the file attachment properly. However, I am unable to do so in the junit test.
The following is my implementation:
#Model(adaptables = SlingHttpServletRequest.class)
public class Comment {
//Variables declaration
#Inject
private CommentService service;
#PostConstruct
public void setup() {
requestData = new JSONObject();
for (String item : request.getRequestParameterMap().keySet()) {
try {
requestData.put(item, request.getParameter(item));
}
} catch (Exception e) {
Throw error message
}
}
//Upload attachment to server
try {
for (Part part : request.getParts()) { <= The JUnit test stopped at this line and throw the error below
} catch (Exception e) {
Throw error message
}
I have tried using a SlingHttpServletRequestWrapper class to override the getParts method but to no avail.
The following is my junit test:
public class CommentTest {
public final AemContext context = new AemContext();
private CommentService commentService = mock(CommentService.class);
#InjectMocks
private Comment comment;
private static String PATH = "/content/testproject/en/page/sub-page";
#Before
public void setUp() throws Exception {
context.addModelsForPackage("de.com.adsl.sightly.model");
context.load().json("/components/textrte.json", PATH);
context.currentPage(PATH);
}
#Test
public void testSetup() throws IOException, ServletException {
//before
context.request().setParameterMap(getRequestCat1());
context.registerService(CommentService.class, commentService);
Resource resource = context.resourceResolver().getResource(PATH + "/jcr:content/root/responsivegrid/textrte");
assertNotNull(resource);
//when
comment = new CustomRequest(context.request()).adaptTo(Comment.class);
//then
comment.setup();
}
private class CustomRequest extends SlingHttpServletRequestWrapper {
public CustomRequest(SlingHttpServletRequest request) {
super(request);
}
#Override
public Collection<Part> getParts() {
final String mockContent =
"------WebKitFormBoundarycTqA2AimXQHBAJbZ\n" +
"Content-Disposition: form-data; name=\"key\"\n" +
"\n" +
"myvalue1\n" +
"------WebKitFormBoundarycTqA2AimXQHBAJbZ";
final List<Part> parts = MockPart.parseAll(mockContent);
assertNotNull(parts);
return parts;
}
};
}
The following is the error message that I encountered:
14:53:04.918 [main] ERROR de.com.adsl.sightly.model.Comment - Error Message: null
java.lang.UnsupportedOperationException: null
at org.apache.sling.servlethelpers.MockSlingHttpServletRequest.getParts(MockSlingHttpServletRequest.java:882) ~[org.apache.sling.servlet-helpers-1.1.10.jar:?]
at de.com.adsl.sightly.model.Comment.uploadFile(Feedback.java:137) ~[classes/:?]
at de.com.adsl.sightly.model.Comment.setup(Feedback.java:82) [classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_201]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_201]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_201]
at org.apache.sling.models.impl.ModelAdapterFactory.invokePostConstruct(ModelAdapterFactory.java:792) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.createObject(ModelAdapterFactory.java:607) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.internalCreateModel(ModelAdapterFactory.java:335) [org.apache.sling.models.impl-1.3.8.jar:?]
at org.apache.sling.models.impl.ModelAdapterFactory.getAdapter(ModelAdapterFactory.java:211) [org.apache.sling.models.impl-1.3.8.jar:?]
...
I have looked up various solutions online such as writing two mockito when statements but has not been successful. I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!
From the source code of MockSlingServletResquest it always throws that exception as it's not supported yet by the mocked class.
https://github.com/apache/sling-org-apache-sling-servlet-helpers/blob/71ef769e5564cf78e49d6679a3270ba8706ae406/src/main/java/org/apache/sling/servlethelpers/MockSlingHttpServletRequest.java#L953
Maybe you should consider writing a servlet, or another approach.
I'm having problems with using Guice's assisted inject within my spigot plugin, and can't seem to narrow down the problem. This is the error I'm getting:
> [12:00:38 INFO]: [DestinyMC] Enabling DestinyMC v1.0
> 2019-01-14 12:00:41,492 Log4j2-TF-1-AsyncLogger[AsyncContext#5c647e05]-1 ERROR An exception occurred processing Appender File com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: zip file closed
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2217)
at com.google.common.cache.LocalCache.get(LocalCache.java:4154)
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:4158)
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:5147)
at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:5153)
at com.google.inject.internal.util.StackTraceElements.forMember(StackTraceElements.java:71)
at com.google.inject.internal.Messages.formatSource(Messages.java:241)
at com.google.inject.internal.Messages.formatSource(Messages.java:220)
at com.google.inject.internal.Messages.formatMessages(Messages.java:90)
at com.google.inject.CreationException.getMessage(CreationException.java:50)
at org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:134)
at org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:122)
at org.apache.logging.log4j.core.async.RingBufferLogEvent.getThrownProxy(RingBufferLogEvent.java:330)
at org.apache.logging.log4j.core.pattern.ExtendedThrowablePatternConverter.format(ExtendedThrowablePatternConverter.java:61)
at org.apache.logging.log4j.core.pattern.PatternFormatter.format(PatternFormatter.java:38)
at org.apache.logging.log4j.core.layout.PatternLayout$PatternSelectorSerializer.toSerializable(PatternLayout.java:455)
at org.apache.logging.log4j.core.layout.PatternLayout.toText(PatternLayout.java:232)
at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:217)
at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:57)
at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.directEncodeEvent(AbstractOutputStreamAppender.java:177)
at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.tryAppend(AbstractOutputStreamAppender.java:170)
at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.append(AbstractOutputStreamAppender.java:161)
at org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender.append(RollingRandomAccessFileAppender.java:218)
at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156)
at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129)
at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:448)
at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:433)
at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:417)
at org.apache.logging.log4j.core.config.AwaitCompletionReliabilityStrategy.log(AwaitCompletionReliabilityStrategy.java:79)
at org.apache.logging.log4j.core.async.AsyncLogger.actualAsyncLog(AsyncLogger.java:337)
at org.apache.logging.log4j.core.async.RingBufferLogEvent.execute(RingBufferLogEvent.java:161)
at org.apache.logging.log4j.core.async.RingBufferLogEventHandler.onEvent(RingBufferLogEventHandler.java:45)
at org.apache.logging.log4j.core.async.RingBufferLogEventHandler.onEvent(RingBufferLogEventHandler.java:29)
at com.lmax.disruptor.BatchEventProcessor.processEvents(BatchEventProcessor.java:168)
at com.lmax.disruptor.BatchEventProcessor.run(BatchEventProcessor.java:125)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: zip file closed
at java.util.zip.ZipFile.ensureOpen(Unknown Source)
at java.util.zip.ZipFile.getEntry(Unknown Source)
at java.util.jar.JarFile.getEntry(Unknown Source)
at java.util.jar.JarFile.getJarEntry(Unknown Source)
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:120)
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:104)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.google.inject.internal.util.StackTraceElements$1.load(StackTraceElements.java:49)
at com.google.inject.internal.util.StackTraceElements$1.load(StackTraceElements.java:45)
at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3716)
at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2424)
at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2298)
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2211)
... 39 more
This is my Binder Class:
public class MainBinder extends AbstractModule {
#Override
protected void configure() {
bind(DestinyMC.class).toInstance(this.plugin);
install(new FactoryModuleBuilder().build(InventoryFromFileFactory.class));
}
The error goes away when I comment out the install line. That line uses this factory class
public interface InventoryFromFileFactory {
InventoryFromFile create(String targetRootKey, String targetFile);
}
which declare the parameters that need to be manually provided at object creation for this class:
public class InventoryFromFile {
#Inject
public InventoryFromFile
(
#Assisted String targetRootKey,
#Assisted String targetFile,
ConfigAccessorFactory configAccessorFactory
)
{
ConfigurationSection targetCS = configAccessorFactory.create(targetFile).getCustomConfig().getConfigurationSection(targetRootKey);
...
}
}
The ConfigAccessFactory is another factory class for assisted inject
public interface ConfigAccessorFactory {
ConfigAccessor create(String filename);
}
which is used here:
public class ConfigAccessor {
private Plugin plugin;
private final String customFileName;
#Inject
public ConfigAccessor
(
#Assisted String fileName,
DestinyMC plugin
)
{
this.customFileName = fileName;
this.plugin = plugin;
}
...
}
Finally, the DestinyMC dependency is the main class for the spigot plugin:
public class DestinyMC extends JavaPlugin {
//Inject dependencies
#Inject private ConfigAccessorFactory configAccessorFactory;
//Code only run once when the plugin is enabled
public void onEnable() {
MainBinder mainBinder = new MainBinder(this);
Injector injector = Guice.createInjector(mainBinder);
injector.injectMembers(this);
//Saves config files to disk if they don't exist
saveDefaultConfig();
Arrays.asList(
"inventory-gui.yml",
"player-tree-template.yml",
"player-tree-data.yml"
).forEach((file) -> {
configAccessorFactory.create(file).saveDefaultConfig();
});
...
}
I'm not too sure what I'm doing wrong, but I'm fairly new to Guice so I'm most likely misunderstanding something. Also, if there's simply a better way to do this, let me know. Thanks for the help.
first I want to say that I have seen all the topics here on stackoverflow for my case but wasn't able to solve my problem anyway.
I need to run scheduled task every night to check weather the task was finished or not - I'm doing like this:
#Service
#Transactional
public class CronBackGroundProcess {
#Autowired
private CronJobService cronJobService;
#Scheduled(cron = "15 01 01 ? * *")
public void StartNightJob() {
CronJobLog log = new CronJobLog();
int count = 0;
try {
log.setStartTime(new Date());
log.setStatus("Entered StartNightJob Function");
cronJobService.saveCronJobLog(log);
List<Task> Tasks = cronJobService.getActive_AND_InArreasTasks();
log.setStatus("Grabbed List of tasks to Check");
cronJobService.saveCronJobLog(log);
for (Task Task : Tasks) {
cronJobService.StartNightJobProcess(Task, true);
count++;
}
} catch (Exception e) {
CronJobLog log2 = new CronJobLog();
log2.setStatus("Error Occurred " + new Date().toString() + e.getMessage());
cronJobService.saveCronJobLog(log2);
}
log.setLoansChecked(count);
log.setStatus("Finished");
log.setEndDate(new Date());
cronJobService.saveCronJobLog(log);
}
}
CronJobService itself is #Transactional and autowires several #Transactional services
#Service
#Transactional
public class CronJobService {
#Autowired
private ProductService productService;
#Autowired
private RepaymentService repaymentService;
#Autowired
private CronJobLogDAO cronJobLogDAO;
#Autowired
private TransferService transferService;
public String StartNightJobProcess(Account account, boolean makeTransfers) {
do something....
}
}
}
the process goes without errors and when all transactions must be committed I receive such error:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:524) ~[spring-orm-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:478) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:272) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) ~[spring-tx-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646) ~[spring-aop-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at ge.shemo.services.core.CronBackGroundProcess$$EnhancerByCGLIB$$30cdcf31.StartNightJob(<generated>) ~[spring-core-4.0.0.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_79]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_79]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65) ~[spring-context-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81) [spring-context-4.0.0.RELEASE.jar:4.0.0.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [na:1.7.0_79]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_79]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178) [na:1.7.0_79]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292) [na:1.7.0_79]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_79]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_79]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_79]
Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:58) ~[hibernate-entitymanager-5.0.1.Final.jar:5.0.1.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:515) ~[spring-orm-4.0.0.RELEASE.jar:4.0.0.RELEASE]
... 22 common frames omitted
I can't figure out why.
Also If I launch same function from #Controller it works fine
#Controller
#RequestMapping("/test")
public class test {
#Autowired
private ClientService clientService;
#Autowired
private CronBackGroundProcess cronBackGroundProcess;
#RequestMapping(value = "/test")
#ResponseBody
public void test() throws Exception {
try {
cronBackGroundProcess.StartNightJob();
} catch (Exception e) {
String s = "sd";
}
}
}
So my question is why this function works from controller - commits everything as expected and not works from scheduled task(goes through all process without errors)?
If you can then, put a debug break-point in org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionInfo txInfo, Throwable ex) and then see what the actual exception is.
You not need mark CronBackGroundProcess as #Transactional because in StartNightJob() method you not have access to db all access to DB as I guess you execute in CronJobService.
So remove #Transactional from CronBackGroundProcess and it must help.
I am trying to use dropwizard-sundial and am having trouble with a resource. I'm not sure if it's a classpath issue or if I am failing to register resources properly.
This is my application class' run method:
public void run(DataLoaderApplicationConfiguration configuration, Environment environment) throws Exception {
logger.info("Started DataLoader Application");
final String template = configuration.getTemplate();
environment.healthChecks().register("TemplateHealth", new TemplateHealthCheck(template));
// JOBS
environment.jersey().packages("com.tradier.dataloader.jobs");
}
I get the following error at runtime:
INFO [2015-04-07 15:00:19,737] com.xeiam.sundial.plugins.AnnotationJobTriggerPlugin: Loading annotated jobs from com.tradier.dataloader.jobs.
[WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.RuntimeException: Unexpected problem: No resource for com/tradier/dataloader/jobs
at org.quartz.classloading.CascadingClassLoadHelper.getJobClasses(CascadingClassLoadHelper.java:217)
at com.xeiam.sundial.plugins.AnnotationJobTriggerPlugin.start(AnnotationJobTriggerPlugin.java:72)
at org.quartz.QuartzScheduler.startPlugins(QuartzScheduler.java:1102)
at org.quartz.QuartzScheduler.start(QuartzScheduler.java:211)
at com.xeiam.sundial.SundialJobScheduler.startScheduler(SundialJobScheduler.java:102)
Check out a working example at https://github.com/timmolter/XDropWizard. It uses annotated jobs. You need to add the package name conatining the annotated jobs in your config.yaml file like this:
sundial:
thread-pool-size: 5
shutdown-on-unload: true
wait-on-shutdown: false
start-delay-seconds: 0
start-scheduler-on-load: true
global-lock-on-load: false
annotated-jobs-package-name: org.knowm.xdropwizard.jobs
If you still are getting an exception, leave a report at: https://github.com/timmolter/dropwizard-sundial/issues.
#Jeyashree Narayanan, the jobs package should not be configured in the application class as you have shown, it can be easily done in the yml file. Here is the explanation in simple steps:
Step 1: Configuration in yml file and the Configuration class
sundial:
thread-pool-size: 10
shutdown-on-unload: true
start-delay-seconds: 0
start-scheduler-on-load: true
global-lock-on-load: false
annotated-jobs-package-name: com.tradier.dataloader.jobs
tasks: [startjob, stopjob]
Configuration Class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class DropwizardSundialConfiguration extends Configuration {
#Valid
#NotNull
public SundialConfiguration sundialConfiguration = new SundialConfiguration();
#JsonProperty("sundial")
public SundialConfiguration getSundialConfiguration() {
return sundialConfiguration;
}
}
Step 2: Add and configure the dropwizard-sundial bundle in the application class.
public class DropwizardSundialApplication extends Application<DropwizardSundialConfiguration> {
private static final Logger logger = LoggerFactory.getLogger(DropwizardSundialApplication.class);
public static void main(String[] args) throws Exception {
new DropwizardSundialApplication().run("server", args[0]);
}
#Override
public void initialize(Bootstrap<DropwizardSundialConfiguration> b) {
b.addBundle(new SundialBundle<DropwizardSundialConfiguration>() {
#Override
public SundialConfiguration getSundialConfiguration(DropwizardSundialConfiguration configuration) {
return configuration.getSundialConfiguration();
}
});
}
}
Step 3: Add the required job classes.
Here is a sample Cron job class:
#CronTrigger(cron = "0 19 13 * * ?")
public class CronJob extends Job {
private static final Logger logger = LoggerFactory.getLogger(CronJob.class);
#Override
public void doRun() throws JobInterruptException {
logger.info("Hello from Cron Job");
}
}
I have also written a blog post and a working application which is available on GitHub with these steps. Please check: http://softwaredevelopercentral.blogspot.com/2019/05/dropwizard-sundial-scheduler-tutorial.html
It appears to be a classpath issue.
From https://github.com/timmolter/Sundial/blob/develop/src/main/java/com/xeiam/sundial/SundialJobScheduler.java#L102:
public static void startScheduler(int threadPoolSize, String annotatedJobsPackageName) {
try {
createScheduler(threadPoolSize, annotatedJobsPackageName);
getScheduler().start(); // ---> Line 102
} catch (SchedulerException e) {
logger.error("COULD NOT START SUNDIAL SCHEDULER!!!", e);
throw new SchedulerStartupException(e);
}
I'm also using Sundial in my dropwizard project, I have all my jobs defined in jobs.xml, Sundial config defined in the .yaml file, and start it as follows:
SundialJobScheduler.startScheduler();
SundialManager sm = new SundialManager(config.getSundialConfiguration(),environment);
environment.lifecycle().manage(sm);
I' m developing a simple JSF application which uses Hibernate. I imported all required libraries to WEB-INF/lib folder and also point them in classpath. But when I tried to compile it I got error:
Here is code where I create SessionFactory and use it:
private static SessionFactory buildSessionFactory()
{
try
{
Configuration configuration = new Configuration();//This line
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry( );
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Exception e)
{
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory()
{
return buildSessionFactory();
}
And here I use it:
public static void saveUser( String title)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Client client = new Client();
......
So what am I doing wrong? How can I fix this?
The javax.transaction.SystemException is in the jta-x.y.jar (x.y is the required version for the version of Hibernate you use). It should be in your classpath.
Hibernate requires a lot of libraries. To manage the dependencies, you should use something like Maven or Ivy.