2017-09-19 1 views
0

Je suis en train de mettre en place un module pour prendre la capture d'écran de l'utilisateur connecté toutes les 3 minutes.Le travail à quartz ne redémarre pas dans Java Web

Ce module fonctionne très bien

Mais le problème que je suis confronté est que chaque fois que je me suis connecté à l'utilisateur le travail commence comme elle a l'intention de le faire, mais sur la fermeture de session, j'arrête le planificateur. Mais maintenant, la prochaine fois que j'essaie de me reconnecter, le planificateur a été initialisé mais le travail ne démarre pas. Je dois redéployer le projet pour la prochaine fois.

Voici ma classe LoginBean.java d'où je commence le travail.

package com.viremp.beans; 

import java.awt.AWTException; 
import java.io.IOException; 
import java.io.Serializable; 
import java.sql.SQLException; 
import java.util.Map; 

import javax.annotation.PostConstruct; 
import javax.faces.bean.ManagedBean; 
import javax.faces.bean.SessionScoped; 
import javax.faces.context.ExternalContext; 
import javax.faces.context.FacesContext; 
import javax.servlet.http.HttpServletRequest; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

import com.viremp.component.HandleHobs; 

@ManagedBean 
@SessionScoped 
public class LoginBean implements Serializable { 
    /** 
    * 
    */ 
    private static final long serialVersionUID = -8650636789236091591L; 
private static Logger LOGGER = LoggerFactory.getLogger(LoginBean.class); 

private String username; 

private String password; 

private String error; 

private boolean visible = false; 

private HandleHobs handleHobs; 

public String getUsername() { 
    return username; 
} 

public void setUsername(String username) { 
    this.username = username; 
} 

public String getPassword() { 
    return password; 
} 

public void setPassword(String password) { 
    this.password = password; 
} 

public String getError() { 
    return error; 
} 

public void setError(String error) { 
    this.error = error; 
} 

public boolean isVisible() { 
    return visible; 
} 

public void setVisible(boolean visible) { 
    this.visible = visible; 
} 

/* 
* public LoginBean() { try { if (handleHobs != null && 
* !handleHobs.isJobStoredScreenShotIsStarted()) { handleHobs = new 
* HandleHobs(); } } catch (Exception e) { LOGGER.error("error init job", e); } 
* 
* } 
*/ 

@PostConstruct 
public void init() { 
    try { 
     if (handleHobs == null || !handleHobs.isJobStoredScreenShotIsStarted()) { 
      handleHobs = new HandleHobs(); 
     } 
    } catch (Exception e) { 
     LOGGER.error("error init job", e); 
    } 

} 

public void login() throws ClassNotFoundException, SQLException, IOException, AWTException { 
    // String un = "a"; 
    // String pw = "b"; 
    FacesContext context = FacesContext.getCurrentInstance(); 
    ExternalContext externalContext = context.getExternalContext(); 
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); 
    // Login login = new Login(); 
    // boolean isLoggedIn = login.LoginUser(username, password); 
    try { 
     request.login(username, password); 

     handleHobs.startJobStoredScreenShot(username); 
     externalContext 
       .redirect(externalContext.getRequestContextPath() + "/faces/Success.xhtml?faces-redirect=true"); 
    } catch (Exception e) { 
     FacesContext fc = FacesContext.getCurrentInstance(); 
     this.error = getErrorParam(fc); 

     setVisible(true); 
     System.out.println("not equal.. " + error); 
     e.printStackTrace(); 
    } 

    /* 
    * 
    * if (isLoggedIn) { System.out.println("equal"); externalContext 
    * .redirect(externalContext.getRequestContextPath() + 
    * "/faces/Success.xhtml?faces-redirect=true"); } else { 
    * 
    * FacesContext fc = FacesContext.getCurrentInstance(); this.error = 
    * getErrorParam(fc); 
    * 
    * setVisible(true); System.out.println("not equal.. " + error); 
    * 
    * } 
    */ 
} 

public String getErrorParam(FacesContext fc) { 

    Map<String, String> params = fc.getExternalContext().getRequestParameterMap(); 
    return params.get("error1"); 

} 
public logout(){ 
     handleHobs.shutdownJobStoredScreenShot(); 
     ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); 
    externalContext.invalidateSession(); 
    externalContext.redirect(externalContext.getRequestContextPath() + "/faces/login.xhtml?faces-redirect=true"); 
} 

Et voici ma classe HandleHobs.java qui est pour le traitement travail, [désolé pour le mauvais nom de la classe, il devrait être HandleJobs.java]

package com.viremp.component; 

import static org.quartz.JobBuilder.newJob; 
import static org.quartz.SimpleScheduleBuilder.simpleSchedule; 
import static org.quartz.TriggerBuilder.newTrigger; 

import org.quartz.JobDetail; 
import org.quartz.Scheduler; 
import org.quartz.Trigger; 
import org.quartz.impl.StdSchedulerFactory; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

public class HandleHobs { 

private static Logger LOGGER = LoggerFactory.getLogger(HandleHobs.class); 

private static JobDetail job; 

private static Scheduler scheduler; 
String email; 

public HandleHobs(String email) { 
    this.email = email; 
} 

private static Trigger trigger; 

{ 
    try { 

     if (job == null && scheduler == null && trigger == null) { 
      LOGGER.info("initializing job"); 

      job = (JobDetail) newJob(JobStoredScreenShot.class).withIdentity("job1", "group1").build(); 

      trigger = newTrigger().withIdentity("trigger1", "group1").startNow() 
        .withSchedule(simpleSchedule().withIntervalInSeconds(5).repeatForever()).build(); 

      scheduler = StdSchedulerFactory.getDefaultScheduler(); 
      scheduler.scheduleJob(job, trigger); 
      LOGGER.info("init successsful"); 
     } 
    } catch (Exception e) { 
     LOGGER.error("fail to init variables for job", e); 
    } 
} 

public HandleHobs() { 

} 

public void startJobStoredScreenShot(String email) { 
    try { 
     this.email = email; 
     JobStoredScreenShot jss = new JobStoredScreenShot(); 
     jss.setEmail(email); 
     if (scheduler != null && !scheduler.isStarted()) { 

      Scheduler scheduler1 = new StdSchedulerFactory().getScheduler(); 
      System.out.println("here..... " + email); 
      scheduler1.getContext().put("email", email); 
      System.out.println("and here..... " + email); 

      scheduler.start(); 
     } 
     LOGGER.info("init successsful"); 
    } catch (Exception e) { 
     LOGGER.error("fail to init job JobStoredScreenShot", e); 
    } 
} 

public void shutdownJobStoredScreenShot() { 
    try { 
     if (scheduler.isStarted()) { 
      scheduler.shutdown(); 
     } 
     LOGGER.info("shutdown successsful"); 
    } catch (Exception e) { 
     LOGGER.error("fail to init job JobStoredScreenShot", e); 
    } 
} 

public boolean isJobStoredScreenShotIsStarted() { 
    boolean isStarted = false; 
    try { 

     if (scheduler != null) { 
      isStarted = true; 
     } 
    } catch (Exception e) { 
     LOGGER.error("fail get isTarted", e); 
    } 
    return isStarted; 
} 

} 

Et voilà ma JobStoredScreenShot.java classe

package com.viremp.component; 

import java.awt.Rectangle; 
import java.awt.Robot; 
import java.awt.Toolkit; 
import java.awt.image.BufferedImage; 
import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.InputStream; 
import java.time.LocalDate; 

import javax.imageio.ImageIO; 

import org.quartz.Job; 
import org.quartz.JobExecutionContext; 
import org.quartz.JobExecutionException; 
import org.quartz.SchedulerContext; 

import com.viremp.core.domain.Screenshot; 
import com.viremp.core.domain.User; 
import com.viremp.core.repository.ScreenshotRepository; 
import com.viremp.core.repository.UserRepository; 
import com.viremp.core.repository.impl.ScreenshotRepositoryImpl; 
import com.viremp.core.repository.impl.UserRepositoryImpl; 

