Ocorre o erro java.lang.NullPointerException na hora que tentona classe SecurityFilter pegar os valores do caixa instanciado na classe authenticationAction, mas isso é depois de um tempo de execução, e ão consigo solucionar, por favor me ajudem

12/03/2016

0

Meu components.xml

<?xml version="1.0" encoding="UTF-8"?>
<components xmlns="http://jboss.com/products/seam/components"
xmlns:web="http://jboss.com/products/seam/web"
xmlns:security="http://jboss.com/products/seam/security"
xmlns:persistence="http://jboss.com/products/seam/persistence"
xmlns:core="http://jboss.com/products/seam/core"
xmlns:transaction="http://jboss.com/products/seam/transaction"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:international="http://jboss.com/products/seam/international"
xsi:schemaLocation=
"http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.2.xsd
http://jboss.com/products/seam/persistence http://jboss.com/products/seam/persistence-2.2.xsd
http://jboss.com/products/seam/transaction http://jboss.com/products/seam/transaction-2.2.xsd
http://jboss.com/products/seam/security http://jboss.com/products/seam/security-2.2.xsd
http://jboss.com/products/seam/international http://jboss.com/products/seam/international-2.2.xsd
http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.2.xsd"
>

<!-- <web:exception-filter url-pattern="*.seam"/>
<web:redirect-filter url-pattern="*.seam"/>
-->
<core:init debug="true"/>

<persistence:entity-manager-factory class="persistence.DynamicEntityProvider" name="mainDatabase"/>
<transaction:entity-transaction entity-manager="#"/>
<persistence:managed-persistence-context name="em" auto-create="true" entity-manager-factory="#"/>
<persistence:managed-persistence-context name="entityManager" auto-create="true" entity-manager-factory="#"/>

<security:identity authenticate-method="#{authenticatorAction.authenticate}" />

<core:manager concurrent-request-timeout="9500"
conversation-timeout="120000"
conversation-id-parameter="cid"/>
<!-- default-flush-mode="MANUAL/>" -->
<component name="org.jboss.seam.core.init">
<property name="jndiPattern">#/local</property>
</component>

<international:locale-selector cookie-enabled="true"/>
</components>











Minha Classe authenticatorAction session scoped

package com.intelinet.seam.security;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.servlet.ServletContext;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.commons.lang.time.DateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.LocaleSelector;
import org.jboss.seam.security.Identity;

import sun.misc.BASE64Encoder;

import com.intelinet.biz.Diropcaomenuperfil;
import com.intelinet.biz.Perfil;
import com.intelinet.biz.User;
import com.intelinet.biz.onbyte.Caixas;
import com.intelinet.biz.onbyte.Fechamento;
import com.intelinet.biz.onbyte.Frequencia;
import com.intelinet.biz.onbyte.Funcionarios;
import com.intelinet.biz.onbyte.Matriculas;
import com.intelinet.biz.onbyte.Parametro;
import com.intelinet.biz.onbyte.Tabhorarios;
import com.intelinet.seam.action.onbyte.ParametroHome;
import com.intelinet.util.Combos;
import com.intelinet.util.Config;
import com.intelinet.util.Decode;
import com.intelinet.util.Erros;
import com.intelinet.util.ExportRelatorio;
import com.intelinet.util.ImportUsuarios;

@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();
}
}

}

