quartz threw an unhandled Exception: : java.lang.NullPointerException with JSF+EJB - jsf-2

I am using JSF and EJB in my project.
I have one functionality where i need to send the sms to some people for every 1 hour.
For that i am getting the information(some persons) from the database to whom i need to send.
While retrieving from the database it is throwing the following exceptions.
09:51:29,640 ERROR [org.quartz.core.JobRunShell] (DefaultQuartzScheduler_Worker-2) Job group1.job1 threw an unhandled Exception: : java.lang.NullPointerException
at hms.general.SendSMSJob.execute(SendSMSJob.java:43) [classes:]
at org.quartz.core.JobRunShell.run(JobRunShell.java:213) [quartz-all-2.1.7.jar:]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557) [quartz-all-2.1.7.jar:]
09:51:29,640 ERROR [org.quartz.core.ErrorLogger] (DefaultQuartzScheduler_Worker-2) Job (group1.job1 threw an exception.: org.quartz.SchedulerException: Job threw an unhandled exception. [See nested exception: java.lang.NullPointerException]
at org.quartz.core.JobRunShell.run(JobRunShell.java:224) [quartz-all-2.1.7.jar:]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557) [quartz-all-2.1.7.jar:]
Caused by: java.lang.NullPointerException
at hms.general.SendSMSJob.execute(SendSMSJob.java:43) [classes:]
at org.quartz.core.JobRunShell.run(JobRunShell.java:213) [quartz-all-2.1.7.jar:]
... 1 more
The following code is for scheduler
package hms.general;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
#ManagedBean(eager=true)
#ApplicationScoped
public class ScheduleBean {
public ScheduleBean() {
try{
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
JobDetail job = org.quartz.JobBuilder.newJob(SendSMSJob.class).withIdentity("job1","group1").build();
Trigger trigger = org.quartz.TriggerBuilder.newTrigger().withIdentity("trigger1","group1").startNow().withSchedule(org.quartz.SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(1).repeatForever()).build();
scheduler.scheduleJob(job,trigger);
}
catch(SchedulerException se){
se.getMessage();
}
}
}
Code for JobScheduler
import hms.db.PatientRegEMRemote;
import hms.db.Prescription;
import hms.db.PrescriptionEMRemote;
import java.util.List;
import javax.ejb.EJB;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class SendSMSJob implements Job {
#EJB(mappedName = "java:global/Hms-Main/PatientRegEM!hms.db.PatientRegEMRemote")
public PatientRegEMRemote patreg_r;
#EJB(mappedName = "java:global/Hms-Main/PrescriptionEM!hms.db.PrescriptionEMRemote")
private PrescriptionEMRemote prescription_r;
public static void main(String ar[]){
SendSMSJob hj = new SendSMSJob();
try {
hj.execute(null);
} catch (JobExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println(arg0.getJobDetail());
System.out.println("I am in execute method....");
// TODO Auto-generated method stub
System.out.println("Im inside execute method");
String s="select p from prescription p where p.smsflag=1";
System.out.println(s);
List<Prescription> pre=prescription_r.retrieveAll(s);
System.out.println(".........");
for (Prescription p : pre) {
System.out.println(p.getAppointno());
}
}
}

List pre=prescription_r.retrieveAll(s);
Seems like prescription_r is appearing null here. Not sure. Just check with breakpoint.

Related

Null pointer exception when jenkins version is set to 2.X

I have a plugin with jenkins version set to 1.580.3.And when I upgrade the jenkins version to 1.642.3<=version , it is throwing a null pointer exception.Below is the stacktrace
java.lang.NullPointerException
at hudson.model.Label.hashCode(Label.java:528)
at java.util.HashMap.hash(HashMap.java:338)
at java.util.HashMap.put(HashMap.java:611)
at java.util.HashSet.add(HashSet.java:219)
at java.util.Collections.addAll(Collections.java:5401)
at com.google.common.collect.Sets.newHashSet(Sets.java:183)
at com.ericsson.oss.axis.ATest.setUp(ATest.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
below is my code
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.jenkins.plugins.nodelabelparameter.LabelParameterValue;
import org.mockito.Answers;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.XXXXX.JenkinsUtils;(internal)
import com.google.common.collect.Sets;
import hudson.model.AbstractBuild;
import hudson.model.Label;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import jenkins.model.Jenkins;
#RunWith(PowerMockRunner.class)
#PrepareForTest( JenkinsUtils.class)
public class A{
#Mock
private Label label;
#Mock
private Jenkins jenkins;
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
private AbstractBuild build;
#Before
public void setUp() {
PowerMockito.mockStatic(JenkinsUtils.class);
try {
doReturn(Sets.newHashSet(label)).when(jenkins).getLabels();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(NodeLabelParameterUtils.class )
public class B{
private BaselineDefinedMessageDispatcher unit;
private BuildData buildData = new BuildData();
private MyBuildDetails myBuildDetails;
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
private AbstractBuild build;
#Mock
private BuildLogger buildLogger;
#Mock
private Label label;
#Mock
private Computer computer;
#Mock
private PretendSlave node;
#Mock
private FreeStyleProject project;
#Mock
private Jenkins jenkins;
#Mock
private EnvironmentVariableResolver envVarsResolver;
#Before
public void setUp() throws IOException, InterruptedException, Descriptor.FormException {
unit = spy(new BaselineDefinedMessageDispatcher(null, null));
unit.setBuildLogger(mock(BuildLogger.class));
MyBuildDetails = mock(MyBuildDetails.class);
doReturn("expectedSlaveHost").when(unit).getHostNameFromSlave(any(Node.class));
doReturn(project).when(build).getProject();
doReturn(Sets.<Node>newHashSet(node)).when(label).getNodes();
doReturn(node).when(build).getBuiltOn();
doReturn(jenkins).when(unit).getJenkinsInstance();
doReturn(Sets.newHashSet(label)).when(jenkins).getLabels();
PowerMockito.mockStatic(A.class);
when(envVarsResolver.processString(anyString())).thenAnswer(new Answer<String>() {
#Override
public String answer(InvocationOnMock invocationOnMock) throws Throwable {
return (String) invocationOnMock.getArguments()[0];
}
});
}
The following dependencies are being used
powermock-api-mockito - 1.6.3
mockito-core - 1.9.5
junit - 4.11
java - 1.8
jenkins.version - 1.642.3
I get the error exactly at doReturn(Sets.newHashSet(label)).when(jenkins).getLabels(); in class A.
This is a maven project and when jenkins version is set to 1.580.3 mvn clean install is success but when it is version>=1.642.3 it is failing.
My aim is to upgrade jenkins verison to 2.X.I went through manyworkarounds in stackoverflow but nothing worked
Any help is appreciated
Edit:
Looks like my orignal answer was just incorrect.
The NPE comes from the fact that the abstract Label class has a constructor parameter called name. This parameter is used to calculate the hashcode of the label.
If you mock it this name is null and you get the NPE.
The question now is do you need to create a mock of this or can you actually use a real instance? In the exmaple below I just used one of the implementations of that class LabelAtom. If a mock is required because you need to define some behaviour on the object that you can not get otherwise, you probably have to use a spy.
(Tested with org.jenkins-ci.main:jenkins-core:2.85)
import static org.mockito.Mockito.doReturn;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import com.google.common.collect.Sets;
import hudson.model.Label;
import hudson.model.labels.LabelAtom;
import jenkins.model.Jenkins;
#RunWith(PowerMockRunner.class)
public class Test {
#Mock
private Jenkins jenkins;
private Label label;
#Before
public void setUp() {
Assert.assertNotNull(jenkins);
label = new LabelAtom("someName");
// or if a mock is required
//label = Mockito.spy(new LabelAtom("someName"));
doReturn(Sets.newHashSet(label)).when(jenkins).getLabels();
}
#Test
public void test() {
}
}
Regarding the WithOrWithoutExpectedArguments I was not able to reproduce that one.

AccessDeniedException Spring Security Can Not Catched By AbstractRequestCycleListener wicket

I have custom class from AbstractRequestCycleListener:
package com.rudiwijaya.rcommerce.security;
import java.util.List;
import org.apache.wicket.Session;
import org.apache.wicket.core.request.handler.PageProvider;
import org.apache.wicket.core.request.handler.RenderPageRequestHandler;
import org.apache.wicket.core.request.handler.RenderPageRequestHandler.RedirectPolicy;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.cycle.AbstractRequestCycleListener;
import org.apache.wicket.request.cycle.RequestCycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.rudiwijaya.rcommerce.WicketSession;
import com.rudiwijaya.rcommerce.pages.AccessDeniedPage;
public class NotAuthorizedRequestCycleListener extends AbstractRequestCycleListener {
private static final Logger log = LoggerFactory.getLogger(NotAuthorizedRequestCycleListener.class);
#Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
// Since our actual exception is wrapped, we need to find based on the chain
final List<Throwable> chain = Throwables.getCausalChain(ex);
final AccessDeniedException notAuthorizedException = Iterables.getFirst(
Iterables.filter(chain, AccessDeniedException.class), null);
if (notAuthorizedException != null) {
final Url url = cycle.getRequest().getClientUrl();
log.debug("Got exception " + notAuthorizedException.getClass().getName() + " on " + url, ex);
final WicketSession wSession = (WicketSession) Session.get();
wSession.error("Anda tidak memilik akses.");
wSession.dirty();
return new RenderPageRequestHandler(new PageProvider(AccessDeniedPage.class), RedirectPolicy.NEVER_REDIRECT);
} else {
return super.onException(cycle, ex);
}
}
}
In init() method from AuthenticatedWebApplication, I added:
getRequestCycleListeners().add(new NotAuthorizedRequestCycleListener());
How can I to catch the AccessDeniedException spring security in wicket's AbstractRequestCycleListener?
My point is showing custom access denied page with keep the url, in Wicket command like:
return new RenderPageRequestHandler(new PageProvider(AccessDeniedPage.class), RedirectPolicy.NEVER_REDIRECT);
Most probably Spring Security filter is executed before WicketFilter, so Wicket doesn't have a chance to do anything.
You may need custom AuthenticationEntryPoint to handle such failures via Spring Security APIs.

Univocity Parsers - The code doesn't run: Exception in thread "main" java.lang.NullPointerException

I want to parse .csv files and I'm following the Univocity Parsers tutorial, and have added their jar file to the dependencies here.
A null pointer exception occurs.
I would like to get Univocity Parsers working so I can see how good it is, here is the code I am running in IntelliJ, any help would be greatly appreciated, thanks!
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.IllegalStateException;
import java.lang.String;
import java.util.List;
public class UnivocityParsers {
public Reader getReader(String relativePath) {
try {
return new InputStreamReader(this.getClass().getResourceAsStream(relativePath), "Windows-1252");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Unable to read input", e);
}
}
public void parseCSV(){
CsvParserSettings settings = new CsvParserSettings();
//the file used in the example uses '\n' as the line separator sequence.
//the line separator sequence is defined here to ensure systems such as MacOS and Windows
//are able to process this file correctly (MacOS uses '\r'; and Windows uses '\r\n').
settings.getFormat().setLineSeparator("\r");
// creates a CSV parser
CsvParser parser = new CsvParser(settings);
// parses all rows in one go.
List<String[]> allRows = parser.parseAll(getReader("prodlist.csv"));
}
public static void main(String arg[]) {
UnivocityParsers univocityParsers = new UnivocityParsers();
univocityParsers.parseCSV();
}
}
Stack trace:
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:97)
at UnivocityParsers.getReader(UnivocityParsers.java:15)
at UnivocityParsers.parseCSV(UnivocityParsers.java:33)
at UnivocityParsers.main(UnivocityParsers.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 1
The InputStreamReader is not finding your "prodlist.csv" file. I suspect it should be "/prodlist.csv" as it seems you are getting this file from your resources folder.
In any case, you can use the full path to your file just to make sure. Add this method:
public Reader getFileReader(String absolutePath) {
return new InputStreamReader(new FileInputStream(new File(absolutePath)), "UTF-8");
}
Then call parser.parseAll with:
List<String[]> allRows = parser.parseAll(getFileReader("c:/path/to/prodlist.csv"));

using quartz with out the quartz plugin in grails

i'm trying to use quartz to schedule jobs in grails with out using the plugin.
this is the code:
1 - RunMeTask.java
package tt;
public class RunMeTask {
public void printMe() {
System.out.println("Run Me ~");
}
}
2 - resources.groovy (under conf/spring)
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerBean;
import tt.RunMeTask
beans = {
runMeTask(RunMeTask){}
runMeJob(JobDetailFactoryBean) {
targetObject = ref('runMeTask')
targetMethod = "printMe"
}
simpleTrigger(SimpleTriggerBean){
jobDetail = ref('runMeJob')
repeatInterval = "5000"
startpDelay = "1000"
}
schedulerFactoryBean(SchedulerFactoryBean){
jobDetails = [ref('runMeJob')]
triggers = [ref('simpleTrigger')]
}
}
i get the following exception:
Error Fatal error during compilation org.apache.tools.ant.BuildException: java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.SimpleTriggerBean has interface org.quartz.SimpleTrigger as super class (Use --stacktrace to see the full trace)
can anyone help?
ok i figure it out. wasn't that hard when i think about it.the good thing about it its just as simple as you would do it in java and no plugin that may or may not work on grails certain version or any trouble that can caused by using a plugin.
there is 1 change in the code from the question:
RunMeTask.java (this can also be RunMeTask.groovy) must implement runnable and so
it look like this:
package tt;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class RunMeTask implements Runnable {
static Random r = new Random();
public void printMe() throws IOException {
File f = new File("c:\ofer.txt"+r.nextInt());
f.createNewFile();
System.out.println("fff");
}
public void run(){
try {
printMe();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
one funny thing is the println of "fff" occures only 2 times but a new file is created as expected every 5 seconds.
ok so thats it now a new file is created every 5 seconds in your c directory.
no plugin and no hassle. if anyone know why the System.out.println("fff"); occures only 2 times i will be happy to know.
thanks

jena programming error while reading from an input file .rdf.......Please guide me

package sample;
import java.io.InputStream;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.FileManager;
public class ReadRDF extends Object {
static final String fileName = "foaf-ijd.rdf";
public static void main(String[] args) {
Model model = ModelFactory.createDefaultModel();
InputStream in = FileManager.get().open(fileName);
if (in == null) {
throw new IllegalArgumentException("File: " + fileName
+ " not found");
}
model.read(in, "");
model.write(System.out);
}
}
Errors getting populated
Exception in thread "main" java.lang.NoSuchMethodError:
org.slf4j.Logger.isTraceEnabled()Z at
com.hp.hpl.jena.util.LocatorFile.open(LocatorFile.java:118) at
com.hp.hpl.jena.util.FileManager.openNoMapOrNull(FileManager.java:527)
at com.hp.hpl.jena.util.FileManager.openNoMap(FileManager.java:510)
at
com.hp.hpl.jena.util.LocationMapper.initFromPath(LocationMapper.java:132)
at com.hp.hpl.jena.util.LocationMapper.get(LocationMapper.java:61)
at com.hp.hpl.jena.util.FileManager.makeGlobal(FileManager.java:116)
at com.hp.hpl.jena.util.FileManager.get(FileManager.java:82) at
sample.ReadRDF.main(ReadRDF.java:17)
This error can apper, if you don't add to CLASSPATH all jar file from /lib dir in Jena ditrib.
Also, if version's slf4j, which you use, an d jena's slf4j is differenf, this error can appear.

Resources