maia_modificado/.svn/pristine/d1/d1829a829470068e2be09ba74bb...

292 lines
10 KiB
Plaintext
Executable File

package com.fp.frontend.controller.pgeneral.firmas;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.crypto.BadPaddingException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;
import com.fp.base.persistence.TfirmDatosFirmante;
import com.fp.common.logger.APPLogger;
import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.save.DtoSave;
import com.fp.firmas.rules.common.CertificateUtils;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.pfirmas.param.TfirmCertificado;
@ManagedBean
@ViewScoped
public class CertificadosController extends AbstractController<TfirmCertificado> {
private static final long serialVersionUID = 1L;
private boolean existeCertificado;
public CertificadosController() throws Exception {
super(TfirmCertificado.class);
}
@PostConstruct
public void postConstruct() {
this.init();
}
/**
* Incializa el controlador, cuando se esta utilizando una pagina que utliza el controlador.
*/
private void init() {
try {
recperpage = 10; // Cambiar al # reg a mirar.
lrecord = new ArrayList<>();
beanalias = "USUARIOCERTIFICADOS";
} catch (Exception e) {
MessageHelper.setMessageError(e);
}
}
@SuppressWarnings("unchecked")
@Override
public void querydatabase() {
try {
Request request = callerhelper.getRequest();
DtoQuery dto = super.getDtoQuery(Boolean.TRUE);
HashMap<String, DtoQuery> mtable = new HashMap<String, DtoQuery>();
mtable.put(beanalias, dto);
request.setQueryTables(mtable);
request.put("queryalias", beanalias);
Response response = callerhelper.executeQuery(request);
if (response.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
lrecord = new ArrayList<TfirmCertificado>();
MessageHelper.setMessageError(response);
} else {
lrecord = (List<TfirmCertificado>) response.get(beanalias);
super.postQuery(lrecord);
}
} catch (Throwable e) {
MessageHelper.setMessageError(e);
}
}
@Override
public void save() {
try {
Request request = callerhelper.getRequest();
DtoSave dto = super.getDtoSave();
if (!dto.pendingProcess()) {
return;
}
HashMap<String, DtoSave> msave = new HashMap<String, DtoSave>();
msave.put(beanalias, dto);
request.setSaveTables(msave);
Response response = callerhelper.executeSave(request);
if (response.getResponseCode().compareTo(Response.RESPONSE_OK) == 0) {
this.postCommit(response);
MessageHelper.setMessageInfo(response);
} else {
MessageHelper.setMessageError(response);
}
} catch (Throwable e) {
MessageHelper.setMessageError(e);
}
}
/**
* M&eacute;todo que abre el LOV de empleados y setea los par&aacute;metros definidos
*/
public void abrirLovEmpleado() {
Map<String, List<String>> paramsLov = new HashMap<String, List<String>>();
// LovEmpleadoSbsController.openLov(paramsLov);
}
/**
* M&eacute;todo que se invoca al regresar desde el LOV de empleados un p:dialog
*
* @param event
* @throws Exception
*/
public void retornoServidor(SelectEvent event) throws Exception {
/*
* Empleado e = (Empleado) event.getObject(); this.addFilter("codigousuario", e.getUsuarioweb());
* this.addField("nom_servidor", e.getNombre());
*/
}
/**
* M&eacute;todo que se invoca al retornar del segundo LOV de empleados
*
* @param event
*/
public void retornoPopupCreacion(SelectEvent event) {
/*
* Empleado e = (Empleado) event.getObject(); // this.record.modifiedData.put("codigousuario", e.getCodigo());
* this.record.modifiedData.put("nom_servidor", e.getNombre()); //
* this.record.modifiedData.put("cargo_servidor", e.getCargo());
* this.record.setCodigousuario(e.getUsuarioweb()); this.record.setCargo(e.getCargo());
*/
}
/**
* Sobreescribo el metodo update del popup para que genere los datos del certificado
*/
@Override
public void update() throws Exception {
try {
if (record.modifiedData.get("nom_servidor") == null) {
throw new RuntimeException("Debe ingresar el empleado");
}
if (record.modifiedData.get("valor_certificado_bin") != null) {
// valido los datos adicionales a agregar para enviar datos a la capa de negocio donde se procesara la
// logica de almacenamiento
TfirmDatosFirmante datosFirmante = generacionDatosArchivo(record.getPk().getIdcertificado(), new ByteArrayInputStream((byte[]) record
.getModifiedData().get("valor_certificado_bin")));
record.getPk().setFcaducidad(new Date(datosFirmante.getFechaVigencia().getTime()));
record.setFingreso(new Date(System.currentTimeMillis()));
record.setFvigencia(new Date(datosFirmante.getFechaInicioVigencia().getTime()));
record.modifiedData.put("nom_certificado", datosFirmante.getNombre());
record.modifiedData.put("estado_certificado",
datosFirmante.getFechaVigencia().compareTo(new Date(System.currentTimeMillis())) >= 0 ? "VIGENTE" : "CADUCADO");
super.update();
} else {
throw new RuntimeException("Debe a\u00f1adir un archivo para grabar");
}
} catch (IOException e) {
FacesContext.getCurrentInstance().validationFailed();
if (e.getCause() instanceof BadPaddingException) {
MessageHelper.setMessageError(new RuntimeException("La clave del certificado es incorrecta"));
}
} catch (Throwable e) {
FacesContext.getCurrentInstance().validationFailed();
MessageHelper.setMessageError(e);
}
}
/**
* Carga un documento y lo almacena en memoria
*
* @param event
*/
public void uploadCertificado(FileUploadEvent event) {
try {
// this.existeCertificado = true;
APPLogger.getLogger().info("Ingreso a subir el documento");
record.getPk().setIdcertificado(event.getFile().getFileName());
record.modifiedData.put("valor_certificado_bin", IOUtils.toByteArray(event.getFile().getInputstream()));
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "Archivo subido correctamente", "Archivo subido correctamente"));
} catch (IOException e) {
MessageHelper.setMessageError(e);
}
}
/**
* Retorna datos del firmante antes de que se envie los datos a grabar
*
* @param nombreArchivo
* @param datosArchivo
* @return
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws IOException
*/
private TfirmDatosFirmante generacionDatosArchivo(String nombreArchivo, InputStream datosArchivo) throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(datosArchivo, record.modifiedData.get("password_certificado").toString().toCharArray());
Certificate certificate = CertificateUtils.obtainCertificateInAlias(ks, ks.aliases());
return CertificateUtils.obtainDataForCertificate(certificate);
}
/**
* Entrega una lista de objetos TfirmCertificado
*
* @return lrecord Lista de objetos TfirmCertificado
*/
public static List<TfirmCertificado> find() {
try {
CertificadosController cc = new CertificadosController();
cc.init();
cc.recperpage = 300;
cc.querydatabase();
if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
return cc.lrecord;
}
return null;
} catch (Throwable e) {
MessageHelper.setMessageError(e);
return null;
}
}
/**
* Entrega una lista de objetos TgeneCatalogDetail
*
* @param certificado C&oacute de certificado
* @return record Objeto TfirmCertificado
*/
public static TfirmCertificado find(String usuario) {
try {
CertificadosController cc = new CertificadosController();
cc.init();
cc.recperpage = 300;
cc.addFilter("codigousuario", usuario);
cc.querydatabase();
if ((cc.lrecord != null) && !cc.lrecord.isEmpty()) {
return cc.lrecord.get(0);
}
return null;
} catch (Throwable e) {
MessageHelper.setMessageError(e);
return null;
}
}
/**
* Entrega V/F
*
* @return existeCertificado
*/
public boolean isExisteCertificado() {
return existeCertificado;
}
/**
* Fija V/F
*
* @param existeCertificado
*/
public void setExisteCertificado(boolean existeCertificado) {
this.existeCertificado = existeCertificado;
}
}