public Boolean verificarEnvioDados(String idCliente, String chaveLiberacao){
Boolean result = false;
if (idCliente!=null && idCliente.length()>0){
String idClienteAux = desencriptar(idCliente, getControleInterno().getBytes());
if (idClienteAux.substring(10).equals("1")){
return 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();
try {

if (chaveLiberacao!=null && chaveLiberacao.length()>9){
gcRefAnterior.setTimeInMillis(clientDateFormat.parse("01/"+referenciaFormat.format(new java.util.Date())).getTime());
gcRefAnterior.add(Calendar.MONTH, -1);
String serialHDD = getControleInterno();
String refChave = desencriptar(chaveLiberacao, serialHDD.getBytes());
String refAnterior = referenciaFormat.format(gcRefAnterior.getTime());

if (Integer.parseInt(refChave.substring(3,7)+refChave.substring(0,2))>=Integer.parseInt(refAnterior.substring(3,7)+refAnterior.substring(0,2)) ){
result = true;
}else {
GregorianCalendar gcAtual = new GregorianCalendar();
gcRefAnterior.add(Calendar.MONTH, -1);
if (desencriptar(chaveLiberacao, serialHDD.getBytes()).equals(referenciaFormat.format(gcRefAnterior.getTime())) && gcAtual.get(Calendar.DATE) <=5 ){
result = true;
avisoEnvioDados = true;
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}

public static String desencriptar (String texto){
String resultado = texto;
try {
String chave = texto.substring(0,16);
texto = texto.substring(16,texto.length());
return desencriptar(texto, hexStringToByteArray(chave));
}catch (Exception e){
e.printStackTrace();
}
return resultado;
}

private static String desencriptar (String texto, byte[] chave){
try {
DESKeySpec desKeySpec = new DESKeySpec(chave);
SecretKeyFactory keyFactory2 = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory2.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(hexStringToByteArray(texto)));
}catch (Exception e){
e.printStackTrace();
return null;
}
}

private static byte[] hexStringToByteArray(String hexa)
throws IllegalArgumentException {

if (hexa.length() % 2 != 0) {
throw new IllegalArgumentException("String hexa inválida");
}

byte[] b = new byte[hexa.length() / 2];

for (int i = 0; i < hexa.length(); i+=2) {
b[i / 2] = (byte) ((hexDigits.indexOf(hexa.charAt(i)) << 4) |
(hexDigits.indexOf(hexa.charAt(i + 1))));
}
return b;
}

/**
* @return the enviodeDados
*/
public Boolean isDadosEnviados() {
return dadosEnviados;
}

/**
* @return the informarIdCliente
*/
public Boolean isInformarIdCliente() {
return informarIdCliente;
}

public Boolean verificarIdCliente(String idCliente){
return !(idCliente!=null && idCliente.length()>0 && desencriptar(idCliente, getControleInterno().getBytes()).length()==11);
}

private Integer decodeIdCliente(String idCliente) {
Integer idClienteAux = null;
if (idCliente!=null && idCliente.length()>0) {
idClienteAux = Integer.parseInt(desencriptar(idCliente, getControleInterno().getBytes()).substring(0,10));
}
return idClienteAux;
}

public void informarIdCliente(ActionEvent event){
messageRetornoAjax = "";
try {
String idCliente = verificarChaveLiberacaoEnvioDados(idClienteChange);
if (idCliente!=null){
@SuppressWarnings("unchecked")
List<Parametro> parametros_result = entityManager.createQuery(
"from Parametro ").getResultList();
parametros_result.get(0).setIdCliente(idCliente);
informarIdCliente = false;
entityManager.merge(parametros_result.get(0));
entityManager.flush();
chaveLiberacaoEnvioDadosChange=idClienteChange;
liberarSistemaEnvioDados(event);
}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();
}
}

/**
* @return the idClienteChange
*/
public String getIdClienteChange() {
return idClienteChange;
}

/**
* @param idClienteChange the idClienteChange to set
*/
public void setIdClienteChange(String idClienteChange) {
this.idClienteChange = idClienteChange;
}

public String verificarChaveLiberacaoEnvioDados(String idClienteChange){
String result = null;
try {

if (idClienteChange!=null){
SimpleDateFormat clientDateFormat = new SimpleDateFormat(FacesMessages.createFacesMessage(FacesMessage.SEVERITY_INFO, "pattern", "dd/MM/yyyy", new Object[]{}).getSummary());
String algo = clientDateFormat.format(new java.util.Date()).substring(0,2)+clientDateFormat.format(new java.util.Date()).substring(3,5);
String serialHDD = getControleInterno();
String idClienteDecode = desencriptar(idClienteChange, (algo+serialHDD).getBytes());
if (idClienteDecode.length()==11){
result = encriptar(idClienteDecode.substring(0,11), (serialHDD).getBytes());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

private static String encriptar(String texto, byte[] chave) {

try{
DESKeySpec desKeySpec = new DESKeySpec(chave);
SecretKeyFactory keyFactory2 = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory2.generateSecret(desKeySpec);
byte[] data = texto.getBytes();
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] resultado = cipher.doFinal(data);
return byteArrayToHexString(resultado);

}catch (Exception ioe) {
ioe.printStackTrace();
return null;
}
}

public static String byteArrayToHexString(byte[] b) {
StringBuffer buf = new StringBuffer();

for (int i = 0; i < b.length; i++) {
int j = b[i] & 0xFF;
buf.append(hexDigits.charAt(j / 16));
buf.append(hexDigits.charAt(j % 16));
}

return buf.toString();
}

public void liberarSistemaEnvioDados(ActionEvent event){
messageRetornoAjax = "";
try {
String chave = verificarChaveLiberacaoEnvioDados(chaveLiberacaoEnvioDadosChange);
if (chave!=null){
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();
try {

@SuppressWarnings("unchecked")
List<Parametro> parametros_result = entityManager.createQuery(
"from Parametro ").getResultList();

gcRefAnterior.setTimeInMillis(clientDateFormat.parse("01/"+referenciaFormat.format(new java.util.Date())).getTime());
gcRefAnterior.add(Calendar.MONTH, -1);
parametros_result.get(0).setChDados(encriptar(referenciaFormat.format(gcRefAnterior.getTime()), getControleInterno().getBytes()));
entityManager.merge(parametros_result.get(0));
entityManager.flush();
dadosEnviados = true;
} catch (ParseException e) {
e.printStackTrace();
}

}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();
}
}

/**
* @return the chaveLiberacaoEnvioDadosChange
*/
public String getChaveLiberacaoEnvioDadosChange() {
return chaveLiberacaoEnvioDadosChange;
}

/**
* @param chaveLiberacaoEnvioDadosChange the chaveLiberacaoEnvioDadosChange to set
*/
public void setChaveLiberacaoEnvioDadosChange(
String chaveLiberacaoEnvioDadosChange) {
this.chaveLiberacaoEnvioDadosChange = chaveLiberacaoEnvioDadosChange;
}

public boolean getAvisoEnvioDados() {
return avisoEnvioDados;
}

public void setAvisoEnvioDados(boolean avisoEnvioDados) {
this.avisoEnvioDados = avisoEnvioDados;
}
}

Minha classe SecurityFilters

package com.intelinet.servlet.filter;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.seam.Component;
import org.jboss.seam.Seam;
import org.jboss.seam.security.Identity;

import com.intelinet.biz.User;
import com.intelinet.biz.onbyte.Caixas;
import com.intelinet.seam.security.AuthenticatorAction;

@WebFilter(filterName = "SecurityFilter", urlPatterns = "/private/*")
public class SecurityFilter implements Filter {

private String encoding = "utf-8";
//@In Identity identity;

@Override
public void destroy() {
// Empty
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("This filter can only process HttpServletRequest requests");
}
request.setCharacterEncoding(encoding);
HttpServletRequest httpRequest = (HttpServletRequest) request;
Identity identity = (Identity) httpRequest.getSession().getAttribute( Seam.getComponentName(Identity.class) );



User user = (User) httpRequest.getSession().getAttribute( "user");

Boolean liberacao = (Boolean) httpRequest.getSession().getAttribute( "sistemaLiberado");

Boolean dadosEnviados = (Boolean) httpRequest.getSession().getAttribute( "dadosEnviados");

Boolean informarIdCliente = (Boolean) httpRequest.getSession().getAttribute( "informarIdCliente");

AuthenticatorAction authenticatorAction = (AuthenticatorAction) httpRequest.getSession().getAttribute( Seam.getComponentName(AuthenticatorAction.class) );
Caixas caixa=null;
if (authenticatorAction!=null){
caixa = authenticatorAction.getCaixa();
}

if (caixa!=null){
//Component.getInstance("entityManager");Component.getInstance("org.jboss.seam.core.conversation");
//org.jboss.seam.contexts.ServletLifecycle.beginReinitialization((HttpServletRequest) request, request.getServletContext());
//Collections.list(request.getServletContext().getAttributeNames());
//((org.jboss.seam.Component) request.getServletContext().getAttribute("org.jboss.seam.core.conversation.component"));
//((ServerConversationContext)Contexts.getConversationContext()).get("entityManager");
//ContextAdaptor.getRequest(javax.servlet.ServletRequest request)
//Context ctx = new SessionContext( new ServletRequestSessionMap((HttpServletRequest) request) );
//ServerConversationContext ctx2 = new ServerConversationContext(new ServletRequestMap((HttpServletRequest) request));

org.jboss.seam.contexts.ServletLifecycle.beginReinitialization((HttpServletRequest)request, request.getServletContext());
org.jboss.seam.contexts.ServletLifecycle.resumeConversation((HttpServletRequest) request);
EntityManager entityManager = ((EntityManager)Component.getInstance("entityManager", false));

if (entityManager!=null){
caixa = entityManager.find(Caixas.class, caixa.getNumero());
authenticatorAction.setCaixa(caixa);
}
}

String pageSetFuncionario = ((HttpServletRequest) request).getContextPath() + "/private/onbyte/SetFuncionario.jsf";
String pageCaixasAbertura = ((HttpServletRequest) request).getContextPath() + "/private/onbyte/CaixasAbertura.jsf";
String pageLiberacao = ((HttpServletRequest) request).getContextPath() + "/private/onbyte/LiberacaoSistema.jsf";
String pageMovcaixaList = ((HttpServletRequest) request).getContextPath() + "/private/onbyte/MovcaixaList.jsf";
request.getCharacterEncoding();
/*Enumeration<String> e = ((HttpServletRequest) request).getSession().getAttributeNames();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}*/
boolean logout = false;
String action = ((HttpServletRequest) request).getParameter("actionMethod");
if (action!=null && action.indexOf("authenticatorAction.logout")!=-1){
logout = true;
}


if (!logout && !identity.isLoggedIn()) {
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/index.jsf");
}else if (!logout && (liberacao==null || !liberacao) && !((HttpServletRequest) request).getRequestURI().equals(pageLiberacao) ){
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/index.jsf");
}else if (!logout && (dadosEnviados==null || !dadosEnviados) ){
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/index.jsf");
}else if (!logout && (informarIdCliente==null || informarIdCliente) ){
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/index.jsf");
}else if (!logout && user==null && !((HttpServletRequest) request).getRequestURI().equals(pageSetFuncionario) ){
((HttpServletResponse) response).sendRedirect(pageSetFuncionario);
}else if (!logout && (caixa==null || caixa.getDtFecha()!=null) && !((HttpServletRequest) request).getRequestURI().equals(pageSetFuncionario) && !((HttpServletRequest) request).getRequestURI().equals(pageCaixasAbertura) && !((HttpServletRequest) request).getRequestURI().equals(pageMovcaixaList) ){
//chain.doFilter(request, response);
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/index.jsf");
}else {
chain.doFilter(request, response);
}
//chain.doFilter(request, response); //request instanceof javax.servlet.http.HttpServletRequest request.getServletContext().//((Identity) org.jboss.seam.Seam.getComponentName(Identity.class)).getCredentials().getUsername()
}catch (ServletException e) {
e.printStackTrace();
throw e;
}
}


@Override
public void init(FilterConfig config) throws ServletException {
// Empty
String encodingParam = config.getInitParameter("encoding");
if (encodingParam != null) {
encoding = encodingParam;
}
}


}
[img]http://arquivo.devmedia.com.br/forum/imagem/480156-20160312-091042.png[/img]
Edson Mello

Edson Mello

Responder

Posts

20/03/2016

Cassius Magalhães

Olá,

Você colocou a bilblioteca do Seam Security ?

Em caso negativo, veja: http://docs.jboss.org/seam/3/security/latest/reference/en-US/html_single/#d0e55
Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar