0 Replies - 376 Views - Last Post: 21 December 2018 - 01:08 AM

#1 Totte   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 70
  • Joined: 18-January 16

EJB - Injecting Singleton into Callable class

Posted 21 December 2018 - 01:08 AM

Hello! In CallableBackgroundTask I try to @Inject TaskManagerServiceBean but it always returns null. I am told this is because I create new CallableBackgroundTask objects using the new keyword. Issue is, I dont know how to solve it in another way. How could I make a new CallableBackgroundTask without using the new keyword, or how can I inject TaskManagerServiceBean in the CallableBackgroundTask in an alternative way to make this work. Thanks:

@POST
@Path("newTask")
@Produces(MediaType.TEXT_HTML)
public void newTask() throws ExecutionException, InterruptedException {
	try {
		// Add futures to list
		List<CallableBackgroundTask> futureList = new ArrayList<CallableBackgroundTask>();
		for (int i = 0; i < 10; i++) {
			String taskid = UUID.randomUUID().toString();
			CallableBackgroundTask task = new CallableBackgroundTask(taskid); // Object creation
			futureList.add(task);
		}

		// Start!
		System.out.println("Start");

		// Invoke all futures
		List<Future<Task>> futures = managedExecutorService.invokeAll(futureList);
		
		// Foreach all futures and get them
		for (Future<Task> future : futures) {
			try {
				System.out.println("future: call =" + future.get());
			} catch (Exception ex) {
				System.out.println("Exception 1: " + ex.getMessage());
			}
		}
		
		// Completed!
		System.out.println("Completed");
		
	} catch (InterruptedException e2) {
		System.out.println("InterruptedException: " + e2.getMessage());
	}
}



CallableBackgroundTask.java:
public class CallableBackgroundTask implements Callable<Task> {

    @Inject
    TaskManagerServiceBean ts;
        
    private final String taskid;
 
    public CallableBackgroundTask(String taskid) {
        this.taskid = taskid;
    }
    
    @Override
    public Task call() throws Exception {
        Task task = null;
        try {
            System.out.println("Running in thread " + Thread.currentThread().getName());
            LocalDateTime time = LocalDateTime.now();
            task = new Task(taskid, TaskState.IN_PROGRESS, time, null);

            System.out.println("TaskId in run is: " + taskid);
            ts.addTask(taskid, task); // Fails because ts is null

            System.out.println("Task " + taskid + " completed");
            ts.markComplete(taskid); // Fails because ts is null
        } catch (Exception ex1) {
            System.out.println("Task " + taskid + " failed... [message: " + ex1.getMessage() + "]");
            ts.markFailed(taskid); // Fails because ts is null
        }
        
        return task;
    }
}



TaskManagerServiceBean.java:
/** Removed imports to shorten code */
 
@Singleton
public class TaskManagerServiceBean {
     
    @PersistenceUnit(name = "example")
    EntityManagerFactory emf;
         
    private final Map<String, Task> idToTaskMapping = new ConcurrentHashMap<>();
     
    public void persist(Task entity) {
        System.out.println("Persisting entity taskId: " + entity.getTaskId()); 
        EntityManager em = emf.createEntityManager();
        em.persist(entity);
        em.close();
    }
     
    public void addTask(String taskId, Task task) {
        try {
            System.out.println("addTask taskid: " + taskId); // Never triggered
            persist(task); // Add to database
            idToTaskMapping.put(taskId, task); // Add to map
            new Log(LogType.ADD_TASK); // Make static later
        } catch (Exception ex) {
            System.out.print("Something went wrong persisting! " + ex);
        }
    }  
     
    public void markComplete(String taskId) {
        try {
            Task task = idToTaskMapping.get(taskId);
            LocalDateTime time = LocalDateTime.now();
            task.setEnd(time);
            task.setState(TaskState.COMPLETED);
            merge(task);
        } catch (Exception ex) {
            System.out.print("Something went wrong merging! " + ex);
        } 
    }
     
    public void markFailed(String taskId) {
        try {
            Task task = idToTaskMapping.get(taskId);
            LocalDateTime time = LocalDateTime.now();
            task.setEnd(time);
            task.setState(TaskState.FAILED);
            merge(task);
        } catch (Exception ex) {
            System.out.print("Something went wrong merging! " + ex);
        } 
    }
     
}


Thanks for help!

Is This A Good Question/Topic? 0
  • +

Page 1 of 1