Minha classe session scoped authenticationAction

Continuando a discussão do Java.lang.NullPointerException:

Minha classe session scoped authenticationAction

package com.intelinet.seam.security;

@Scope(ScopeType.SESSION)
@Name(value = “authenticatorAction”)
public class AuthenticatorAction implements Serializable {

private static final long serialVersionUID = 1L;


private @In Identity identity;
//private @In FacesMessages messages;
//private @In LoggedUserManager userMgr;
private @In EntityManager entityManager;
//private static Document mappingsDoc;


@Out(required=false, scope = ScopeType.SESSION)
User user;

@Out(required=false, scope = ScopeType.SESSION)
String versionAplicacao = getVersaoAplicacao();


@Out(required=false, scope = ScopeType.SESSION)
Boolean sistemaLiberado = false;

@Out(required=false, scope = ScopeType.SESSION)
Boolean dadosEnviados = false;

private String chaveLiberacaoChange;


private Caixas caixa = new Caixas();

private Integer userId;

private String userPasswd;

private String messageRetornoAjax="";

private boolean finalizarMatriculas;

private boolean matriculasSemApostila;

private boolean finalizandoMatricula = false;

private List<Matriculas> matriculas_p_finalizar;

private List<Frequencia> horariosRepAberto = new ArrayList<Frequencia>();

private boolean existeHorariosEmAberto;

private static final String hexDigits = "0123456789abcdef";

@Out(required=false, scope = ScopeType.SESSION)
Boolean informarIdCliente = true;

private String idClienteChange;

private String chaveLiberacaoEnvioDadosChange;

private boolean avisoEnvioDados = false;

public boolean authenticate()  {
	try {
		@SuppressWarnings("unchecked")
		List<Parametro> parametros_result = entityManager.createQuery(
				"from Parametro ").getResultList();


		if (parametros_result.get(0).getImportUser()==1){
			Session session = ((Session) entityManager.getDelegate()).getSessionFactory().openSession();
			Transaction tx = session.beginTransaction();
			try {
				new ImportUsuarios().importar(session);
				session.createQuery("update Parametro set importUser=0 ").executeUpdate();
				tx.commit();
			}catch (Exception e) {
				e.printStackTrace();
				tx.rollback();
			}finally{
				session.close();
			}
		}

		@SuppressWarnings("unchecked")
		List<User> users = entityManager.createQuery("from User u where lower(u.login)=lower(:login) and u.passwd=:password")
		.setParameter("login", identity.getCredentials().getUsername())
		.setParameter("password", new BASE64Encoder().encode(identity.getCredentials().getPassword().toUpperCase().getBytes()))
		.getResultList();

		boolean result = false;
		if (users.size() == 0 || users.get(0).getAtivo()==0) {
			// Login failed
			return false;
		} else {
			// Login successful
			user = users.get(0);
			result = true;
			if (user.getPerfil()!=null){
				setRoles(user.getPerfil());
			}
		}

		//return true;

		//boolean result = getUserFromFile(identity.getCredentials().getUsername(), identity.getCredentials().getPassword());
		if (result){
			/*if (parametros_result.get(0).getVendautomatico()!=null){
				user = entityManager.find(User.class, Long.parseLong(parametros_result.get(0).getVendautomatico().toString()));
				if (user!=null){
					userId = user.getId().intValue();
				}
			}else {
				user = null;
			}*/

			sistemaLiberado = verificarChave(new String(parametros_result.get(0).getNomefand(), ParametroHome.encoding)+new String(parametros_result.get(0).getNomefanh(),ParametroHome.encoding), parametros_result.get(0).getAlgo());

			isSistemaLiberado();

			try {
				informarIdCliente = verificarIdCliente(parametros_result.get(0).getIdCliente());
			}catch (Exception e) {
				e.printStackTrace();
				informarIdCliente = true;
			}


			try {
				if (!informarIdCliente){
					checkFilesFechamento(decodeIdCliente(parametros_result.get(0).getIdCliente()), parametros_result.get(0));
					checkReferencia();

					dadosEnviados = verificarEnvioDados(parametros_result.get(0).getIdCliente(), parametros_result.get(0).getChDados());
				}
			}catch (Exception e) {
				e.printStackTrace();
				dadosEnviados = false;
			}

			@SuppressWarnings("unchecked")
			List<Caixas> results = entityManager.createQuery(
					"from Caixas where numero = (select max(numero) from Caixas)").getResultList();

			if (results.size()>0 && results.get(0).getDtFecha()==null && results.get(0).getDtAbre().getTime() ==  DateUtils.truncate(new java.util.Date(), Calendar.DATE).getTime()){


				caixa = results.get(0);

			}


			if (parametros_result.get(0).getMensfincurso().equals("Sim")) {
				@SuppressWarnings("unchecked")
				List<Matriculas> resultList = entityManager.createQuery("from Matriculas where status='ATIVA' and dttermino < :dtaAtual order by dttermino ")
				.setParameter("dtaAtual", DateUtils.truncate(new java.util.Date(), Calendar.DATE))
				.getResultList();

				matriculas_p_finalizar = resultList;

				if (matriculas_p_finalizar.size()>0){
					finalizarMatriculas = true;
				}
			}


			@SuppressWarnings("unchecked")
			List<Frequencia> resultListHorariosRep = entityManager.createQuery(
					" select fr " +
							" from Frequencia fr " +
							"  where fr.id.data < :dtaAtual " +
							"	 and fr.tipo = 'REPOSIÇÃO' " +
							"	 and fr.presente = 'R' " +
					"  order by fr.id.data, fr.id.horario ")
					.setParameter("dtaAtual", DateUtils.truncate(new java.util.Date(), Calendar.DATE))
					.getResultList();

			@SuppressWarnings("unchecked")
			List<Frequencia> resultListHorariosAvulsa = entityManager.createQuery(
					" select fr " +
							" from Frequencia fr " +
							"  where fr.id.data < :dtaAtual " +
							"	 and fr.tipo = 'AVULSA' " +
							"	 and fr.presente = 'A' " +
					"  order by fr.id.data, fr.id.horario ")
					.setParameter("dtaAtual", DateUtils.truncate(new java.util.Date(), Calendar.DATE))
					.getResultList();


			horariosRepAberto.addAll(resultListHorariosRep);

			horariosRepAberto.addAll(resultListHorariosAvulsa);


			if (horariosRepAberto.size()>0){
				if (parametros_result.get(0).getMensrepaberto().equals("Sim")) {
					existeHorariosEmAberto = true;
				}

				for (Frequencia frequencia : horariosRepAberto) {
					@SuppressWarnings("unchecked")
					List<Frequencia> frequenciasHorarios = entityManager.createQuery(" from Frequencia where id.matricula = :matricula and id.data <> :data and id.horario = :horario and (presente = 'A' or presente = 'R') " )
					.setParameter("matricula", frequencia.getMatriculas().getCodigo())
					.setParameter("horario", frequencia.getHorarios().getCodigo())
					.setParameter("data", frequencia.getId().getData())
					.getResultList();
					if (frequenciasHorarios.size()==0){
						@SuppressWarnings("unchecked")
						List<Tabhorarios> l_tabhorarios = entityManager.createQuery( " from Tabhorarios t " +
								"where t.horarios.codigo = :horario " +
								"  and (t.tipo = 'A' or t.tipo = 'R') " +
								"  and t.horarios.diasemana = :diasemana " +
								"  and t.matricula = :matricula ")
								.setParameter("matricula", frequencia.getMatriculas().getCodigo())
								.setParameter("horario", frequencia.getHorarios().getCodigo())
								//.setParameter("tipo", aulaAvulsaMarcada.getPresente())
								.setParameter("diasemana", frequencia.getHorarios().getDiasemana())
								.getResultList();
						for (Tabhorarios tabhorarios : l_tabhorarios) {
							tabhorarios.setTipo("");
							tabhorarios.setMatricula(0);
							entityManager.merge(tabhorarios);
						}
					}
					frequencia.getMatriculas().getAlunos().getNome();
					frequencia.setPresente("N");
					entityManager.flush();
				}
			}

			@SuppressWarnings("unchecked")
			List<Matriculas> matrSemApostilas = entityManager.createQuery("from Matriculas m join m.curMatris cm join cm.cursos c where m.status='ATIVA' and cm.entregouApostila = 'N' and cm.status = 'A'  and c.requerApostila = 1 ")
			.getResultList();

			if (matrSemApostilas.size()>0){
				matriculasSemApostila = true;
			}
		}
		LocaleSelector.instance().setCookieEnabled(false);
		LocaleSelector.instance().select();
		Combos.clearAll();
		return result;

	} catch (Exception ex) {
		ex.printStackTrace();
		return false;
	} catch (Error err) {
		err.printStackTrace();
		return false;
	}
}

public String logout() {
	identity.logout();
	return "/index.xhtml?faces-redirect=true";
}

public boolean getUserFromFile(String login, String password) throws Exception{
	boolean libera = false;
	StringWriter sw = Decode.decodeFile(new File(Config.getDefaultInstance().getProperty("file.User")));

	BufferedReader br = new BufferedReader(new StringReader(sw.toString()));

	String currentLine = br.readLine();

	login = "["+login+"]";
	boolean encontrado = false;
	int nivelAcesso = 0;
	while ((currentLine != null)&&(currentLine.trim().length()>0)) {

		currentLine = currentLine.replaceAll("\r", "").replaceAll("\n", "");
		if (encontrado){
			if (currentLine.substring(0, 1).equals("[")){
				break;
			}else {
				String key = currentLine.substring(0, currentLine.indexOf("="));
				String value = currentLine.substring(currentLine.indexOf("=")+1, currentLine.length());
				if (key.equals("PASSWORD")){
					if (value.toUpperCase().equals(password.toUpperCase())){
						libera = true;
					}else {
						break;
					}
				}else {
					//permissoesMenu.put(key, value);
					nivelAcesso = Integer.parseInt(value.substring(0,1));
					if (nivelAcesso!=0){
						identity.addRole(key);
						if (nivelAcesso == 2){
							identity.addRole(key+"_A");
						}else if (nivelAcesso == 3) {
							identity.addRole(key+"_A");
							identity.addRole(key+"_R");
						}else if (nivelAcesso == 4) {
							identity.addRole(key+"_A");
							identity.addRole(key+"_R");
							identity.addRole(key+"_4");
						}else if (nivelAcesso == 5) {
							identity.addRole(key+"_A");
							identity.addRole(key+"_R");
							identity.addRole(key+"_4");
							identity.addRole(key+"_5");
						}

					}
				}
			}

		}else if (login.toUpperCase().equals(currentLine)){
			encontrado = true;
		}
		currentLine = br.readLine();
	}
	br.close();
	return libera;
}

public synchronized void setRoles(Perfil perfil) {
	int nivelAcesso = 0;
	String key = "";
	for (Diropcaomenuperfil diropcaomenuperfil : perfil.getDiropcaomenuperfils()) {
		key = diropcaomenuperfil.getOpcaomenu().getOpcaoMenu();
		nivelAcesso = Integer.parseInt(diropcaomenuperfil.getDireitoopcao().substring(0,1).substring(0,1));
		if (nivelAcesso!=0){
			identity.addRole(key);
			if (nivelAcesso == 2){
				identity.addRole(key+"_A");
			}else if (nivelAcesso == 3) {
				identity.addRole(key+"_A");
				identity.addRole(key+"_R");
			}else if (nivelAcesso == 4) {
				identity.addRole(key+"_A");
				identity.addRole(key+"_R");
				identity.addRole(key+"_4");
			}else if (nivelAcesso == 5) {
				identity.addRole(key+"_A");
				identity.addRole(key+"_R");
				identity.addRole(key+"_4");
				identity.addRole(key+"_5");
			}

		}
	}
}

/*public synchronized void setRoles(Profile profile) {
	if (profile == null) {
		return;
	}
	if (mappingsDoc == null) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			mappingsDoc = builder.parse(this.getClass().getResourceAsStream("/conf/rolesMapping.xml"));
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	if (mappingsDoc != null) {
		NodeList nl = mappingsDoc.getDocumentElement().getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			Node n = nl.item(i);
			if (n instanceof Element) {
				// profile
				String name = ((Element) n).getAttribute("name");
				if (name.equals(profile.getTag())) {
					NodeList nl2 = n.getChildNodes();
					for (int j = 0; j < nl2.getLength(); j++) {
						// grouptype
						Node n2 = nl2.item(j);
						if (n2 instanceof Element) {
							//String grouptype = ((Element) n2).getAttribute("name");
							NodeList nl3 = n2.getChildNodes();
							for (int k = 0; k < nl3.getLength(); k++) {
								// group
								Node n3 = nl3.item(k);
								if (n3 instanceof Element) {
									String group = ((Element) n3).getAttribute("name");
									identity.addRole(group);
									NodeList nl4 = n3.getChildNodes();
									for (int l = 0; l < nl4.getLength(); l++) {
										// role
										Node n4 = nl4.item(l);
										if (n4 instanceof Element) {
											String role = ((Element) n4).getAttribute("name");
											identity.addRole(role);
										}
									}
								}
							}
						}
					}
					break;
				}
			}
		}
	}
}*/

public User getUser() {
	return user;
}

public void setUser(User user) {
	this.user = user;
}

@SuppressWarnings("unchecked")
public List<Funcionarios> getFuncionarios(){
	return entityManager.createQuery("from Funcionarios order by nome").getResultList();
}

public Integer getUserId() {
	return userId;
}

public void setUserId(Integer userId) {
	this.userId = userId;
	user =  entityManager.find(User.class, Long.parseLong(userId.toString()));
}


public String getUserPasswd() {
	return userPasswd;
}

public void setUserPasswd(String userPasswd) {
	messageRetornoAjax = "";
	if (userPasswd!=null && userPasswd.length()>0){
		@SuppressWarnings("unchecked")
		List<User> usersAux = entityManager.createQuery("from User where passwd = :userPasswd").setParameter("userPasswd", ParametroHome.encripta(userPasswd)).getResultList();
		if (usersAux.size()> 0){
			userId = usersAux.get(0).getId().intValue();
		}else {
			userId = null;
			messageRetornoAjax = "Senha inválida!!!";
		}
	}
	this.userPasswd = userPasswd;
}


public Caixas getCaixa() {

	return caixa;
}

public void setCaixa(Caixas caixa) {
	this.caixa = caixa;
}

public String getSenhavend(){
	@SuppressWarnings("unchecked")
	List<Parametro> parametros_result = entityManager.createQuery(
			"from Parametro ").getResultList();
	return parametros_result.get(0).getSenhavend();
}

public String setFuncionario(){
	if (userId!=null){
		user =  entityManager.find(User.class, Long.parseLong(userId.toString()));
		return "funcionarioSet";
	}
	return "";
}

public String getMessageRetornoAjax() {
	return messageRetornoAjax;
}

public void setMessageRetornoAjax(String messageRetornoAjax) {
	this.messageRetornoAjax = messageRetornoAjax;
}

public boolean isFinalizarMatriculas() {
	return finalizarMatriculas;
}

public void setFinalizarMatriculas(boolean finalizarMatriculas) {
	this.finalizarMatriculas = finalizarMatriculas;
}

public List<Matriculas> getMatriculas_p_finalizar() {
	return matriculas_p_finalizar;
}

public void setMatriculas_p_finalizar(List<Matriculas> matriculas_p_finalizar) {
	this.matriculas_p_finalizar = matriculas_p_finalizar;
}

public void finalizarMatr(ActionEvent event){
	if (getMatriculas_p_finalizar()!=null){
		for (Matriculas matricula : getMatriculas_p_finalizar()) {
			matricula.setStatus("FINALIZADA");
			entityManager.merge(matricula);

			entityManager.createQuery("update Tabhorarios tabhorarios set matricula = 0, tipo='' where matricula = :matricula")
			.setParameter("matricula",matricula.getCodigo())
			.executeUpdate();
		}
		entityManager.flush();
	}
}

public boolean isFinalizandoMatricula() {
	return finalizandoMatricula;
}

public void setFinalizandoMatricula(boolean finalizandoMatricula) {
	this.finalizandoMatricula = finalizandoMatricula;
}

public boolean isMatriculasSemApostila() {
	return matriculasSemApostila;
}

public void setMatriculasSemApostila(boolean matriculasSemApostila) {
	this.matriculasSemApostila = matriculasSemApostila;
}

public String getVersaoAplicacao(){
	if (versionAplicacao == null){
		try {
			versionAplicacao =  Config.getDefaultInstance().getProperty("versionAplicacao");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	return versionAplicacao;
}


public String getControleInterno() {
	String result = "";

	try {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ServletContext servletContext = (ServletContext)facesContext.getExternalContext().getContext();
		String driveLetter = new File(servletContext.getRealPath("")).getParent().substring(0,1);

		File file = File.createTempFile("realhowto",".vbs");
		file.deleteOnExit();
		FileWriter fw = new java.io.FileWriter(file);

		String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
				+"Set colDrives = objFSO.Drives\n"
				+"Set objDrive = colDrives.item(\"" + driveLetter + "\")\n"
				+"Wscript.Echo objDrive.SerialNumber";  // see note
		fw.write(vbs);
		fw.close();
		Process p = Runtime.getRuntime().exec("cscript //NoLogo \"" + file.getPath()+"\"");
		BufferedReader input =
				new BufferedReader
				(new InputStreamReader(p.getInputStream()));
		String line;
		while ((line = input.readLine()) != null) {
			result += line;
		}
		input.close();
		if (result !=null && result.length()>0){
			result = Integer.toHexString(Integer.parseInt(result)).toUpperCase();
		}
	}
	catch(Exception e){
		e.printStackTrace();
	}
	return result.trim();
}


/*private static String encodeChave(String stg, int algo){
	String encoding = "ISO-8859-1";
	String result = "";
	try {
		for (int i = 0; i < stg.length(); i++) {
			byte[] b = stg.getBytes(encoding);
			result += new String(new byte[] {(byte) (b[i]+algo)}, encoding);
		}
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return result;
}*/

private static String decodeChave(String stg, int algo){
	String encoding = "ISO-8859-1";
	String result = "";
	try {
		byte[] b = stg.getBytes(encoding);
		for (int i = 0; i < stg.length(); i++) {
			result += new String(new byte[] {(byte) (b[i]-algo)}, encoding);
		}
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return result;
}

public Boolean isSistemaLiberado(){
	return sistemaLiberado;
}

public Boolean verificarChave(String chaveLiberacao, int algo){
	Boolean result = false;
	try {

		SimpleDateFormat clientDateFormat = new SimpleDateFormat(FacesMessages.createFacesMessage(FacesMessage.SEVERITY_INFO, "pattern", "dd/MM/yyyy", new Object[]{}).getSummary());
		if (chaveLiberacao!=null && chaveLiberacao.length()>9){
			java.util.Date dtChave = clientDateFormat.parse(decodeChave(chaveLiberacao.substring(0, 10), algo));
			if (dtChave.getTime() >= clientDateFormat.parse(clientDateFormat.format(new java.util.Date())).getTime()){
				String serialHDD = getControleInterno();
				if (serialHDD.equals(decodeChave(chaveLiberacao.substring(10), algo))){
					result = true;
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return result;
}

public String getChaveLiberacaoChange() {
	return chaveLiberacaoChange;
}

public void setChaveLiberacaoChange(String chaveLiberacaoChange) {
	this.chaveLiberacaoChange = chaveLiberacaoChange;
}

public void liberarSistema(ActionEvent event){
	messageRetornoAjax = "";
	try {
		SimpleDateFormat clientDateFormat = new SimpleDateFormat(FacesMessages.createFacesMessage(FacesMessage.SEVERITY_INFO, "pattern", "dd/MM/yyyy", new Object[]{}).getSummary());
		int algo = Integer.parseInt(clientDateFormat.format(new java.util.Date()).substring(0,2))+Integer.parseInt(clientDateFormat.format(new java.util.Date()).substring(3,5));
		if (verificarChave(chaveLiberacaoChange, algo)){
			@SuppressWarnings("unchecked")
			List<Parametro> parametros_result = entityManager.createQuery(
					"from Parametro ").getResultList();
			parametros_result.get(0).setNomefand(chaveLiberacaoChange.substring(0, 10).getBytes(ParametroHome.encoding));
			parametros_result.get(0).setNomefanh(chaveLiberacaoChange.substring(10).getBytes(ParametroHome.encoding));
			parametros_result.get(0).setAlgo(algo);
			sistemaLiberado = true;
			entityManager.merge(parametros_result.get(0));
			entityManager.flush();
		}else {
			messageRetornoAjax = FacesMessages.createFacesMessage(FacesMessage.SEVERITY_INFO, "erro.validacao.chaveLiberacao", "erro.validacao.chaveLiberacao", new Object[]{}).getSummary();
		}
	}catch (Exception e) {
		messageRetornoAjax = "Erro:"+Erros.getMessage(e);
		e.printStackTrace();
	}
}

public List<Frequencia> getHorariosRepAberto() {
	return horariosRepAberto;
}

public void setHorariosRepAberto(List<Frequencia> horariosRepAberto) {
	this.horariosRepAberto = horariosRepAberto;
}

public boolean isExisteHorariosEmAberto() {
	return existeHorariosEmAberto;
}

public void setExisteHorariosEmAberto(boolean existeHorariosEmAberto) {
	this.existeHorariosEmAberto = existeHorariosEmAberto;
}

public String exportarRelatorioReposicoesAbertoPDF(ActionEvent event) {
	try {

		FacesContext facesContext = FacesContext.getCurrentInstance();
		ServletContext servletContext = (ServletContext)facesContext.getExternalContext().getContext();
		String path = servletContext.getRealPath("/reports/RelHorariosReposicaoAberta.jasper");

		///parametros
		Map<String, Object> parameters = new HashMap<String, Object>();
		String nomeArquivo = "RelHorariosReposicaoAberto.pdf";
		//recebe por parametro uma lista da propia classe jah populada
		JRDataSource jrds = new JRBeanCollectionDataSource(horariosRepAberto);

		ExportRelatorio.exportarRelatorioPDF(path, nomeArquivo, jrds, parameters, entityManager);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;

}

private void checkReferencia() {
	try {

		ParametroHome parametroHome = new ParametroHome();
		parametroHome.setUser(user);
		String referencia =parametroHome.getInstance().getReferencia();

		SimpleDateFormat referenciaFormat = new SimpleDateFormat("MM/yyyy");
		SimpleDateFormat clientDateFormat = new SimpleDateFormat(FacesMessages.createFacesMessage(FacesMessage.SEVERITY_INFO, "pattern", "dd/MM/yyyy", new Object[]{}).getSummary());

		GregorianCalendar gcAtual = new GregorianCalendar();
		GregorianCalendar gcLimite = new GregorianCalendar();

		do {
			gcLimite.setTimeInMillis(clientDateFormat.parse("01/"+parametroHome.getNovaReferencia()).getTime());
			if (!referenciaFormat.format(gcAtual.getTime()).equals(referencia) && gcAtual.after(gcLimite) ){
				parametroHome.trocaReferencia();
				if (parametroHome.getMessageRetornoAjax().length()==0){
					parametroHome.setNovaReferencia(null);
					referencia =parametroHome.getInstance().getReferencia();
					gcLimite.setTimeInMillis(clientDateFormat.parse("01/"+parametroHome.getNovaReferencia()).getTime());
				}else {
					break;
				}
			}
		}while (!referenciaFormat.format(gcAtual.getTime()).equals(referencia) && gcAtual.after(gcLimite) );
	} catch (Exception e) {
		e.printStackTrace();
	}

}

private void checkFilesFechamento(Integer idCliente, Parametro parametro) throws ParseException{
	FacesContext facesContext = FacesContext.getCurrentInstance();
	ServletContext servletContext = (ServletContext)facesContext.getExternalContext().getContext();
	String path = servletContext.getRealPath("/private/informativos");

	@SuppressWarnings("unchecked")
	List<Fechamento> l_fechamento = entityManager.createQuery( " from Fechamento f " +
			"where f.dtaEnvio is null ").getResultList();
	for (Fechamento fechamento : l_fechamento) {
		java.util.Date dtAtual = new java.util.Date();
		String fileZip = path+File.separator+fechamento.getFilefechamento();
		File file = new File(fileZip);
		boolean enviado = false;
		String chave = ParametroHome.sendDadosWS(fechamento, idCliente);
		if (chave!=null){
			enviado = true;
			SimpleDateFormat referenciaFormat = new SimpleDateFormat("MM/yyyy");
			SimpleDateFormat clientDateFormat = new SimpleDateFormat(FacesMessages.createFacesMessage(FacesMessage.SEVERITY_INFO, "pattern", "dd/MM/yyyy", new Object[]{}).getSummary());
			GregorianCalendar gcRefAnterior = new GregorianCalendar();
			gcRefAnterior.setTimeInMillis(clientDateFormat.parse("01/"+referenciaFormat.format(new java.util.Date())).getTime());
			gcRefAnterior.add(Calendar.MONTH, -1);
			if ( fechamento.getRefer().equals(referenciaFormat.format(gcRefAnterior.getTime()))){
				parametro.setChDados(encriptar(fechamento.getRefer(), getControleInterno().getBytes()));
			}
			entityManager.flush();
		}
		boolean exist = file.exists();
		if (!enviado && exist){
			enviado = ParametroHome.sendFTP(file);
		}
		fechamento.setDtaEnvio(enviado?dtAtual:null);
		fechamento.setUlttentaenvio(dtAtual);
		fechamento.setFilefechamento(file.getName());
		entityManager.merge(fechamento);
		entityManager.flush();
		if (enviado ) {
			file.delete();
		}
	}

}