Package controller

Source Code of controller.WizardCTRL

package controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import manager.ChoiceManager;
import manager.DiplomeMNG;
import manager.DomainManager;
import manager.FormationManager;
import manager.LevelManager;
import manager.PersonalInfoManager;
import manager.PromoManager;
import manager.SkillsManager;
import manager.UniversityMNG;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;

import util.Generator;
import util.MailSenDer;
import util.WebgiProperties;
import web.FolderForm;
import domain.Choice;
import domain.Diplome;
import domain.Document;
import domain.Folder;
import domain.Formation;
import domain.PersonalInfo;
import domain.Promodetail;
import domain.Skill;
import domain.University;
import domain.logic.InputValidator;

public class WizardCTRL extends AbstractWizardFormController {

  private DomainManager dmmng;

  private FormationManager fmng;

  private DiplomeMNG dmng;

  private UniversityMNG umng;

  private SkillsManager smng;

  private LevelManager lmng;

  private PersonalInfoManager pimng;

  private ChoiceManager cmng;

  private PromoManager pdmng;

  public PromoManager getPdmng() {
    return pdmng;
  }

  public void setPdmng(PromoManager pdmng) {
    this.pdmng = pdmng;
  }

  public ChoiceManager getCmng() {
    return cmng;
  }

  public void setCmng(ChoiceManager cmng) {
    this.cmng = cmng;
  }

  public PersonalInfoManager getPimng() {
    return pimng;
  }

  public void setPimng(PersonalInfoManager pimng) {
    this.pimng = pimng;
  }

  public FormationManager getFmng() {
    return fmng;
  }

  public void setFmng(FormationManager fmng) {
    this.fmng = fmng;
  }

  public LevelManager getLmng() {
    return lmng;
  }

  public void setLmng(LevelManager lmng) {
    this.lmng = lmng;
  }

  public DomainManager getDmmng() {
    return dmmng;
  }

  public void setDmmng(DomainManager dmmng) {
    this.dmmng = dmmng;
  }

  public SkillsManager getSmng() {
    return smng;
  }

  public void setSmng(SkillsManager smng) {
    this.smng = smng;
  }

  public UniversityMNG getUmng() {
    return umng;
  }

  public void setUmng(UniversityMNG umng) {
    this.umng = umng;
  }

  public DiplomeMNG getDmng() {
    return dmng;
  }

  public void setDmng(DiplomeMNG dmng) {
    this.dmng = dmng;
  }

  private WizardCTRL() {
    setCommandName("newFolderForm");
    setPages(new String[] { "add-personalinfo", "add-choices",
        "add-promodetails", "add-skills", "add-resume", "sum-up" });
    // setAllowDirtyBack(false);
    // setAllowDirtyForward(false);
  }

  @Override
  protected void postProcessPage(HttpServletRequest request, Object command,
      Errors errors, int page) throws Exception {

    FolderForm ff = (FolderForm) command;
    Folder folder = ff.getFolder();
    PersonalInfo pi = folder.getPi();
    Promodetail current = folder.getCurrentPromoDetail();
    String delete = request.getParameter("del");
    String action = request.getParameter("action");
    String todelete = request.getParameter("delCV");

    if (page == 0) {

      if (!pi.getEmail().equals("")) {

        if (!pimng.emailIsAvailable(pi.getEmail().trim())) {
          errors.setNestedPath("folder.pi");
          errors.rejectValue("email", "email.invalide",
              "Email existant");
          errors.setNestedPath("");
        }
      }

    } else if (page == 4) {

      if (action != null) {
        // recuperation du multipart
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile fichier = multipartRequest.getFile("data");

        if (fichier.isEmpty()) {
          errors.setNestedPath("folder.pi.cv");
          errors.rejectValue("data", "cv.data.obligatoire",
              "Le document est vide!");
          errors.setNestedPath("");
          return;
        }

        String nomDocument = fichier.getOriginalFilename();

        if (!nomDocument.endsWith(".pdf")) {
          errors.setNestedPath("folder.pi.cv");
          errors.rejectValue("data", "data.invalid",
              "Seuls les documents 'pdf' sont autorises!");
          errors.setNestedPath("");
          return;
        }

        if (nomDocument.equals("")) {
          errors.setNestedPath("folder.pi.cv");
          errors.rejectValue("data", "data.invalid",
              "Specifiez un chemin !");
          errors.setNestedPath("");
          return;
        }

        String chemin = null;
        Document cv = folder.getPi().getCv();

        if (!cv.getName().equals("")) {
          errors.setNestedPath("folder.pi.cv");
          errors.rejectValue("data", "data.invalid",
              "Vous avez deja envoye un cv: supprimez le avant!");
          errors.setNestedPath("");
          return;
        }

        String id = Generator.getRandomId();
        chemin = request.getSession().getServletContext().getRealPath(
            "/")
            + "uploads/CV/" + id + "_" + nomDocument;
        enregistrer(fichier, chemin);
        cv.setName(id + "_" + nomDocument);
      } else if (todelete != null) {
        Document cv = folder.getPi().getCv();
        File f = new File(request.getSession().getServletContext()
            .getRealPath("/")
            + "uploads/CV/" + cv.getName());
        f.delete();
        cv.setName("");
      }

    } else if (page == 2) {

      if (request.getParameter("add") != null && !errors.hasErrors()) {

        if (folder.getNbPromodetails() == 6) {
          errors.setNestedPath("folder");
          errors.rejectValue("promodetails", "promodetails.invalid",
              "Vous avez deja specifie 6 annees d'etude.");
          errors.setNestedPath("");
          return;
        }

        String university = request.getParameter("univs");
        String diplome = request.getParameter("diplomes");
        if (current.isInComplete()) {
          errors.setNestedPath("folder");
          errors.rejectValue("promodetails", "promodetails.invalid",
              "Remplissez tous les champs.");
          errors.setNestedPath("");
          return;
        }

        University u = umng.getUniversity(university);
        Diplome d = dmng.getDiplomes(diplome);

        if (!current.isEmpty()) {
          current.setDiplome(d);
          current.setUniversity(u);
          folder.addPromodetail(current);
        }

      } else if (request.getParameter("adduniv") != null) {
        String nouveau = request.getParameter("newuniv");
        /*
         * It is very difficult to check the validity of variable
         * 'newuniv' Whe just check if 'nouveau' is not empty.
         */
        if (!nouveau.equals("")) {
          University university = new University();
          university.setLabel(nouveau.toUpperCase());
          umng.add(university);
        }
      } else if (request.getParameter("adddegree") != null) {
        String nouveau = request.getParameter("newdegree");
        /*
         * It is very difficult to check the validity of variable
         * 'newdegree' Whe just check if 'nouveau' is not empty.
         */
        if (!nouveau.equals("")) {
          Diplome diplome = new Diplome();
          diplome.setLabel(nouveau.toUpperCase());
          dmng.add(diplome);
        }

      } else if (delete != null) {
        int index = Integer.parseInt(delete);
        ff.getFolder().deletePromodetail(index);
      }
    }

  }