public class JobStoredScreenShot implements Job { 

String email; 
User user = new User(); 

public void setEmail(String Email) { 

    this.email = Email; 
    System.out.println("in job stored class email is: " + email); 

    user.setEmail(email); 
} 

@Override 
public void execute(JobExecutionContext arg0) throws JobExecutionException { 

    try { 

     SchedulerContext schedulerContext = arg0.getScheduler().getContext(); 
     // Below line gets the value from context. 
     // Just get it and cast it in to correct type 
     String email = (String) schedulerContext.get("email"); 
     System.out.println(email); 
     BufferedImage image = new Robot() 
       .createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     ImageIO.write(image, "png", baos); 
     baos.flush(); 
     byte[] imageInByte = baos.toByteArray(); 
     baos.close(); 

     System.out.println("in execute " + user.getEmail() + ".................: " + email); 
     UserRepository userRepository = new UserRepositoryImpl(); 
     user = userRepository.getUserByEmail(email); 
     System.out.println("USER IS: " + user.getUsername() + " id is : " + user.getId()); 
     // byte[] buffer = (((DataBufferByte) 
     // (image).getRaster().getDataBuffer()).getData()); 
     InputStream inputStream = new ByteArrayInputStream(imageInByte); 
     LocalDate localDate = LocalDate.now(); 
     Screenshot screenshot = new Screenshot(); 
     screenshot.setInput(inputStream); 
     screenshot.setScreenshotName(user.getUsername()); 
     screenshot.setUser(new User()); 
     screenshot.getUser().setId(user.getId()); 
     screenshot.setScreenShotTime(java.sql.Date.valueOf(localDate)); 
     System.out.println("id is " + 1l); 
     ScreenshotRepository screenshotRepository = new ScreenshotRepositoryImpl(); 
     screenshotRepository.create(screenshot); 
     ImageIO.write(image, "png", new File("d:\\screenshot.png")); 

     System.out.println("screenshot taken"); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

} 

S'il vous plaît aider, Merci

Répondre

0

Je résolu ce problème émettre en faisant job et schedulernull après avoir arrêté le scheduler.

est ici le code de travail de HandleHobs.java

package com.viremp.component; 

import static org.quartz.JobBuilder.newJob; 
import static org.quartz.SimpleScheduleBuilder.simpleSchedule; 
import static org.quartz.TriggerBuilder.newTrigger; 

import org.quartz.JobDetail; 
import org.quartz.Scheduler; 
import org.quartz.Trigger; 
import org.quartz.impl.StdSchedulerFactory; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

public class HandleHobs { 
private static Logger LOGGER = LoggerFactory.getLogger(HandleHobs.class); 

private static JobDetail job; 

private static Scheduler scheduler; 
String email; 

// SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory(); 

public HandleHobs(String email) { 
    this.email = email; 
} 

private static Trigger trigger; 

{ 
    try { 

     LOGGER.info("initializing job"); 

     job = (JobDetail) newJob(JobStoredScreenShot.class).withIdentity("job1", "group1").build(); 

     trigger = newTrigger().withIdentity("trigger1", "group1").startNow() 
       .withSchedule(simpleSchedule().withIntervalInSeconds(5).repeatForever()).build(); 

     scheduler = StdSchedulerFactory.getDefaultScheduler(); 
     scheduler.scheduleJob(job, trigger); 
     LOGGER.info("init successsful 1"); 
    } catch (Exception e) { 
     LOGGER.error("fail to init variables for job", e); 
    } 
} 

public HandleHobs() { 

} 

public void startJobStoredScreenShot(String email) { 
    try { 
     System.out.println("yaar ma aa gaya hun"); 
     this.email = email; 
     JobStoredScreenShot jss = new JobStoredScreenShot(); 
     jss.setEmail(email); 
     if (scheduler != null && !scheduler.isStarted()) { 

      Scheduler scheduler1 = new StdSchedulerFactory().getScheduler(); 
      System.out.println("here..... " + email); 
      scheduler1.getContext().put("email", email); 
      System.out.println("and here..... " + email); 
      scheduler.start(); 

     } 
     LOGGER.info("init successsful"); 
    } catch (Exception e) { 
     LOGGER.error("fail to init job JobStoredScreenShot", e); 
    } 
} 

public void shutdownJobStoredScreenShot() { 
    try { 
     if (scheduler.isStarted()) { 
      // JobExecutionContext context = new JobExecutionContext(); 
      // JobKey key = context.getJobDetail().getKey(); 
      // String jobId = key.getName(); 
      // System.out.println("```````````````````NAME``````````````````````" + jobId); 
      // flag = true; 

      scheduler.shutdown(); 
      scheduler = null; //i made it null here 
      job = null; // i made it null here 
     } 
     LOGGER.info("shutdown successsful"); 
    } catch (Exception e) { 
     LOGGER.error("fail to init job JobStoredScreenShot", e); 
    } 
} 

public boolean isJobStoredScreenShotIsStarted() { 
    boolean isStarted = false; 
    try { 

     if (scheduler != null) { 
      isStarted = true; 
     } 
    } catch (Exception e) { 
     LOGGER.error("fail get isTarted", e); 
    } 
    return isStarted; 
} 

} 

Et voici ma LoginBean.java où j'entreprends le travail.

package com.viremp.beans; 

import java.awt.AWTException; 
import java.io.IOException; 
import java.io.Serializable; 
import java.sql.SQLException; 
import java.util.Map; 

import javax.annotation.PostConstruct; 
import javax.faces.bean.ManagedBean; 
import javax.faces.bean.SessionScoped; 
import javax.faces.context.ExternalContext; 
import javax.faces.context.FacesContext; 
import javax.servlet.http.HttpServletRequest; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

import com.viremp.component.HandleHobs; 

@ManagedBean 
@SessionScoped 
public class LoginBean implements Serializable { 
    /** 
    * 
    */ 
    private static final long serialVersionUID = -8650636789236091591L; 

private static Logger LOGGER = LoggerFactory.getLogger(LoginBean.class); 

private String username; 

private String password; 

private String error; 

private boolean visible = false; 

private HandleHobs handleHobs; 

public String getUsername() { 
    return username; 
} 

public void setUsername(String username) { 
    this.username = username; 
} 

public String getPassword() { 
    return password; 
} 

public void setPassword(String password) { 
    this.password = password; 
} 

public String getError() { 
    return error; 
} 

public void setError(String error) { 
    this.error = error; 
} 

public boolean isVisible() { 
    return visible; 
} 

public void setVisible(boolean visible) { 
    this.visible = visible; 
} 

/* 
* public LoginBean() { try { if (handleHobs != null && 
* !handleHobs.isJobStoredScreenShotIsStarted()) { handleHobs = new 
* HandleHobs(); } } catch (Exception e) { LOGGER.error("error init job", e); } 
* 
* } 
*/ 

@PostConstruct 
public void init() { 
    try { 

     handleHobs = new HandleHobs(); 

    } catch (Exception e) { 
     LOGGER.error("error init job", e); 
    } 

} 

public void login() throws ClassNotFoundException, SQLException, IOException, AWTException { 
    // String un = "a"; 
    // String pw = "b"; 
    FacesContext context = FacesContext.getCurrentInstance(); 
    ExternalContext externalContext = context.getExternalContext(); 
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); 
    // Login login = new Login(); 
    // boolean isLoggedIn = login.LoginUser(username, password); 
    try { 
     request.login(username, password); 

     handleHobs.startJobStoredScreenShot(username); 
     externalContext 
       .redirect(externalContext.getRequestContextPath() + "/faces/Success.xhtml?faces-redirect=true"); 
    } catch (Exception e) { 
     FacesContext fc = FacesContext.getCurrentInstance(); 
     this.error = getErrorParam(fc); 

     setVisible(true); 
     System.out.println("not equal.. " + error); 
     e.printStackTrace(); 
    } 

    /* 
    * 
    * if (isLoggedIn) { System.out.println("equal"); externalContext 
    * .redirect(externalContext.getRequestContextPath() + 
    * "/faces/Success.xhtml?faces-redirect=true"); } else { 
    * 
    * FacesContext fc = FacesContext.getCurrentInstance(); this.error = 
    * getErrorParam(fc); 
    * 
    * setVisible(true); System.out.println("not equal.. " + error); 
    * 
    * } 
    */ 
} 

public void logout() { 

    System.out.println("in logotu"); 
    handleHobs.shutdownJobStoredScreenShot(); 
    this.handleHobs = null; // here i also made null 
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); 
    externalContext.invalidateSession(); 
    try { 
     externalContext 
       .redirect(externalContext.getRequestContextPath() + "/faces/Login.xhtml?faces-redirect=true"); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

public String getErrorParam(FacesContext fc) { 

    Map<String, String> params = fc.getExternalContext().getRequestParameterMap(); 
    return params.get("error1"); 

} 
} 

En fait, après l'arrêt des travaux a fait arrêter le planificateur, mais n'a pas désempli le travail et planificateur, donc lors de la connexion suivante, le planificateur et travail maintient la valeur de telle sorte que le travail n'a pas commencé encore, donc je viens de faire les valeurs sont nulles à l'arrêt.