I created a program using threads to read data from file and dispay. Am getting Null pointer exception, first time thread 1 is printing the firstrecord from textfile and second data it removes from file it throws null pointer
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newSingleThreadExecutor();
List<String> tasks = getUsersFromFile("new_users.txt");
DoctorDao dao = new DoctorDao();
for (String data : tasks) {
Future<Boolean> result = es.submit(new DoctorTask(data, dao));
while (result.get()) {
System.out.println("data stored!!!");
}
}
es.shutdown();
System.out.println("task done!!!");
}
public static List<String> getUsersFromFile(String fileName) {
List<String> users = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
String line = null;
while ((line = reader.readLine()) != null) {
users.add(line);
}
} catch (FileNotFoundException ex) {
// Logger.getLogger(TestExecutors.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
// Logger.getLogger(TestExecutors.class.getName()).log(Level.SEVERE, null, ex);
}
return users;
In Callable implemented class
public Boolean call() throws Exception {
Boolean status = false;
System.out.println(Thread.currentThread().getName() + " processing record for : " + doctorRecord);
StringTokenizer tokenizer = new StringTokenizer(this.doctorRecord, ",");
Doctor doc = null;
while (tokenizer.hasMoreTokens()) {
doc = new Doctor();
doc.setEmailAddress(tokenizer.nextToken());
doc.setName(tokenizer.nextToken());
doc.setId(Integer.valueOf(tokenizer.nextToken()));
status = dao.saveUser(doc);
}
return status;
}
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at com.executor.demo.readfile.TestDotorExecutor.main(TestDotorExecutor.java:23)
Caused by: java.lang.NullPointerException
at com.executor.demo.readfile.DoctorDao.saveUser(DoctorDao.java:5)
at com.executor.demo.readfile.DoctorTask.call(DoctorTask.java:28)
at com.executor.demo.readfile.DoctorTask.call(DoctorTask.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
I made a mistake in the code I returned a null value from statiDB class, I didn't intialize List Object, so I modified the code as shown below
This complete code below was missing in above question
In dao class:
public class DoctorDao {
public boolean saveUser(Doctor doc) {
boolean storedStatus = StaticDB.getDoctorList().add(doc);
return storedStatus;
}
}
In DB class
class StaticDB {
static List<Doctor> docList=null;
public static List<Doctor> getDoctorList() {
Doctor doc1 = new Doctor(111,"Shalu","ss#gmail.com");
Doctor doc2 = new Doctor(112,"luke","luke#gmail.com");
docList = new ArrayList<Doctor>(); //This was missing
docList.add(doc1);
docList.add(doc2);
return docList;
}
}
Related
I am converting xml to csv using spring batch and integration. I have a approach that job will start by reading files in from landing dir. while processing it will move files in inprocess dir. on error file will be moved to error dir. on successfully processing/writing file will be moved to output/completed.
After searching a while i got to know that there must be problem with itemreader but it is also returning null. I am not getting where is the problem.
Below is my batch configuration
#Bean
public Job commExportJob(Step parseStep) throws IOException {
return jobs.get("commExportJob")
.incrementer(new RunIdIncrementer())
.flow(parseStep)
.end()
.listener(listener())
.build();
}
#Bean
public Step streamStep() throws IOException {
CommReader itemReader = itemReader(null);
if (itemReader != null) {
return
steps.get("streamStep")
.<Object, Object>chunk(env.getProperty(Const.INPUT_READ_CHUNK_SIZE, Integer.class))
.reader(itemReader)
.processor(itemProcessor())
.writer(itemWriter(null))
.listener(getChunkListener())
.build();
}
return null;
}
#Bean
#StepScope
public ItemWriter<Object> itemWriter(#Value("#{jobParameters['outputFilePath']}") String outputFilePath) {
log.info("CommBatchConfiguration.itemWriter() : " + outputFilePath);
CommItemWriter writer = new CommItemWriter();
return writer;
}
#Bean
#StepScope
public CommReader itemReader(#Value("#{jobParameters['inputFilePath']}") String inputFilePath) {
log.info("CommBatchConfiguration.itemReader() : " + inputFilePath);
CommReader reader = new CommReader(inputFilePath);
// reader.setEncoding(env.getProperty("char.encoding","UTF-8"));
return reader;
}
#Bean
#StepScope
public CommItemProcessor itemProcessor() {
log.info("CommBatchConfiguration.itemProcessor() : Entry");
return new CommItemProcessor(ruleService);
}
CommReader.java
File inputFile = null;
private String jobName;
public CommReader(String inputFilePath) {
inputFile = new File(inputFilePath);
}
#Value("#{stepExecution}")
private StepExecution stepExecution;
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
#Override
public Object read() throws IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
if (inputFile.exists()) {
try {
builder = factory.newDocumentBuilder();
log.info("CommReader.read() :" + inputFile.getAbsolutePath());
Document document = builder.parse(inputFile);
return document;
} catch (ParserConfigurationException | SAXException | TransformerFactoryConfigurationError e) {
log.error("Exception while reading ", e);
}
}
return null;
}
#Override
public void close() throws ItemStreamException {
}
#Override
public void open(ExecutionContext arg0) throws ItemStreamException {
}
#Override
public void update(ExecutionContext arg0) throws ItemStreamException {
}
#Override
public void setResource(Resource arg0) {
}
CommItemProcessor.java
#Autowired
CommExportService ruleService;
public CommItemProcessor(CommExportService ruleService) {
this.ruleService = ruleService;
}
#Override
public Object process(Object bean) throws Exception {
log.info("CommItemProcessor.process() : Item Processor : " + bean);
return bean;
}
CommItemWriter.java
FlatFileItemWriter<byte[]> delegate;
ExecutionContext execContext;
FileOutputStream fileWrite;
File stylesheet;
StreamSource stylesource;
Transformer transformer;
List<List<?>> itemsTotal = null;
int recordCount = 0;
#Autowired
FileUtil fileUtil;
#Value("${input.completed.dir}")
String completedDir;
#Value("${input.inprocess.dir}")
String inprocessDir;
public void update(ExecutionContext arg0) throws ItemStreamException {
this.delegate.update(arg0);
}
public void open(ExecutionContext arg0) throws ItemStreamException {
this.execContext = arg0;
this.delegate.open(arg0);
}
public void close() throws ItemStreamException {
this.delegate.close();
}
#Override
public void write(List<? extends Object> items) throws Exception {
log.info("CommItemWriter.write() : items.size() : " + items.size());
stylesheet = new File("./config/style.xsl");
stylesource = new StreamSource(stylesheet);
String fileName = fileUtil.getFileName();
try {
transformer = TransformerFactory.newInstance().newTransformer(stylesource);
} catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
log.error("Exception while writing",e);
}
for (Object object : items) {
log.info("CommItemWriter.write() : Object : " + object.getClass().getName());
log.info("CommItemWriter.write() : FileName : " + fileName);
Source source = new DOMSource((Document) object);
Result outputTarget = new StreamResult(
new File(fileName));
transformer.transform(source, outputTarget);
}
}
In chunkListener there is nothing much i am doing.
Below is the job listener.
#Override
public void beforeJob(JobExecution jobExecution) {
log.info("JK: CommJobListener.beforeJob()");
}
#Override
public void afterJob(JobExecution jobExecution) {
log.info("JK: CommJobListener.afterJob()");
JobParameters jobParams = jobExecution.getJobParameters();
File inputFile = new File(jobParams.getString("inputFilePath"));
File outputFile = new File(jobParams.getString("outputFilePath"));
try {
if (jobExecution.getStatus().isUnsuccessful()) {
Files.move(inputFile.toPath(), Paths.get(inputErrorDir, inputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
Files.move(outputFile.toPath(), Paths.get(outputErrorDir, outputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
} else {
String inputFileName = inputFile.getName();
Files.move(inputFile.toPath(), Paths.get(inputCompletedDir, inputFileName),
StandardCopyOption.REPLACE_EXISTING);
Files.move(outputFile.toPath(), Paths.get(outputCompletedDir, outputFile.getName()),
StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ioe) {
log.error("IOException occured ",ioe);
}
}
I am also using integration flow.
#Bean
public IntegrationFlow messagesFlow(JobLauncher jobLauncher) {
try {
Map<String, Object> headers = new HashMap<>();
headers.put("jobName", "commExportJob");
return IntegrationFlows
.from(Files.inboundAdapter(new File(env.getProperty(Const.INPUT_LANDING_DIR)))
,
e -> e.poller(Pollers
.fixedDelay(env.getProperty(Const.INPUT_POLLER_DELAY, Integer.class).intValue())
.maxMessagesPerPoll(
env.getProperty(Const.INPUT_MAX_MESSAGES_PER_POLL, Integer.class).intValue())
.taskExecutor(getFileProcessExecutor())))
.handle("moveFile","moveFile")
.enrichHeaders(headers)
.transform(jobTransformer)
.handle(jobLaunchingGw(jobLauncher))
.channel("nullChannel").get();
} catch (Exception e) {
log.error("Exception in Integration flow",e);
}
return null;
}
#Autowired
private Environment env;
#Bean
public MessageHandler jobLaunchingGw(JobLauncher jobLauncher) {
return new JobLaunchingGateway(jobLauncher);
}
#MessagingGateway
public interface IMoveFile {
#Gateway(requestChannel = "moveFileChannel")
Message<File> moveFile(Message<File> inputFileMessage);
}
#Bean(name = "fileProcessExecutor")
public Executor getFileProcessExecutor() {
ThreadPoolTaskExecutor fileProcessExecutor = new ThreadPoolTaskExecutor();
fileProcessExecutor.setCorePoolSize(env.getRequiredProperty(Const.INPUT_EXECUTOR_POOLSIZE, Integer.class));
fileProcessExecutor.setMaxPoolSize(env.getRequiredProperty(Const.INPUT_EXECUTOR_MAXPOOLSIZE, Integer.class));
fileProcessExecutor.setQueueCapacity(env.getRequiredProperty(Const.INPUT_EXECUTOR_QUEUECAPACITY, Integer.class));
fileProcessExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
fileProcessExecutor.initialize();
return fileProcessExecutor;
}
Try to return document itself instead of Object in read method of CommReader.java and then check whether its coming null or not in the writer to stop it.
I am trying to implement a SessionListener which I plan to use for logging active user sessions (name/time) so that I can let manager know who all are available at anytime. However, when I add it, I see sessionCreated message and then I see this JVM error on server console. No java code is executed after it.
HTTP JVM: com.ibm.xsp.webapp.FacesServlet$ExtendedServletException:
java.lang.ExceptionInInitializerError HTTP JVM: Error type not
found:java.lang.ExceptionInInitializerError import
javax.servlet.http.HttpSessionEvent;
Here is my SessionTracker.java:
import com.ibm.xsp.application.ApplicationEx;
import com.ibm.xsp.application.events.SessionListener;
public class SessionTracker implements SessionListener {
public void sessionCreated(ApplicationEx arg0, HttpSessionEvent arg1) {
System.out.println("***session created***");
}
public void sessionDestroyed(ApplicationEx arg0, HttpSessionEvent arg1) {
System.out.println("***session destroyed ***");
}
}
Here is what I see in xpages_exec*.log under IBM_Technical_Support directory.
Context Path: /igdmnext/igdm.nsf Page Name: /Services.xsp
java.lang.ExceptionInInitializerError at
java.lang.J9VMInternals.initialize(J9VMInternals.java:221) at
java.lang.J9VMInternals.newInstanceImpl(Native Method) at
java.lang.Class.newInstance(Class.java:1688) at
com.ibm.xsp.util.ManagedBeanUtil.getBean(ManagedBeanUtil.java:61) at
com.ibm.xsp.extlib.component.rest.CustomService.findBeanInstance(CustomService.java:225)
at
com.ibm.xsp.extlib.component.rest.CustomService$ScriptServiceEngine.renderService(CustomService.java:257)
at
com.ibm.domino.services.HttpServiceEngine.processRequest(HttpServiceEngine.java:170)
at
com.ibm.xsp.extlib.component.rest.UIBaseRestService._processAjaxRequest(UIBaseRestService.java:259)
at
com.ibm.xsp.extlib.component.rest.UIBaseRestService.processAjaxRequest(UIBaseRestService.java:236)
at
com.ibm.xsp.util.AjaxUtilEx.renderAjaxPartialLifecycle(AjaxUtilEx.java:206)
at
com.ibm.xsp.webapp.FacesServletEx.renderAjaxPartial(FacesServletEx.java:249)
at
com.ibm.xsp.webapp.FacesServletEx.serviceAjaxPartialView(FacesServletEx.java:200)
at
com.ibm.xsp.webapp.FacesServletEx.serviceAjaxPartialViewSync(FacesServletEx.java:169)
at
com.ibm.xsp.webapp.FacesServletEx.serviceView(FacesServletEx.java:155)
at com.ibm.xsp.webapp.FacesServlet.service(FacesServlet.java:160) at
com.ibm.xsp.webapp.FacesServletEx.service(FacesServletEx.java:138) at
com.ibm.xsp.webapp.DesignerFacesServlet.service(DesignerFacesServlet.java:103)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule.invokeServlet(ComponentModule.java:576)
at
com.ibm.domino.xsp.module.nsf.NSFComponentModule.invokeServlet(NSFComponentModule.java:1335)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule$AdapterInvoker.invokeServlet(ComponentModule.java:853)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule$ServletInvoker.doService(ComponentModule.java:796)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule.doService(ComponentModule.java:565)
at
com.ibm.domino.xsp.module.nsf.NSFComponentModule.doService(NSFComponentModule.java:1319)
at
com.ibm.domino.xsp.module.nsf.NSFService.doServiceInternal(NSFService.java:662)
at
com.ibm.domino.xsp.module.nsf.NSFService.doService(NSFService.java:482)
at
com.ibm.designer.runtime.domino.adapter.LCDEnvironment.doService(LCDEnvironment.java:357)
at
com.ibm.designer.runtime.domino.adapter.LCDEnvironment.service(LCDEnvironment.java:313)
at
com.ibm.domino.xsp.bridge.http.engine.XspCmdManager.service(XspCmdManager.java:272)
Caused by: java.lang.NullPointerException at
org.openntf.domino.xsp.session.AbstractXPageSessionFactory.wrapSession(AbstractXPageSessionFactory.java:23)
at
org.openntf.domino.xsp.session.XPageSignerSessionFactory.createSession(XPageSignerSessionFactory.java:18)
at org.openntf.domino.utils.Factory.getSession(Factory.java:952) at
com.hcl.igdm.util.EndUserMap.(EndUserMap.java:46) --> this is my custom java class which works if I do not implement SessionTracker above at
java.lang.J9VMInternals.initializeImpl(Native Method) at
java.lang.J9VMInternals.initialize(J9VMInternals.java:199) ... 27
more
** EndUserMap.java **
package com.hcl.igdm.util;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewEntryCollection;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.utils.Factory.SessionType;
import com.hcl.igdm.Activity;
import com.hcl.igdm.Phases;
import com.hcl.igdm.Stages;
import com.ibm.commons.util.StringUtil;
import com.ibm.commons.util.io.json.JsonJavaArray;
import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;
import com.ibm.xsp.extlib.util.ExtLibUtil;
/**
* #author agnihotri.a
*
*/
public class EndUserMap extends CustomServiceBean implements Serializable {
private static final long serialVersionUID = 1L;
private static String requestedType = "";
static Session session = Factory.getSession(SessionType.NATIVE);
static Database db = session.getCurrentDatabase();
static View allView = db.getView("mapAll");
public static void setRequestedType(String requestType) {
requestedType = requestType;
}
public static String getRequestedType() {
return requestedType;
}
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();
response.setHeader("Content-Type", "application/json; charset=UTF-8");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
FacesContext faccon = FacesContext.getCurrentInstance();
/**** read requested type from query string parameters ****/
String reqType = request.getParameter("type");
try {
JsonJavaObject jjo = new JsonJavaObject();
PrintWriter pw = response.getWriter();
if (reqType.equalsIgnoreCase("Map") || "".equalsIgnoreCase(reqType)) {
setRequestedType("Map");
pw.write(getEndUserMap().toString());
} else if (reqType.equalsIgnoreCase("Activity")) {
setRequestedType("Activity");
request.getParameter("ukey");
try {
jjo = getActivity(request.getParameter("ukey"));
// jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (reqType.equalsIgnoreCase("Phase")) {
request.getParameter("ukey");
try {
setRequestedType("Phase");
jjo = getPhase(request.getParameter("ukey"));
jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (reqType.equalsIgnoreCase("Stage")) {
request.getParameter("ukey");
try {
setRequestedType("Stage");
jjo = getStage(request.getParameter("ukey"));
// jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
faccon.responseComplete();
}
public static JsonJavaObject getActivity(String ukey) throws Exception {
Activity activity = new Activity();
activity.load(ukey);
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) activity.getValue("Status"), "Live")) {
jjo.put("error", "You are not authorized to view this document.");
return jjo;
}
jjo.put("title", activity.getValue("Title"));
jjo.put("teaser", activity.getValue("Teaser"));
jjo.put("ukey", activity.getUnid());
jjo.put("overview", activity.getValue("Overview"));
jjo.put("inputs", activity.getValue("Inputs"));
jjo.put("outputs", activity.getValue("Outputs"));
jjo.put("order", activity.getValue("SortOrder"));
jjo.put("artefacts", activity.getArtefacts());
jjo.put("kmlinks", activity.getValue("KMLinks"));
jjo.put("kmenabled", activity.getValue("KMEnabled"));
jjo.put("resources", activity.getResources());
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
if (!mappings.isEmpty()) {
if (mappings.containsKey("Substage")) {
// jjo.put("substage", mappings.get("Substage").get(0));
jjo.put("substage", getStage(mappings.get("Substage").get(0)));
} else if (mappings.containsKey("Stage")) {
// jjo.put("stage", mappings.get("Stage").get(0));
jjo.put("stage", getStage(mappings.get("Stage").get(0)));
}
}
return jjo;
}
public static JsonJavaObject getStage(String ukey) {
Stages stage = new Stages();
stage.load(ukey);
String stageType = (String) stage.getValue("StageType");
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) stage.getValue("Status"), "Live")) {
jjo.put("error", "You are not authorized to view this document.");
return jjo;
}
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
jjo.put("title", stage.getValue("Title"));
jjo.put("ukey", stage.getUnid());
jjo.put("overview", stage.getValue("Overview"));
jjo.put("order", stage.getValue("Row"));
jjo.put("type", stageType);
jjo.put("status", (String) stage.getValue("Status"));
if (!mappings.isEmpty()) {
if (mappings.containsKey("Stream")) {
JsonJavaArray mapStreamJJA = new JsonJavaArray();
for (String key : mappings.get("Stream")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapStreamJJA.add(entryMap);
}
} catch (Exception ex) {
// do nothing
}
}
jjo.put("stream", mapStreamJJA);
} else {
jjo.put("stream", "");
}
/** below mapping check handles substages */
if (mappings.containsKey("Stage") && !StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray mapStreamJJA = new JsonJavaArray();
JsonJavaArray mapPhaseJJA = new JsonJavaArray();
// as this is substage ..we'll get phase from parent stage
for (String key : mappings.get("Stage")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapStreamJJA.add(entryMap);
TreeMap<String, ArrayList<String>> stageMap = Mappings.loadMyMap(key);
if (!stageMap.isEmpty() && stageMap.containsKey("Phase")) {
for (String phase : stageMap.get("Phase")) {
Map<String, Object> entryMapPhase = allView.getFirstEntryByKey(phase).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMapPhase.get("status")) || isAdmin()) {
mapPhaseJJA.add(entryMapPhase);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
jjo.put("stage", mapStreamJJA);
jjo.put("phase", mapPhaseJJA);
}
if (mappings.containsKey("Phase") && StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray mapPhJJA = new JsonJavaArray();
for (String key : mappings.get("Phase")) {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapPhJJA.add(entryMap);
}
}
jjo.put("phase", mapPhJJA);
} else {
if (!jjo.containsKey("phase")) {
jjo.put("phase", "");
}
}
if (mappings.containsKey("Activity")) {
JsonJavaArray actJJA = new JsonJavaArray();
for (String key : mappings.get("Activity")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
actJJA.add(entryMap);
}
} catch (Exception ex) {
}
}
jjo.put("child", "Activities");
jjo.put("activities", actJJA);
} else if (mappings.containsKey("Substage") && StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray ssJJA = new JsonJavaArray();
for (String key : mappings.get("Substage")) {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
ssJJA.add(entryMap);
}
}
jjo.put("child", "Substages");
jjo.put("substages", ssJJA);
}
}
return jjo;
}
public static JsonJavaObject getPhase(String ukey) {
Phases phase = new Phases();
phase.load(ukey);
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) phase.getValue("Status"), "Live")) {
return null;
}
jjo.put("title", phase.getValue("Title"));
jjo.put("ukey", phase.getUnid());
jjo.put("status", phase.getValue("Status"));
jjo.put("overview", phase.getValue("Overview"));
jjo.put("order", phase.getValue("SortOrder"));
try {
jjo.put("artefacts", phase.getArtefacts());
} catch (Exception e) {
jjo.put("artefacts", null);
e.printStackTrace();
}
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
if (!mappings.isEmpty() && mappings.containsKey("Stage")) {
JsonJavaArray jja = new JsonJavaArray();
for (String key : mappings.get("Stage")) {
ViewEntry stage = allView.getFirstEntryByKey(key);
if (null != stage) {
if (isAdmin() || "Live".equalsIgnoreCase((String) stage.getColumnValue("status"))) {
Map<String, Object> stg = stage.getColumnValuesMap();
TreeMap<String, ArrayList<String>> stgMap = Mappings.loadMyMap(key);
if (!stgMap.isEmpty() && stgMap.containsKey("Stream")) {
JsonJavaArray stgStreamArr = new JsonJavaArray();
for (String stream : stgMap.get("Stream")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(stream).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
stgStreamArr.add(entryMap);
}
} catch (Exception ex) {
}
}
stg.put("stream", stgStreamArr);
}
jja.add(stg);
}
}
}
jjo.put("stages", jja);
}
return jjo;
}
public static JsonJavaObject getEndUserMap() {
setRequestedType("Map");
JsonJavaObject endUserMap = new JsonJavaObject();
try {
ArrayList<String> docTypes = new ArrayList<String>();
docTypes.add("Phase");
docTypes.add("Stream");
for (String dtype : docTypes) {
View view = db.getView("map" + dtype);
JsonJavaArray jja = new JsonJavaArray();
ViewEntryCollection vec;
if (isAdmin()) {
vec = view.getAllEntries();
} else {
vec = view.getAllEntriesByKey("Live");
}
for (ViewEntry ve : vec) {
jja.add(ve.getColumnValuesMap());
}
endUserMap.put(dtype, jja);
}
} catch (Exception e) {
e.printStackTrace();
}
return endUserMap;
}
#SuppressWarnings("unchecked")
public static boolean isAdmin() {
List<String> roleList = ExtLibUtil.getXspContext().getUser().getRoles();
if (!roleList.isEmpty() && roleList.contains("[admin]")) {
return true;
} else {
return false;
}
}
}
Caused by: java.lang.NullPointerException at org.openntf.domino.xsp.session.AbstractXPageSessionFactory.wrapSession(AbstractXPageSessionFactory.java:23) at org.openntf.domino.xsp.session.XPageSignerSessionFactory.createSession(XPageSignerSessionFactory.java:18) at org.openntf.domino.utils.Factory.getSession(Factory.java:952) at
It seems to be hitting an error getting the signer session.
This may be a timing issue, caused by it running in a different ClassLoader, before the ODA Factory has initialised the factory's sessions. I'm not sure how to confirm that, but if your error is hitting the logs before the XOTS logging at server startup, that would almost certainly be the case.
Alternatively, it may be specific to not finding the signer. I've tended to use Factory.getSession(SessionType.NATIVE) rather than a signer session. That runs under server's identity, which should be high enough and avoids the issue of multiple signers etc.
I'm trying to implement a multi-thread logic to send hsql request at the same time and at the end of all threads to get one list with all the results.
My thread class is the following:
public class QueryWorker implements Runnable {
private static Query query;
private List result;
private Exception exception;
private volatile boolean flag = false;
public QueryWorker(Query query) {
this.query = query;
}
public void run() {
try {
// System.out.println(method+" Start!!!");
this.result = invokeMethod(this.query);
this.flag = true;
// System.out.println(method+" finished!!!");
} catch (Exception e) {
this.exception = e;
}
}
public boolean isDaemon() {
return false;
}
public void release() {
}
private static List invokeMethod(Query query) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
HibernateException {
List result = query.list();
return result;
}
public List getResult() {
while (!flag) {
System.out.println("blocked on the result");
this.run();
}
return result;
}
public void setResult(List result) {
this.result = result;
}
public Exception getException() {
return this.exception;
}
}
Next I just add the querys to the ExecutorService.
...
ExecutorService executor = Executors.newFixedThreadPool(2);
Runnable worker1 = new QueryWorker(q);
executor.execute(worker1);
...
Runnable worker2 = new QueryWorker(q);
executor.execute(worker2);
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
while (!executor.isTerminated()) {
}
list = ((QueryWorker) worker1).getResult();
List list2 = ((QueryWorker) worker2).getResult();
list.addAll(list2);
} catch (InterruptedException e) {
// send error somewhere
}
The problem is that the program ends before I can get the result of both lists. I also looked at how to use ThreadPoolExecutor but I use java 1.4 so I can not aford the luxury of generic in order to use this class.
I'm using log4net and logging exceptions. but i want to log current object on exception time but i couldn't.
I created exception and add object to exception's data property then log exception by log4net. log4net's exceptions message doesn't contain my object.
my code such as;
try
{
Exception exp = new Exception("critical error");
exp.Data.Add("Eror Object", viewModel);
throw exp;
}
catch (Exception exp)
{
_logManager.Error(exp);
}
my viewModel object;
[Serializable]
public class CartTransferViewModel
{
public CartTransferViewModel()
{
Model = new ModelObject();
}
public ModelObject Model { get; set; }
public string InformatinMessage { get; set; }
public bool? IsActive { get; set; }
}
And my Model object serializable too. but log4Net's exception message like this;
System.Exception: critical error
at FooProject.FooClass.FooMethod() in d:\FooProject\FooClass.cs:line 200
I'm remove serializable attribute then re run my application, error code did change to;
System.ArgumentException: Argument passed in is not serializable.
Parameter name: value
at System.Collections.ListDictionaryInternal.Add(Object key, Object value)
at FooProject.FooClass.FooMethod() in d:\FooProject\FooClass.cs:line 200
How to log my custom exception with my objects?
Ok ,if i got your question. i do the something similar . i use logger to write the exception . But i use Exception.Data property.
here is the example , example contains
1) Info class , which needs to be written
2) Sample class with method , write infoclass when exception happens
3) Utility class which formats the exception
[Serializable]
public class FlatFileItem
{
ArrayList errorlist = new ArrayList();
public FlatFileItem()
{
if (errorlist == null) { errorlist = new ArrayList(); }
}
//Name of the file
public string FileName { get; set; }
public override string ToString()
{
return string.Format(#"FlatFileItem (Unzip FTPLineItem) => FileName:{0}", this.FileName);
}
}
public class someclass {
public void somemethod(){
try{
// throw exception here
} catch (Exception ex)
{
ex.Data["flatfile"] = Convert.ToString(flatfile); //Using data property
flatfile.HasErrors = true; //not there in above example
flatfile.Parent.AddErrorInfo(ex); //not there in above example
logger.Error(String.Format(ex.Message)); //not there in above example
throw ( new Exception ("yourmsg",ex)); //if you want to do this
}
}
}
//Now i use this utility method to write out everything at very top level exception
public class ExceptionInfoUtil
{
public static string GetAllExceptionInfo(Exception ex)
{
StringBuilder sbexception = new StringBuilder();
int i = 1;
sbexception.Append(GetExceptionInfo(ex, i));
while (ex.InnerException != null)
{
i++;
ex = ex.InnerException;
sbexception.Append(GetExceptionInfo(ex, i));
}
return sbexception.ToString();
}
private static string GetExceptionInfo(Exception ex, int count)
{
StringBuilder sbexception = new StringBuilder();
sbexception.AppendLine(string.Format(""));
sbexception.AppendLine(string.Format(""));
sbexception.AppendLine(string.Format("************************************************"));
sbexception.AppendLine(string.Format("************************************************"));
sbexception.AppendLine(string.Format(" Inner Exception : No.{0} ", count));
sbexception.AppendLine(string.Format("************************************************"));
sbexception.AppendLine(string.Format("=================================================="));
sbexception.AppendLine(string.Format(" Error Message : {0} ", ex.Message));
sbexception.AppendLine(string.Format("=================================================="));
#region Mine Thru data dictionary
try
{
sbexception.AppendLine(string.Format("=================================================="));
sbexception.AppendLine(string.Format(" Data parameters Count at Source :{0}", ex.Data.Count));
sbexception.AppendLine(string.Format("=================================================="));
string skey = string.Empty;
foreach (object key in ex.Data.Keys)
{
try
{
if (key != null)
{
skey = Convert.ToString(key);
sbexception.AppendLine(string.Format(" Key :{0} , Value:{1}", skey, Convert.ToString(ex.Data[key])));
}
else
{
sbexception.AppendLine(string.Format(" Key is null"));
}
}
catch (Exception e1)
{
sbexception.AppendLine(string.Format("** Exception occurred when writting log *** [{0}] ", e1.Message));
}
}
}
catch (Exception ex1)
{
sbexception.AppendLine(string.Format("** Exception occurred when writting log *** [{0}] ", ex1.Message));
}
#endregion
sbexception.AppendLine(string.Format("=================================================="));
sbexception.AppendLine(string.Format(" Source : {0} ", ex.Source));
sbexception.AppendLine(string.Format("=================================================="));
sbexception.AppendLine(string.Format(" StackTrace : {0} ", ex.StackTrace));
sbexception.AppendLine(string.Format("=================================================="));
sbexception.AppendLine(string.Format(" TargetSite : {0} ", ex.TargetSite));
sbexception.AppendLine(string.Format("************************************************"));
sbexception.AppendLine(string.Format(" Finished Writting Exception info :{0} ", count));
sbexception.AppendLine(string.Format("************************************************"));
sbexception.AppendLine(string.Format("************************************************"));
sbexception.AppendLine(string.Format(""));
sbexception.AppendLine(string.Format(""));
return sbexception.ToString();
}
}
I have a webservice on axis2, and in this class a function starts a thread, another function checks if the thread is still running, but when i do a request for the function that checks of the thread is still runnning, i get this error:
org.apache.axis2.AxisFault: Exception occurred while trying to invoke service method isTaskRunning
at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:531)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:375)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:421)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at be.kdg.cosys.thesis.ExecutorStub.isTaskRunning(ExecutorStub.java:487)
at be.kdg.cosys.thesis.AllToPublicScheduler.executeTask(AllToPublicScheduler.java:158)
at be.kdg.cosys.thesis.AllToPublicScheduler.incomingApplication(AllToPublicScheduler.java:106)
at be.kdg.cosys.thesis.ParserToScheduler.run(ParserToScheduler.java:111)
at java.lang.Thread.run(Unknown Source)
Here's is the webservice class:
public class Executor {
private Task task = null;
private long startTime = 0;
private long runTime = 0;
private Thread taskThread=null;
public void execute(byte[] object){
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new ByteArrayInputStream(object));
task = (Task) in.readObject();
in.close();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runTime = task.getRunTime();
startTime = System.currentTimeMillis();
taskThread=new Thread(task);
taskThread.start();
}
public long timeToFinish()
{
return runTime-(System.currentTimeMillis()-startTime);
}
public boolean isTaskRunning()
{
return taskThread.isAlive();
}
public byte[] getTask()
{
byte[] ser=null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(task);
ser = bos.toByteArray();
out.close();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ser;
}
}
On the server of the webservice i get a nullpointerexeception (log of catalina)
Can anyone help me?
Yorick
Yes you will get a Null pointer exception - Because the Web-service method would not be called on the Same class instance which started the Thread. Since the variable taskThread will be null , and in the method isTaskRunning() calls a method on a null object, it causes a NullpointerException
Ideally , if you need to poll a Thread using web-service , you should use an intimidatory media which states the Status of Thread. intimidatory can be a Database Table which stores the Thread Status