  private void enregistrer(MultipartFile file, String path)
      throws IllegalStateException {
    try {
      file.transferTo(new File(path));
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  protected Object formBackingObject(HttpServletRequest request)
      throws Exception {
    HttpSession session = request.getSession(false);
    if (session == null) {
      request.getSession(true);
    }
    return new FolderForm();
  }

  protected ModelAndView processCancel(HttpServletRequest request,
      HttpServletResponse response, Object obj, BindException be)
      throws Exception {
    return null;
  }

  protected ModelAndView processFinish(HttpServletRequest request,
      HttpServletResponse response, Object command, BindException be)
      throws Exception {
    Folder folder = (Folder) ((FolderForm) command).getFolder();

    /** Reversing the birth date */
    String[] sDate = folder.getPi().getBirthdate().split("-");
    folder.getPi().setBirthdate(sDate[2] + "-" + sDate[1] + "-" + sDate[0]);

    /***/
    // folder.getPi().setCvUrl(folder.getCv().getName());
    /** Initialising password and state */
    folder.getPi().setPassword(Generator.getRandomId());
    folder.getPi().setState(Folder.FOLDER_SAVED);

    /***/
    pimng.savePersonalInfo(folder.getPi());

    for (Iterator iter = folder.getChoices().iterator(); iter.hasNext();) {
      Choice choice = (Choice) iter.next();
      choice.setPersonalInfo_ref(folder.getPi().getId());
    }

    /***/
    cmng.saveChoices(folder.getChoices());

    for (Iterator iter = folder.getPromodetails().iterator(); iter
        .hasNext();) {
      Promodetail p = (Promodetail) iter.next();
      p.setPersonalinfo_ref(folder.getPi().getId());

    }
    /***/
    pdmng.savePromoDetails(folder.getPromodetails());

    for (Iterator iter = folder.getSkills().iterator(); iter.hasNext();) {
      Skill s = (Skill) iter.next();
      s.setPersonalinfo_ref(folder.getPi().getId());
    }
    /***/
    smng.saveSkills(folder.getSkills());

    /** Sends an email to the student */

    String path = request.getSession().getServletContext().getRealPath("/");
    MailSenDer ms = new MailSenDer(path + "mail.properties");
    int res = ms.sendPassword(folder.getPi().getEmail(), folder.getPi()
        .getLastname()
        + " " + folder.getPi().getFirstname(), folder.getPi()
        .getPassword());

    Map model = new HashMap();

    if (res < 0) {
      model.put("attention","Une erreur s'est produite lors de l'envoi de vos identifiants par mail. " +
              "Verifiez que votre adresse email est correcte. Modifiez immediatement cette derniere " +
              "si elle est incorrecte.");
    }

    model.put("folder", folder);

    return new ModelAndView("new-finished", model);
  }

  @SuppressWarnings("unchecked")
  protected Map referenceData(HttpServletRequest request, Object command,
      Errors errors, int page) throws Exception {
    Map model = new HashMap();
    if (page == 0) {

      List sexes = new ArrayList();
      sexes.add("M");
      sexes.add("F");
      List nationalities = new ArrayList();
      nationalities.add("FRANCAIS");
      nationalities.add("ETRANGER");
      model.put("nationalities", nationalities);
      model.put("sexes", sexes);

     
      String path = request.getSession().getServletContext().getRealPath(
      "/")+"candidature.properties";
      System.out.println("Le path wizard "+path);
      boolean closed = isClosed(path);
     
      if(closed)
        model.put("closed",true);
      else
        model.put("closed",false);
     
    } else if (page == 1) {
      List formations = fmng.getAllFormations();
      model.put("formations", formations);

      List formationsWithNone = fmng.getAllFormations();
      Formation f = new Formation();
      f.setLabel("");
      formationsWithNone.add(0, f);
      model.put("formationsWithNone", formationsWithNone);

    } else if (page == 2) {

      Calendar c = Calendar.getInstance();
      int year = c.get(Calendar.YEAR);

      List years = new ArrayList();

      for (int i = year; i > (year-20); i--) {
        years.add(i);
      }

      List diplomes = dmng.getDiplomes();
      List univs = umng.getUniversities();
      List promos = ((FolderForm) command).getFolder().getPromodetails();
      model.put("diplomes", diplomes);
      model.put("univs", univs);
      model.put("promos", promos);
      model.put("years", years);
    } else if (page == 3) {

      List domains = dmmng.getAllDomains();
      model.put("domains", domains);

      List levels = lmng.getAllLevels();
      model.put("levels", levels);

    } else if (page == 4) {
      model.put("folder", ((FolderForm) command).getFolder());

    } else {
      Folder folder = ((FolderForm) command).getFolder();
      model.put("folder", folder);
      List domains = dmmng.getAllDomains();
      model.put("domains", domains);

    }

    return model;

  }

  protected void validatePage(Object command, Errors errors, int page) {
    FolderForm folderForm = (FolderForm) command;
    InputValidator inputValidator = (InputValidator) getValidator();

    switch (page) {
    case 0:
      errors.setNestedPath("folder.pi");
      inputValidator.validatePageOne(folderForm.getFolder().getPi(),
          errors);
      logger.info("WizardCTRL - validatePageOne() was called");
      break;
    case 1:
      errors.setNestedPath("folder");
      inputValidator.validatePageTwo(folderForm.getFolder(), errors);

      logger.info("WizardCTRL - validatePageTwo() was called");
      break;
    case 2:
      errors.setNestedPath("folder.currentPromoDetail");
      inputValidator.validatePageThree(folderForm.getFolder()
          .getCurrentPromoDetail(), errors);
      logger.info("WizardCTRL - validatePageThree() was called");
      break;
    }
    errors.setNestedPath("");
  }

  protected void initBinder(HttpServletRequest request,
      ServletRequestDataBinder binder) throws Exception {
    binder.registerCustomEditor(byte[].class,
        new ByteArrayMultipartFileEditor());
  }

 
 
  private boolean isClosed(String path){
   
    WebgiProperties wgip = new WebgiProperties(path);
    String dateS = wgip.get("dateFermeture");
   
    String[] date=dateS.split("-");
   
    int day = Integer.parseInt(date[0]);
    int month = Integer.parseInt(date[1])-1;
    int year = Integer.parseInt(date[2]);
   
    Calendar fermeture = new GregorianCalendar(year, month, day);
   
    Calendar c = Calendar.getInstance();
    int currentYear = c.get(Calendar.YEAR);
    int currentMonth = c.get(Calendar.MONTH);
    int currentDay = c.get(Calendar.DAY_OF_MONTH);
   
    Calendar current = new GregorianCalendar(currentYear,
        currentMonth, currentDay);

    return current.after(fermeture);
  }
}
TOP

Related Classes of controller.WizardCTRL

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.