Añado los fuentes de java

This commit is contained in:
2025-06-09 13:37:06 +02:00
parent d6c990e5d5
commit a97a6350ee
226 changed files with 57246 additions and 0 deletions
@@ -0,0 +1,560 @@
/**
* @(#) GestorAdministracion.java
*/
package com.tarisan.servlets;
import com.google.gson.Gson;
import com.tarisan.control.*;
import com.tarisan.data.TanivelActo;
import com.tarisan.data.TanivelEspecialidad;
import com.tarisan.data.Usuario;
import com.tarisan.excepcion.*;
import com.tarisan.log.*;
import com.tarisan.util.Utilidades;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Vector;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.sql.Connection;
import java.sql.Timestamp;
/**
* Servlet direccionador a páginas JSP para el módulo de administración de usuarios.
* @author <a href="mailto:sistemas@imqnavarra.com">Dpto. Informática</a>.
* @version 1.0, 24/09/2003
*/
public class GestorAdministracion extends HttpServlet implements Constantes
{
/**
* Recepción de la petición de acceso al módulo de administración solicitada por el cliente.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que recibirá el cliente.
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
LogTarisan.logger.log(NivelLog.INFO, "GestorAdministracion.service().INI");
response.setHeader("Expires", "0");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
HttpSession sesion = request.getSession(true);
if(sesion.isNew() || (sesion.getAttribute("USUARIO") == null))
{
String opcion = request.getParameter("OPCION");
if (Integer.parseInt(opcion)==OPC_ADM_MOSTRAR_LOG){
this.evaluarOpcion(opcion, request, response, sesion);
}else{
LogTarisan.logger.log(NivelLog.DEBUG, "Sesión no iniciada redirigimos");
response.sendRedirect("../html/login.html");
}
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Entrada aceptada al módulo de Administración");
String opcion = request.getParameter("OPCION");
this.evaluarOpcion(opcion, request, response, sesion);
}
LogTarisan.logger.log(NivelLog.INFO, "GestorAdministracion.service().FIN");
}
/**
* Evalúa la opción del módulo de administración solicitada por el usuario.
* Redirigiendo a la página JSP correspondiente a la opción de menú requerida.
* @param sOpcion El código de la opción de menú solicitada por el usuario.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> conla sesión del usuario conectado.
*/
private void evaluarOpcion(String sOpcion, HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws IOException
{
int nOpcion = 0;
try
{
nOpcion = Integer.parseInt(sOpcion);
}
catch(NumberFormatException e)
{
}
switch(nOpcion)
{
case OPC_ADM_USUARIO_LISTA:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Usuarios' seleccionada");
response.sendRedirect("../jsp/adm/lista_usuarios.jsp?x=0&pagina=1");
break;
}
case OPC_ADM_PASSWORD:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Password' seleccionada");
response.sendRedirect("../jsp/med/password.jsp");
break;
}
case OPC_ADM_USUARIO_DETALLE:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se actualiza la informacion del usuario seleccionado");
this.actualizarDatosUsuario(request, response, sesion);
//redirigimos a la pagina de detalle de usuario
response.sendRedirect("../jsp/adm/detalle_usuario.jsp?x=" + request.getParameter("x") + "&medico=" + request.getParameter("medico"));
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la actualizacion de los datos del usuario." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
sesion.setAttribute("ERROR", "Error en la actualizacion de los datos del usuario.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_ADM_ACT_AUTORIZACION:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a actualizar autorizacion");
try {
if(this.actualizarAutorizacion(request, response, sesion))
{
sesion.setAttribute("MENSAJE", "Actualizacion realizada correctamente");
response.sendRedirect("../jsp/adm/mto_taconaut.jsp?x=" + request.getParameter("x"));
}
} catch (ExcepcionTarisan e) {
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + e);
sesion.setAttribute("ERROR", "Error en la actualizacion de la autorizacion.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_ADM_GES_NIVELES_ESPE:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Obtener Niveles y Visibilidad de las especialidades");
response.sendRedirect("../jsp/adm/mto_niveles.jsp?x=3&especialidad=" + request.getParameter("hiddenEspecialidad") +"&especialidadSolicitada=" + request.getParameter("hiddenEspecialidadSolicitada"));
break;
}
case OPC_ADM_GES_ACT_VISIBILI:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Actualizar Visibilidad de los niveles");
PersistenciaTanivelEspecialidadTanivelActo per = new PersistenciaTanivelEspecialidadTanivelActo();
Vector v = new Vector();
for (int i = 0; i<3; i++){
TanivelEspecialidad TanivEsp = new TanivelEspecialidad();
TanivEsp.setEspecialidad(Integer.parseInt(request.getParameter("hiddenEspe")));
TanivEsp.setNivel(Integer.parseInt(request.getParameter("hiddenNivel"+(i+1))));
TanivEsp.setVisibilidad(Integer.parseInt(request.getParameter("hiddenVisi"+(i+1))));
v.addElement(TanivEsp);
}
if(per.ActualizarVisibilidad(v,Integer.parseInt(request.getParameter("hiddenEspeS"))))
{
LogTarisan.logger.log(NivelLog.DEBUG, "OK al actualizar la visibilidad de los niveles");
response.sendRedirect("../jsp/adm/mto_niveles.jsp?x=3");
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Error al actualizar la visibilidad de los niveles");
sesion.setAttribute("ERROR", "Error al actualizar visibilidad de los niveles");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_ADM_GES_NIVELES_ACT:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Obtener Actos y niveles de las especialidades");
response.sendRedirect("../jsp/adm/mto_actos.jsp?x=3&especialidad=" + request.getParameter("hiddenEspecialidad")+"&pagina="+ request.getParameter("pagina")+"&hiddenActo="+ request.getParameter("hiddenActo"));
break;
}
case OPC_ADM_GES_ACT_NIVEL_ACTO:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Actualizar Nivel de los actos");
PersistenciaTanivelEspecialidadTanivelActo per = new PersistenciaTanivelEspecialidadTanivelActo();
Vector v = new Vector();
for (int i = 0; i<Integer.parseInt(request.getParameter("nElementos")); i++){
TanivelActo TanivAct = new TanivelActo();
TanivAct.setEspecialidad(Integer.parseInt(request.getParameter("hiddenEspe")));
TanivAct.setActo(Integer.parseInt(request.getParameter("hiddenActo"+(i+1))));
TanivAct.setNivel(Integer.parseInt(request.getParameter("hiddenNivel"+(i+1))));
v.addElement(TanivAct);
}
if(per.ActualizarNivelActo(v))
{
LogTarisan.logger.log(NivelLog.DEBUG, "OK al actualizar el nivel de los actos");
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Error al actualizar el nivel de los actos");
}
response.sendRedirect("../jsp/adm/mto_actos.jsp?x=3&pagina=1");
break;
}
case OPC_ADM_MOSTRAR_LOG:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Devuelve el log de Tarisan");
String nLineas = request.getParameter("NLINEAS");
Integer intSiguiente=0;
Integer intAnterior=0;
Integer intlini=0;
if (request.getParameter("siguiente")!=null){
if (request.getParameter("siguiente")!="")
intSiguiente=Integer.parseInt(request.getParameter("siguiente"));
}
if (request.getParameter("anterior")!=null){
if (request.getParameter("anterior")!="")
intAnterior=Integer.parseInt(request.getParameter("anterior"));
}
if (request.getParameter("lini")!=null){
if (request.getParameter("lini")!="")
intlini=Integer.parseInt(request.getParameter("lini"));
}
String log ="";
/*json = this.mostrarLogJson("/root/apache-tomcat-6.0.20/logs/tarisans.log", 1000);
response.setContentType("application/json");*/
/*log = this.mostrarLogTabla("/root/apache-tomcat-6.0.20/logs/tarisans.log", Integer.parseInt(nLineas), intAnterior, intSiguiente, intlini);*/
log = this.mostrarLogTabla("/var/log/tomcat/tarisans.log", Integer.parseInt(nLineas), intAnterior, intSiguiente, intlini);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(log);
out.close();
break;
}
default:
{
response.sendRedirect("../jsp/adm/lista_usuarios.jsp?x=0");
break;
}
}
}
public String mostrarLogTabla(String archivo, int maxLinMostradas, Integer intAnterior, Integer intSiguiente, Integer intlini) throws FileNotFoundException, IOException {
String tabla = "";
FileReader fr= new FileReader(archivo);
BufferedReader br= new BufferedReader(fr);
String linea=null;
int numLin =0; // Número de líneas del fichero
int linInicial=0; // Primera línea mostrada
int lineaFinal = 0; // Ultima linea mostrada
String strFecha="";
String strHora="";
String strTipo="";
String strLog="";
String estilo = "";
while ((linea=br.readLine())!=null){
numLin++;
}
br.close();
LogTarisan.logger.log(NivelLog.DEBUG, "Número líneas fichero: "+numLin);
LogTarisan.logger.log(NivelLog.DEBUG, "Número máximo de lines a mostrar: "+maxLinMostradas);
// Calculamos primera línea mostrada
linInicial = numLin-maxLinMostradas;
if ((intAnterior == 1) || (intSiguiente == 1)){
linInicial = intlini;
}
lineaFinal = linInicial + maxLinMostradas;
LogTarisan.logger.log(NivelLog.DEBUG, "Linea Inicial: "+linInicial);
// Volvemos a leer mostrando sólo lo requerido
FileReader fr2= new FileReader(archivo);
BufferedReader br2 = new BufferedReader(fr2);
numLin=0; // Línea actual
Collection collection = new ArrayList();
tabla += "<a class=\"enlace\" href=\"https://192.168.2.192/tarisan/servlet/GestorAdministracion?OPCION=9&NLINEAS="+maxLinMostradas+"&anterior=1&lini=1\">Principio</a>";
tabla += "<a class=\"enlace\" href=\"https://192.168.2.192/tarisan/servlet/GestorAdministracion?OPCION=9&NLINEAS="+maxLinMostradas+"&anterior=1&lini="+(linInicial-maxLinMostradas)+"\">Anterior</a>";
tabla += "<a class=\"enlace\" href=\"https://192.168.2.192/tarisan/servlet/GestorAdministracion?OPCION=9&NLINEAS="+maxLinMostradas+"&siguiente=1&lini="+(linInicial+maxLinMostradas)+"\">Siguiente</a>";
tabla += "<a class=\"enlace\" href=\"https://192.168.2.192/tarisan/servlet/GestorAdministracion?OPCION=9&NLINEAS="+maxLinMostradas+"&siguiente=1&lini="+(numLin-maxLinMostradas)+"\">Final</a>";
tabla += "<p>&nbsp;</p>";
tabla += "<table style=\"width:100%\">";
tabla += "<tr>";
tabla += "<td align=\"center\" class=\"cabeceraTabla\">Linea</td>";
tabla += "<td align=\"center\" class=\"cabeceraTabla\">Fecha</td>";
tabla += "<td align=\"center\" class=\"cabeceraTabla\">Hora</td>";
tabla += "<td align=\"center\" class=\"cabeceraTabla\">Tipo</td>";
tabla += "<td align=\"center\" class=\"cabeceraTabla\">Log</td>";
tabla += "</tr>";
while ((linea=br2.readLine())!=null){
// Si el número de líneas a mostrar es superioral número de líneas mostramos todas
if(((numLin>=linInicial) && (numLin<=lineaFinal)) || linInicial<0){
if (linea.length()>=10){
strFecha = linea.substring(0,10);
strHora = linea.substring(11,23);
strTipo = linea.substring(24,29);
strLog = linea.substring(30);
}else{
strFecha = "";
strHora = "";
strTipo = "";
strLog = "";
}
if (numLin % 2 == 0)
{
estilo = "filaB";
}
else
{
estilo = "filaA";
}
if ((strTipo.trim()).compareTo("ERROR")==0){
estilo = "filaError";
}
tabla += "<tr>";
tabla += "<td class=\""+estilo+"\" align=\"center\">"+numLin+"</td>";
tabla += "<td class=\""+estilo+"\" align=\"center\">"+strFecha+"</td>";
tabla += "<td class=\""+estilo+"\" align=\"center\">"+strHora+"</td>";
tabla += "<td class=\""+estilo+"\" align=\"center\">"+strTipo+"</td>";
tabla += "<td class=\""+estilo+"\" align=\"left\">"+strLog+"</td>";
tabla += "</tr>";
}
numLin++;
}
br2.close();
tabla += "</table>";
tabla += "<p>&nbsp;</p>";
tabla += "<a class=\"enlace\" href=\"https://192.168.2.192/tarisan/servlet/GestorAdministracion?OPCION=9&NLINEAS="+maxLinMostradas+"&anterior=1&lini="+(linInicial-maxLinMostradas)+"\">Anterior</a>";
tabla += "<a class=\"enlace\" href=\"https://192.168.2.192/tarisan/servlet/GestorAdministracion?OPCION=9&NLINEAS="+maxLinMostradas+"&siguiente=1&lini="+(linInicial+maxLinMostradas)+"\">Siguiente</a>";
tabla += "<style>";
tabla += "body{background-color:rgb(228, 228, 228);}";
tabla += ".cabeceraTabla{background-color:grey;color:white;font-weight:bold;}";
tabla += ".filaA{background-color:white;}";
tabla += ".filaB{background-color:#EBEBEB;}";
tabla += ".filaError{background-color:#F07777;}";
tabla += ".filaB:hover, .filaA:hover{background-color:#FFE7E7;}";
tabla += ".enlace{text-decoration: none;color: white;font-weight: bold;border: 1px solid !important;background-color: rgb(198, 0, 0);padding: 3px;}";
tabla += ".enlace:hover {background-color:red;color:white;}";
tabla += "</style>";
return tabla;
}
public String mostrarLogJson(String archivo, int maxLinMostradas) throws FileNotFoundException, IOException {
Gson gson = new Gson();
FileReader fr= new FileReader(archivo);
BufferedReader br= new BufferedReader(fr);
String linea=null;
int numLin =0; // Número de líneas del fichero
int linInicial=0; // Primera línea mostrada
while ((linea=br.readLine())!=null){
numLin++;
}
br.close();
LogTarisan.logger.log(NivelLog.DEBUG, "Número líneas fichero: "+numLin);
LogTarisan.logger.log(NivelLog.DEBUG, "Número máximo de lines a mostrar: "+maxLinMostradas);
// Calculamos primera línea mostrada
linInicial = numLin-maxLinMostradas;
LogTarisan.logger.log(NivelLog.DEBUG, "Linea Inicial: "+linInicial);
// Volvemos a leer mostrando sólo lo requerido
FileReader fr2= new FileReader(archivo);
BufferedReader br2 = new BufferedReader(fr2);
numLin=0; // Línea actual
Collection collection = new ArrayList();
while ((linea=br2.readLine())!=null){
// Si el número de líneas a mostrar es superioral número de líneas mostramos todas
if(numLin>=linInicial || linInicial<0){
//System.out.println("Tail:"+linea);
collection.add(numLin);
collection.add(linea);
//String jsonString = gson.toJson(linea);
}
numLin++;
}
String json = gson.toJson(collection);
br2.close();
return json;
}
private TanivelEspecialidad MostrarNivelesEspe(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
TanivelEspecialidad resultado = null;
PersistenciaTanivelEspecialidadTanivelActo per = new PersistenciaTanivelEspecialidadTanivelActo();
//resultado = per.ObtenerNiveles(Integer.parseInt(request.getParameter("especialidad")));
return resultado;
}
private boolean actualizarAutorizacion(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
boolean resultado = false;
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a actualizar la autorizacion: "+request.getParameter("num_aut")+", con la cantidad "+request.getParameter("cantidad"));
PersistenciaTaconaut pertacon = new PersistenciaTaconaut();
long autorizacion = Long.parseLong(request.getParameter("num_aut"));
int acto = Integer.parseInt(request.getParameter("acto"));
int especialidad = Integer.parseInt(request.getParameter("especialidad"));
int cantidad = Integer.parseInt(request.getParameter("cantidad"));
if(pertacon.AutorizacionSinTarjeta(autorizacion))
{
String tarjeta = pertacon.ObtenerTarjeta(autorizacion);
resultado = pertacon.ActualizarCantidadTarjetaAutorizacionADM(autorizacion, acto, especialidad, cantidad, tarjeta);
}
else
resultado = pertacon.ActualizarCantidadAutorizacionADM(autorizacion, acto, especialidad, cantidad);
return resultado;
}
/**
* Actualiza los datos del usuario seleccionado por el administrador.
* @param request Objeto <code>HttpServletRequest</code> que contiene los parámetros enviados desde la página Html.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
* @throws
*/
private void actualizarDatosUsuario(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores = null;
Object[] aCondiciones = null;
StringBuffer strSql = new StringBuffer();
Object nMedico = null;
Object valor = null;
boolean haAccedido = false;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar calCaducidad = Calendar.getInstance();
int intMedicoConectado = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
try
{
nMedico = request.getParameter("medico");
if ((request.getParameter("fecha_ult_acceso") != null) && (request.getParameter("fecha_ult_acceso").trim().compareTo("") != 0))
{
haAccedido = true;
}
if ((request.getParameter("valor_password") != null) && (request.getParameter("valor_password").trim().compareTo("") != 0))
{
aValores = new Object[3];
if (haAccedido)
{
aValores[2] = Utilidades.encripta(request.getParameter("valor_password"), (String)nMedico);
}
else
{
aValores[2] = request.getParameter("valor_password");
}
strSql.append(", PASSWORD = ?");
}
else
{
aValores = new Object[3];
}
valor = sdf.parse(request.getParameter("valor_fecha_modif_clave"));
calCaducidad.setTime((java.util.Date)valor);
calCaducidad.add(Calendar.DATE, -ParametrosConfiguracion.diasCaducidad);
strSql.insert(0, ", FECHA_MODIF_CLAVE = ?");
aValores[2] = new java.sql.Date(calCaducidad.getTime().getTime());
valor = request.getParameter("valor_bloqueo_clave");
/*if ((valor == null) || (((String)valor).toUpperCase().compareTo("S") != 0))
{
valor = "N";
}*/
if (valor.equals("N")){
strSql.insert(0, " BLOQUEO_CLAVE = ?");
strSql.insert(0, "FECHA_ULT_ACCESO = ?,");
aValores[0] = "";
aValores[1] = valor;
} else {
aValores = new Object[2];
strSql.insert(0, " BLOQUEO_CLAVE = ?");
aValores[1] = new java.sql.Date(calCaducidad.getTime().getTime());
aValores[0] = valor;
}
strSql.insert(0, "UPDATE TAMEDICO SET ");
//array condiciones
strSql.append(" , PASSWORD='123' WHERE MEDICO = ? ");
aCondiciones = new Object[1];
aCondiciones[0] = nMedico;
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
PersistenciaTamedico perTamedico = new PersistenciaTamedico();
LogTarisan.logger.log(NivelLog.DEBUG, "--- La sql es esta: "+strSql.toString()+"<<");
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos el ultimo valor del campo correlativo de la tabla tareglog.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
int intUltimoValorCorrelativo = perTareglog.obtenerUltimoValorCorrelativo(intMedicoConectado, tsFechaUltimoAcceso);
perTareglog.insertarLog(intMedicoConectado, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMEDICO", Utilidades.obtenerSentenciaSQL(strSql, aValores, aCondiciones), "", conexion);
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
}
catch (ExcepcionTarisan ex)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
throw (ExcepcionTarisan)ex;
}
catch (Exception ex)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex.getMessage());
throw new ExcepcionTarisan(ex.getMessage());
}
finally
{
//liberamos la conexion
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
}
catch (ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
throw (ExcepcionTarisan)ex;
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
throw new ExcepcionTarisan(ex.getMessage());
}
}
}
@@ -0,0 +1,321 @@
/*
* Created on 22-nov-2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.tarisan.servlets;
import com.tarisan.util.*;
import com.tarisan.control.Constantes;
import com.tarisan.data.Usuario;
import com.tarisan.data.Paciente;
import com.tarisan.log.*;
import com.tarisan.util.Utilidades;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import jakarta.servlet.http.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
//import com.lowagie.text.Chunk;
//import com.lowagie.text.Document;
//import com.lowagie.text.DocumentException;
//import com.lowagie.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import java.util.ArrayList;
//import com.lowagie.text.*;
//import com.lowagie.text.pdf.PdfWriter;
//import com.lowagie.text.pdf.PdfPTable;
import java.io.FileOutputStream;
/**
* @author Roumen
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class GestorImpresion extends HttpServlet {
/** a possible status */
public static final int ACT_INIT = 0;
/** a possible status */
public static final int ACT_REPORT_1 = 1;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doWork(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doWork(request, response);
}
/**
* The actual business logic.
*
* @param requ the request object
* @param resp the response object
* @throws ServletException
* @throws IOException
*/
public void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("Dentro de Servlet: 1");
LogTarisan.logger.log(NivelLog.INFO, "Inicio página de impresion de analitica (imp/impAnalitica.jsp)");
response.setHeader("Expires", "0");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
HttpSession sesion = request.getSession(true);
int opcion = 0;
if (request.getParameter("opcion") != null) {
opcion = Integer.parseInt((String)request.getParameter("opcion"));
System.out.println("opcion: " + opcion);
switch(opcion)
{
case Constantes.OPC_PAC_PRESCRIPCION_ANALITICA:
{
try
{
// Definicion de variables
SimpleDateFormat sdfFormateadorFecha=new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String strMensajeSinElementos="No ha seleccionado ningún acto médico.";
// ArrayList que contedrá las descripciones de analíticas
ArrayList arrayListaElementosPrescripcion = null;
String strAutorizacion = "CSM";
if ((String)request.getAttribute("autorizacion") != null) {
strAutorizacion = (String)request.getAttribute("autorizacion");
System.out.println("Dentro de impAnalitica.jsp: " + strAutorizacion);
}
String strInforme = "INFORME";
if (request.getParameter("informePrescripcion") != null) {
strInforme =(String)request.getParameter("informePrescripcion");
System.out.println("Informe: " + strInforme);
}
// String strInforme = (String)request.getParameter("informe");
String strListaElementosPrescripcion = "";
String strListaElementosPrescripcionAux = "";
if (request.getParameter("listaElementosPrescripcion") != null ) {
// Lista de elementos de Prescripción
strListaElementosPrescripcion = (String)request.getParameter("listaElementosPrescripcion");
System.out.println("1");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
System.out.println("listaElementosPrescripcion original" + strListaElementosPrescripcion);
}
System.out.println("2");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
System.out.println("listaElementosPrescripcion original" + strListaElementosPrescripcion);
strListaElementosPrescripcionAux = strListaElementosPrescripcion.replace('\'', '~');
}
System.out.println("3");
strListaElementosPrescripcion = strListaElementosPrescripcionAux;
System.out.println("4");
System.out.println("listaElementosPrescripcion tras replace " + strListaElementosPrescripcion);
System.out.println("5");
while(strListaElementosPrescripcion.indexOf("~") != -1) {
System.out.println("aaaa");
strListaElementosPrescripcion = strListaElementosPrescripcion.replace('~','\'');
}
System.out.println("6");
System.out.println("listaElementosPrescripcion tras replace " + strListaElementosPrescripcion);
System.out.println("7");
// Vector vElementosPrescripcion = new Vector();
arrayListaElementosPrescripcion = new ArrayList();
System.out.println("8");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
// Lista no vacía
System.out.println("9");
strListaElementosPrescripcion = strListaElementosPrescripcion.substring(strListaElementosPrescripcion.indexOf("¬") + 1);
System.out.println("10");
//Separamos las diferentes determinaciones
int i = 0;
while (strListaElementosPrescripcion.indexOf("¬") != -1) {
System.out.println("BUCLE i: " + i);
//vElementosPrescripcion.add(strListaElementosPrescripcion.substring(0, strListaElementosPrescripcion.indexOf("¬")));
arrayListaElementosPrescripcion.add(strListaElementosPrescripcion.substring(0, strListaElementosPrescripcion.indexOf("¬")));
//System.out.println("11");
strListaElementosPrescripcion = strListaElementosPrescripcion.substring(strListaElementosPrescripcion.indexOf("¬") + 1);
//System.out.println("12");
i++;
}
/*
for (int j=0;j<arrayListaElementosPrescripcion.size();j++) {
System.out.println("Elem: " + (String)arrayListaElementosPrescripcion.get(j));
}
*/
}
}
String strListaCodigoElementos = "";
if (request.getParameter("listaCodigoElementos")!=null) {
strListaCodigoElementos=(String)request.getParameter("listaCodigoElementos");
System.out.println("ListaCodigoElementos" + strListaCodigoElementos);
}
//Creamos el documento
Document document = new Document();
//Fijamos Márgenes
document.setMargins(40, 40, 5, 5);
// we create a writer that listens to the document
String strFile = "../webapps/tarisan/peticiones/" + strAutorizacion + ".pdf";
FileOutputStream foStream = new FileOutputStream(strFile);
PdfWriter.getInstance(document,foStream);
//ByteArrayOutputStream baOS = new
// step 3: we open the document
document.open();
//Definición de tabla
PdfPTable table = new PdfPTable(2); //Numero de columnas
//Fijar anchura de la tabla
table.setWidthPercentage(100);
//Creamos el objeto generador de PDF
Print generadorPDF = new Print();
//AÑADIR CABECERA
table = generadorPDF.anadirCabecera(table, "IMQ");
//AÑADIR MEDICOPRESCRIPTOR
String strMedico = ((Usuario)sesion.getAttribute("USUARIO")).getNombreCab().toString();
String strDireccion = ((Usuario)sesion.getAttribute("USUARIO")).getDireccionCab().toString();
String strEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidadCab().toString();
String strPoblacion = ((Usuario)sesion.getAttribute("USUARIO")).getPoblacionCab();
String strNumColegiado = "Núm.Colegiado: " + ((Usuario)sesion.getAttribute("USUARIO")).getColegiadoCab().toString();
String strTelefono = ((Usuario)sesion.getAttribute("USUARIO")).getTelefonoCab().toString();
table = generadorPDF.anadirMedicoPrescriptor(table, strMedico, strDireccion, strEspecialidad, strPoblacion, strNumColegiado, strTelefono);
//AÑADIR PACIENTE
String strNomPaciente = ((Paciente)sesion.getAttribute("PACIENTE")).getNombre();
String strColectivo = Long.toString( ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo()) + Utilidades.formatearEntero( ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza(), 12, 0);
String strBeneficiario = Integer.toString(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario());
String strPoliza = strColectivo + " " + strBeneficiario;
sdfFormateadorFecha = new SimpleDateFormat("dd/MM/yyyy");
dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
strPoblacion += ", " + sdfFormateadorFecha.format(dtFecha);
table = generadorPDF.anadirPaciente(table, strNomPaciente, strPoliza, "Núm.Autorización: " + strAutorizacion, strPoblacion);
//AÑADIR ANALISIS
table = generadorPDF.anadirAnalisis(table,arrayListaElementosPrescripcion, "IMQ");
//AÑADIR INFORME
//strInforme = strInforme.substring(1000);
table = generadorPDF.anadirInforme(table, strInforme, "IMQ");
//AÑADIR TABLA
table.setHorizontalAlignment(Element.ALIGN_CENTER);
document.add(table);
//CERRAR DOCUMENTO
// step 5: we close the document
document.close();
System.out.println("GestorImpresion antes del forward");
//request.getRequestDispatcher("/jsp/imp/impAnalitica.jsp").forward(request,response);
//response.sendRedirect("../jsp/imp/impAnalitica.jsp");
System.out.println("GestorImpresion despues del forward");
} catch (Exception ex) {
System.out.println("Excepcion1" + ex);
}
break;
}
}
} else {
System.out.println("opcion nula");
}
}
private void htmlHeader(ServletOutputStream out, HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/html; charset=ISO-8859-1");
response.setHeader("Cache-Control", "no-cache");
out.println("<html>");
out.println("<head>");
out
.println("<meta http-equiv='Content-Type' content='text/html;charset=iso-8859-1'>");
out.println("<meta http-equiv='expires' content='0'>");
out.println("<meta http-equiv='cache-control' content='no-cache'>");
out.println("<meta http-equiv='pragma' content='no-cache'>");
out.println("</head>");
out.println("<body>");
}
private void formular(ServletOutputStream out, HttpServletRequest request,HttpServletResponse response, int sub) throws IOException {
out.print("<form method='post' action='");
out.print(request.getRequestURI());
out.print("?action=");
out.print(ACT_INIT);
out.print("&sub=");
out.print(ACT_REPORT_1);
out.println("'>");
out.print("<input type='checkbox' name='preview' value='Y'");
if (request.getParameter("preview") != null)
out.print(" checked ");
out.println(">preview<br>");
out.println("<input type=submit value='Report 1'>");
out.println("</form>");
if (sub != ACT_INIT) {
if (request.getParameter("preview") != null) {
out.println("<script language='JavaScript'>");
out.print("w = window.open(\"");
out.print(request.getRequestURI());
out.print("?action=");
out.print(sub);
out.print("&preview=Y\", \"Printing\", \"width=800,height=450,scrollbars,menubar=yes,resizable=yes\");");
out.println("</script>");
} else {
out.print("<iframe src='");
out.print(request.getRequestURI());
out.print("?action=");
out.print(sub);
out.println("' width='10' height='10' name='pdf_box'>");
}
}
out.println("</body>");
out.println("</html>");
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+435
View File
@@ -0,0 +1,435 @@
/**
* @(#) Login.java
*/
package com.tarisan.servlets;
import com.tarisan.control.*;
import com.tarisan.data.*;
import com.tarisan.excepcion.*;
import com.tarisan.log.*;
import com.tarisan.persistencia.PersistenciaParametros;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
/**
* Login (validación y autenticación) del usuario en la aplicación Tarisan.
* @author <a href="mailto:sistemas@imqnavarra.com">Dpto. Informática</a>.
* @version 1.0, 24/09/2003
*/
public class Login extends HttpServlet implements Constantes
{
/**
* Recepción del método POST requerida por un cliente.<br>
* Comprueba el usuario/password del médico conectado respondiendo de la siguiente manera:<ol>
* <li>Si no existe el usuario redirige a la página de error con el mensaje de usuario no encontrado</li>
* <li>Si existe el usuario:<ul>
* <li>carga el objeto de sesión USUARIO con los datos del médico conectado</li>
* <li>carga el objeto de sesión PERFIL con el correspondiente al médico conectado</li>
* <li>para el perfil de administrador redirige a la página del listado de usuarios del módulo de administración</li>
* <li>para el resto de perfiles redirige a la página de liquidaciones del módulo de gestión de médicos</li>
* </ul></li>
* </ol>
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que recibirá el cliente.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
LogTarisan.logger.log(NivelLog.INFO, " Login.doPost().INI - Empezamos - java 8");
response.setHeader("Expires", "0");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
HttpSession sesion = request.getSession(true);
//Borrar los objetos de sesión del usuario conectado anteriormente
sesion.removeAttribute("USUARIO");
sesion.removeAttribute("PERFIL");
sesion.removeAttribute("MEDICO");
String codigo = request.getParameter("USUARIO");
String clave = request.getParameter("CLAVE");
Usuario usuario = null;
Object objetoSeleccionado = null;
Object objetoSeleccionadoSimulado = null;
String sMensaje = "";
int nCodigo = Integer.parseInt(codigo);
try
{
/*int nCodigo = Integer.parseInt(codigo);*/
sesion.setAttribute("MEDICO", nCodigo);
PersistenciaUsuario perUsu = new PersistenciaUsuario();
PersistenciaTaregmed perRegMed = new PersistenciaTaregmed();
Calendar calHoy = Calendar.getInstance();
try
{
if ((request.getParameter("SIMULADO")!=null)&&(Integer.parseInt(request.getParameter("SIMULADO"))==1)){
objetoSeleccionadoSimulado = perUsu.seleccionarSimulado(nCodigo);
usuario = (Usuario)objetoSeleccionadoSimulado;
sesion.setAttribute("USUARIO", null);
sesion.setAttribute("USUARIO", usuario);
String perfil = this.obtenerPerfilHashtable(usuario.getEspecialidad());
sesion.setAttribute("PERFIL", perfil);
LogTarisan.logger.log(NivelLog.DEBUG, "Perfil: "+perfil);
if (perfil.compareTo(PERFIL_ADMINISTRADOR) == 0)
{
response.sendRedirect("./GestorAdministracion?OPCION=" + OPC_ADM_USUARIO_LISTA);
}
else{
response.sendRedirect("../jsp/med/noticias.jsp?x=19&pagina=1");
}
}else{
objetoSeleccionado = perUsu.seleccionar(nCodigo, clave);
usuario = (Usuario)objetoSeleccionado;
if(this.numeroIntentosExcedido(sesion))
{
//Se ha sobrepasado el número máximo de intentos de conexión en la sesión de usuario
LogTarisan.logger.log(NivelLog.DEBUG, "Login.java llega 81, vamos a bloquear el usuario\n\n\n");
perUsu.bloquearUsuario(nCodigo, calHoy);
sMensaje = this.obtenerMensaje(USUARIO_INTENTOS);
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
}
else
{
//Usuario correcto
LogTarisan.logger.log(NivelLog.INFO, "Usuario " + usuario + " conectado correctamente: "+usuario.getEspecialidad());
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nSession timeout: "+sesion.getMaxInactiveInterval());
//Creación de los objetos de sesión propios
//IDENTIFICACION TIPO DE PERFIL
sesion.setAttribute("USUARIO", null);
sesion.setAttribute("USUARIO", usuario);
//String perfil = this.obtenerPerfil(usuario.getEspecialidad());
String perfil = this.obtenerPerfilHashtable(usuario.getEspecialidad());
sesion.setAttribute("PERFIL", perfil);
sesion.removeAttribute("INTENTOS");
LogTarisan.logger.log(NivelLog.DEBUG, "Perfil: "+perfil);
//Registro del acceso exitoso del usuario a la aplicación
perRegMed.insertar(nCodigo, calHoy, "S");
if (usuario.getFechaUltAcceso() == null)
{
usuario.setFechaUltAcceso(new Timestamp(calHoy.getTime().getTime()));
//Introducción de la nueva clave de usuario por ser primer acceso en la aplicación
LogTarisan.logger.log(NivelLog.INFO, "El Usuario " + usuario + " tiene que cambiar la clave");
response.sendRedirect("../jsp/cambio_clave.jsp" );
}
else if (usuario.getFechaCaducidad() != null)
{
//Actualización de la fecha de último acceso
perUsu.actualizarFechaAcceso(nCodigo, calHoy);
usuario.setFechaUltAcceso(new Timestamp(calHoy.getTime().getTime()));
//Muestra el mensaje de preaviso de caducidad de la clave
SimpleDateFormat sdf = new SimpleDateFormat(PersistenciaParametros.formatoFechas);
StringBuffer mensaje = new StringBuffer();
mensaje.append(this.obtenerMensaje(USUARIO_PREAVISO));
mensaje.append(" ");
mensaje.append(sdf.format(usuario.getFechaCaducidad()));
LogTarisan.logger.log(NivelLog.INFO, mensaje.toString());
sesion.setAttribute("ERROR", mensaje.toString());
response.sendRedirect("./GestorMedicos?OPCION=" + OPC_MED_PREAVISO);
}
else
{
//Actualización de la fecha de último acceso
perUsu.actualizarFechaAcceso(nCodigo, calHoy);
usuario.setFechaUltAcceso(new Timestamp(calHoy.getTime().getTime()));
//Redirección a la página inicial de la aplicación según el perfil del usuario conectado
if (perfil.compareTo(PERFIL_ADMINISTRADOR) == 0)
{
response.sendRedirect("./GestorAdministracion?OPCION=" + OPC_ADM_USUARIO_LISTA);
}
else
{
if(nCodigo==956){
sesion.setAttribute("U", null);
sesion.setAttribute("U", nCodigo);
response.sendRedirect("../jsp/adm/simulado.jsp" );
}else{
//response.sendRedirect("./GestorMedicos?OPCION=" + OPC_MED_LIQUIDACION);
//sMensaje = "<h3 id='idAviso' style='text-align:left'>CAMBIOS A PARTIR DEL 16/03/2015:<br/><br/> - SE ACTUALIZA EL CATÁLOGO DE DETERMINACIONES EN LAS PETICIONES DE ANALiTICAS<br/> - SEGuN INDICACIONES DEL IGUALATORIO ALGUNAS DETERMINACIONES NECESItARaN JUSTIFICAción<br/><br/>CONSULTAR FUNCIONAMIENTO PINCHANDO <a href='/tarisan/Manual_Niveles_Analiticas.pdf' target='blank'>AQUi</a></h3>";
//PersistenciaTamensaje pertamensaje = new PersistenciaTamensaje();
//sMensaje = pertamensaje.obtenerMensaje(69).getMensaje(); //No quitar el html del campo de la bbdd si se quiere guardar el estilo (parpadeante de rojo a negro)
//sesion.setAttribute("AVISO", sMensaje);
//response.sendRedirect("../jsp/pac/gestor.jsp");
response.sendRedirect("../jsp/med/noticias.jsp?x=19&pagina=1");
}
}
}
}
}
}
catch(ClassCastException ex1)
{
//Obtención del mensaje de error correspondiente al intento de login en la aplicación
Integer nMensaje = (Integer)objetoSeleccionado;
if(((nMensaje == USUARIO_INEXISTENTE) || (nMensaje == USUARIO_ERROR_CLAVE)) && (this.numeroIntentosExcedido(sesion)))
{
sMensaje = this.obtenerMensaje(USUARIO_INTENTOS);
try {
perUsu.bloquearUsuario(nCodigo, calHoy);
} catch (ExcepcionTarisan e) {
LogTarisan.logger.log(NivelLog.ERROR, "Excepción en el login de usuario " + codigo + ": " + e);
sesion.setAttribute("ERROR", "");
response.sendRedirect("../jsp/error.jsp" );
}
}
else
{
sMensaje = this.obtenerMensaje(nMensaje);
try
{
if(nMensaje != USUARIO_INEXISTENTE)
//Registro del acceso fallido del usuario a la aplicación
perRegMed.insertar(nCodigo, calHoy, "N");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepción en el login de usuario " + codigo + ": " + ex);
sesion.setAttribute("ERROR", "");
response.sendRedirect("../jsp/error.jsp" );
}
}
sesion.setAttribute("ERROR", sMensaje);
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
response.sendRedirect("../jsp/error.jsp" );
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepción en el login de usuario " + codigo + ": " + ex);
sesion.setAttribute("ERROR", "");
response.sendRedirect("../jsp/error.jsp" );
}
}
catch(NumberFormatException ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepción en el login de usuario " + codigo + ": " + ex);
if(this.numeroIntentosExcedido(sesion))
{
sMensaje = this.obtenerMensaje(USUARIO_INTENTOS);
try {
PersistenciaUsuario perUsu = new PersistenciaUsuario();
Calendar calHoy = Calendar.getInstance();
perUsu.bloquearUsuario(Integer.parseInt(codigo), calHoy);
} catch (ExcepcionTarisan e) {
LogTarisan.logger.log(NivelLog.ERROR, "Excepción en el login de usuario " + codigo + ": " + e);
sesion.setAttribute("ERROR", "");
response.sendRedirect("../jsp/error.jsp" );
}
}
else
{
sMensaje = this.obtenerMensaje(USUARIO_INEXISTENTE);
}
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
}
//}
LogTarisan.logger.log(NivelLog.INFO, "Login.doPost().FIN - java 8");
}
/**
* Calcula el perfil asignado al médico conectado en función de su especialidad.
* @param especialidad El valor de la especialidad del médico.
* @return El código de perfil asignado a la especialidad.
*/
private String obtenerPerfil(int especialidad)
{
String perfil = "";
switch (especialidad)
{
case 0:
{
perfil = PERFIL_ADMINISTRADOR;
break;
}
case 1:
{
perfil = PERFIL_CABECERA;
break;
}
case 4:
{
perfil = PERFIL_ANALISTA;
break;
}
case 17:
{
/*perfil = PERFIL_ANALISTA;*/
perfil = PERFIL_RADIOLOGO;
break;
}
case 19:
{
perfil = PERFIL_DENTISTA;
break;
}
case 37:
{
perfil = PERFIL_REHABPOD;
break;
}
case 50:
{
perfil = PERFIL_ATS;
}
case 53:
{
perfil = PERFIL_REHABPOD;
break;
}
case 70:
{
perfil = PERFIL_ODONTOLOGIA;
break;
}
default:
{
perfil = PERFIL_ESPECIALISTA;
break;
}
}
LogTarisan.logger.log(NivelLog.DEBUG, "A la especialidad:"+especialidad+"le corresponde el perfil:"+perfil);
return perfil;
}
/**
* Calcula el perfil asignado al médico conectado en función de su especialidad
* teniendo en cuenta el fichero de propiedades tarisan.properties
* @param especialidad El valor de la especialidad del médico.
* @return El código de perfil asignado a la especialidad.
*/
private String obtenerPerfilHashtable(int especialidad)
{
String perfil = "";
boolean existe = ParametrosConfiguracion.tablaPerfiles.containsKey(Integer.valueOf(especialidad));
if (existe)
{
perfil = ParametrosConfiguracion.tablaPerfiles.get(Integer.valueOf(especialidad)).toString();
} else {
perfil = Constantes.PERFIL_ESPECIALISTA;
}
LogTarisan.logger.log(NivelLog.DEBUG, " - Existe hastable? - " + existe);
return perfil;
}
/**
* Obtiene el mensaje de error correspondiente al intento de conexión de usuario.
* @param nMensaje Número del mensaje.
* @return El mensaje correspondiente.
*/
private String obtenerMensaje(Integer nMensaje)
{
String mensaje = "";
if(nMensaje.equals(USUARIO_INEXISTENTE))
{
mensaje = "Usuario y password inexistentes, vuelva a intentarlo por favor";
}
else if(nMensaje.equals(USUARIO_ERROR_CLAVE))
{
mensaje = "Usuario y password inexistentes, vuelva a intentarlo por favor";
}
else if(nMensaje.equals(USUARIO_BLOQUEADO))
{
mensaje = "Usuario bloqueado";
}
else if(nMensaje.equals(USUARIO_CADUCADO))
{
mensaje = "Usuario bloqueado, su clave ha caducado";
}
else if(nMensaje.equals(USUARIO_PREAVISO))
{
mensaje = "Por favor cambie su clave de acceso, caduca el día";
}
else if(nMensaje.equals(USUARIO_INACTIVO))
{
mensaje = "Usuario bloqueado por período de inactividad";
}
else if(nMensaje.equals(USUARIO_INTENTOS))
{
mensaje = "Ha sobrepasado el número máximo de intentos de conexión";
}
else
{
mensaje = "Usuario correcto";
}
return mensaje;
}
/**
* Controla el número de intentos fallidos de conexión a la aplicación utilizando un objeto de sesión.
* Si excede al valor del parámetro definido en el fichero de propiedades retornará true, en caso contrario false.
* @param sesion La sesión del usuario conectado
* @return El resultado de la comprobación del número de intentos habidos.
*/
private boolean numeroIntentosExcedido(HttpSession sesion)
{
String strIntentos = (String)sesion.getAttribute("INTENTOS");
int nIntentos = 0;
if(strIntentos != null)
{
nIntentos = Integer.parseInt(strIntentos);
}
sesion.setAttribute("INTENTOS", String.valueOf(++nIntentos));
if (nIntentos > ParametrosConfiguracion.numeroIntentos)
{
return true;
}
else
{
return false;
}
}
}
+52
View File
@@ -0,0 +1,52 @@
/**
* @(#) Logout.java
*/
package com.tarisan.servlets;
import com.tarisan.log.*;
import java.io.IOException;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
/**
* Logout (desconexión) del usuario en la aplicación Tarisan.
* Invalida la sesión del usuario conectado, retornándole a la página de Login.
* @author <a href="mailto:sistemas@imqnavarra.com">Dpto. Informática</a>.
* @version 1.0, 24/09/2003
*/
public class Logout extends HttpServlet
{
/**
* Recepción de la petición de desconexión de la aplicación. Invalida la sesión.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que recibirá el cliente.
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
LogTarisan.logger.log(NivelLog.INFO, "Logout.service().INI");
response.setHeader("Expires", "0");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
HttpSession sesion = request.getSession(true);
if(sesion.isNew())
{
LogTarisan.logger.log(NivelLog.DEBUG, "Sesión no iniciada");
response.sendRedirect("../html/login.html");
}
else
{
sesion.invalidate();
LogTarisan.logger.log(NivelLog.DEBUG, "Desconexión de Tarisan");
response.sendRedirect("../html/login.html");
}
LogTarisan.logger.log(NivelLog.INFO, "Logout.service().FIN");
}
}
+89
View File
@@ -0,0 +1,89 @@
/**
* @(#) Start.java
*/
package com.tarisan.servlets;
import com.tarisan.control.ParametrosConfiguracion;
import com.tarisan.log.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Enumeration;
import java.util.Properties;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import com.tarisan.util.*;
/**
* Servlet de arranque de la aplicación Tarisan.
* @author <a href="mailto:sistemas@imqnavarra.com">Dpto. Informática</a>.
* @version 1.0, 24/09/2003
*/
public class Start extends HttpServlet
{
ServletContext sc = null;
/**
* Inicializa el servlet.
* @param config Entorno de configuración del servlet: objeto <code>ServletConfig</code>.
*/
public void init(ServletConfig config) throws ServletException
{
System.out.println("\n\n\n" );
System.out.println("**************************** TARISAN - Start.init() ****************************" );
sc = config.getServletContext();
System.out.println("Directorio de trabajo de Tarisan:" + sc.getRealPath("/"));
System.out.println("Ruta del log: " + LogTarisan.getPathFichero());
try
{
ParametrosConfiguracion.cargarPropiedades();
System.out.println(" Inicio OK de la aplicación Tarisan - Start.init().Parámetros configurados");
LogTarisan.logger.log(NivelLog.INFO, "Inicio OK de la aplicación Tarisan");
}
catch (Exception e)
{
System.out.println(" Inicio KO de la aplicación Tarisan - Start.init().Exception: " + e);
LogTarisan.logger.log(NivelLog.ERROR, "Inicio KO de la aplicación Tarisan, Exception: " + e);
}
}
/**
* Recepción del método GET requerida por un cliente.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que recibirá el cliente.
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
LogTarisan.logger.log(NivelLog.INFO, "Start.doGet().INI");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println ("Properties");
Properties props = System.getProperties();
Enumeration keys = props.keys();
while (keys.hasMoreElements())
{
Object key = keys.nextElement ();
out.println("key [" + key + "] element [" + props.get (key) + "]");
System.out.println("key [" + key + "] element [" + props.get (key) + "]");
}
out.println("Using classpath:");
out.println(System.getProperty("java.class.path").replace(File.pathSeparatorChar, '\n'));
out.println("ServletContext's realpath of \"/\":");
out.println("\t" + sc.getRealPath("/"));
out.println("Using userdir:");
out.println("\t" + System.getProperty("user.dir"));
out.flush();
LogTarisan.logger.log(NivelLog.INFO, "Start.doGet().FIN");
}
}
@@ -0,0 +1,477 @@
package com.tarisan.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Vector;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import com.tarisan.control.Constantes;
import com.tarisan.control.Paginacion;
import com.tarisan.control.ParametrosConfiguracion;
import com.tarisan.control.PersistenciaPaciente;
import com.tarisan.control.PersistenciaTamedico;
import com.tarisan.control.PersistenciaTapolfac;
import com.tarisan.data.Paciente;
import com.tarisan.data.Tamedico;
import com.tarisan.data.Tarjeta;
import com.tarisan.data.Ttactmed;
import com.tarisan.data.Usuario;
import com.tarisan.excepcion.ExcepcionTarisan;
import com.tarisan.log.LogTarisan;
import com.tarisan.log.NivelLog;
import com.tarisan.util.Utilidades;
public class WebServiceEntidad extends HttpServlet
{
public void dogET(HttpServletRequest req, HttpServletResponse res) throws IOException
{
this.doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException
{
Integer terminal = -1;
Integer acto = -1;
Integer especialidad = -1;
String tarjeta = null;
String xml = "";
if (req.getParameter("medico") != null) {
terminal = Integer.parseInt(req.getParameter("medico"));
}
if (req.getParameter("acto") != null) {
acto = Integer.parseInt(req.getParameter("acto"));
}
if (req.getParameter("tarjeta") != null) {
tarjeta = req.getParameter("tarjeta");
}
if (req.getParameter("especialidad") != null) {
especialidad = Integer.parseInt(req.getParameter("especialidad"));
}
xml = this.responder(req, res, tarjeta, terminal, acto, especialidad);
res.setContentType("text/xml");
PrintWriter out = res.getWriter();
out.println(xml);
out.close();
}
public String responder(HttpServletRequest req, HttpServletResponse res, String valorTarjeta, Integer terminal, Integer acto, Integer especialidad) throws IOException
{
/*
* TARJETA_VALIDA = 0;
* TARJETA_CADUCADA = 1;
* TARJETA_BAJA = 2;
* TARJETA_SUSPENSO = 3;
* ACTO NO PRESCRIBIBLE = 4;
* ESPECIALIDAD NO PERMITIDA = 5;
* ACTO PRESCRIBILBLE = 6;
*/
String xmlRespuesta = "";
String mensajeRespuesta = "DENEGADA";
long codigoAut = 0;
String descripcionCodigoRespuesta = "";
Integer codigoRespuesta = -1; // ERROR la tarjeta no es nuestra
Calendar fec = Calendar.getInstance();
Timestamp fecha = new Timestamp(fec.getTimeInMillis());
boolean esNuestra = false;
Paciente paciente = new Paciente();
Tarjeta tarjeta = new Tarjeta();
try {
esNuestra = this.tarjetaNuestra(valorTarjeta);
if(esNuestra){
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - La tarjeta es nuestra. valorTarjeta.substring(2,8)->"+valorTarjeta.substring(2,8));
String sMensaje="";
tarjeta = GestorPacientes.parsearTarjeta_pistas1_2(valorTarjeta);
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - Se han cargado los datos bien. tarjeta: "+tarjeta.getTarjeta()+", contrato: "+tarjeta.getContrato()+", colectivo: "+tarjeta.getColectivo()+", poliza: "+tarjeta.getPoliza()+", orden"+tarjeta.getBeneficiario()+", entidad_chipcard: "+tarjeta.getEntidadChipcard()+"...");
if(tarjeta.getValida() && tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_propios)==0)
{
PersistenciaPaciente per = new PersistenciaPaciente();
Object objetoSeleccionado = null;
try
{
objetoSeleccionado = per.seleccionarColPolOrd(tarjeta, terminal);
paciente = (Paciente)objetoSeleccionado;
LogTarisan.logger.log(NivelLog.INFO, "WebServiceEntidad - Tarjeta de paciente válida: " + tarjeta);
LogTarisan.logger.log(NivelLog.INFO, "WebServiceEntidad - Paciente: " + paciente.getNombre());
paciente.setDesplazado(ParametrosConfiguracion.bin_chipcard_propios);
Integer contrato = paciente.getTarjeta().getContrato();
Long colectivo = paciente.getTarjeta().getColectivo();
Long poliza = paciente.getTarjeta().getPoliza();
Integer tarifa = 0;
if (this.especialidadPermitida(especialidad)){
if (this.ActoPrescribible(especialidad, contrato, colectivo, poliza, tarifa, acto)){
codigoRespuesta = 6; // OK acto prescribilbe
}else{
codigoRespuesta = 4; // EROR acto no cubierto
}
}else{
codigoRespuesta = 5; // ERROR especialidad no permitida
}
}
catch(ClassCastException ex)
{
Integer nMensaje = (Integer)objetoSeleccionado;
sMensaje = GestorPacientes.obtenerMensaje(nMensaje);
codigoRespuesta = nMensaje;
LogTarisan.logger.log(NivelLog.INFO, "WebServiceEntidad - ERROR - "+sMensaje);
//res.sendRedirect("../jsp/error.jsp" );
}
}
}else{
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - ERROR - La tarjeta NO es nuestra. valorTarjeta.substring(2,8)->"+valorTarjeta.substring(2,8));
}
} catch (ExcepcionTarisan e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//GENERAMOS EN XML COMO STRING
if (codigoRespuesta==6){
mensajeRespuesta = "AUTORIZADA";
}
codigoAut = this.obtenerCodigoAut();
descripcionCodigoRespuesta =this.obtenerMensajeRespuesta(codigoRespuesta);
xmlRespuesta = "<xml version=\"1.0\" encoding=\"UTF-8\">"+
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+
"<soapenv:Body>"+
"<requestService xmlns=\"https://tarisan.imqnavarra.com/tarisan/servlet/WebServiceEntidad\">"+
"<ObjetoRespuesta>"+
"<Respuesta>"+
"<CodigoRespuesta>"+
codigoRespuesta+
"</CodigoRespuesta>"+
"<MensajeRespuesta>"+
mensajeRespuesta+
"</MensajeRespuesta>"+
"<DescripcionRespuesta>"+
descripcionCodigoRespuesta+
"</DescripcionRespuesta>"+
"<Asegurado>"+
"<Nombre>"+
paciente.getNombre()+
"</Nombre>"+
"<LecturaTarjeta>"+
valorTarjeta+
"</LecturaTarjeta>"+
"</Asegurado>"+
"<Autorizacion>"+
"<CodAut>"+
codigoAut+
"</CodAut>"+
"<EspeAut>"+
especialidad+
"</EspeAut>"+
"<ActoAut>"+
acto+
"</ActoAut>"+
"<FechaAut>"+
fecha+
"</FechaAut>"+
"</Autorizacion>"+
"<Terminal>"+
terminal+
"</Terminal>"+
"</Respuesta>"+
"</ObjetoRespuesta>"+
"</requestService>"+
"</soapenv:Body>"+
"</soapenv:Envelope> "+
"</xml>";
insertarPeticion(codigoAut, terminal, especialidad, acto, tarjeta.getTarjetaDesplazado());
insertarMovimiento(codigoAut, tarjeta.getTarjetaDesplazado(), mensajeRespuesta, descripcionCodigoRespuesta, terminal, '"'+xmlRespuesta+'"', especialidad, acto);
return xmlRespuesta;
}
private boolean tarjetaNuestra(String valorTarjeta) throws ExcepcionTarisan, IOException{
boolean resultado = false;
try{
if(valorTarjeta.contains(ParametrosConfiguracion.bin_chipcard_propios)){
resultado = true;
}
}
catch(Exception ex){
throw new ExcepcionTarisan(ex.toString());
}
return resultado;
}
private boolean especialidadPermitida(Integer especialidad){
boolean resp = false;
String descripcion = "";
try
{
String sqlSelect = "select * from wsespecialidad where especialidad="+especialidad;
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, sqlSelect);
if(rs.next())
{
resp = true;
descripcion = rs.getString("DESCRIPCION");
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - OK - La especialidad seleccionada es: "+descripcion);
}else{
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - ERROR - Especialidad("+especialidad+") no permitida");
}
rs.close();
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
catch (ExcepcionTarisan et) {
et.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return resp;
}
public boolean ActoPrescribible(int especialidad, int contratoPoliza, long colectivo, long poliza, int tarifa, Integer acto) throws ExcepcionTarisan
{
boolean resultado = false;
StringBuffer strSql = new StringBuffer();
Object[] aCondiciones = null;
try
{
//Preparar SELECT
strSql.append("SELECT TTACTMED.DESCRIPCION, TTACTMED.ACTO, TATARIFA.IMPORTE AS PRECIO");
strSql.append(" FROM TTACTMED, TATARIFA");
strSql.append(" WHERE TTACTMED.ACTO = TATARIFA.ACTO");
strSql.append(" AND TTACTMED.ESPECIALIDAD = TATARIFA.ESPECIALIDAD");
strSql.append(" AND TATARIFA.TARIFA = ?");
strSql.append(" AND TATARIFA.IMPORTE > 0");
strSql.append(" AND TTACTMED.ESPECIALIDAD = ?");
strSql.append(" AND TTACTMED.AUTOPRESCRIPCION = 'S'");
strSql.append(" AND TTACTMED.ACTO <> ?");
strSql.append(" AND TTACTMED.ACTO = ?");
strSql.append(" AND TTACTMED.ACTO IN");
//SUBSELECT
//INCLUIDOS EN TADERPOL
strSql.append(" (");
strSql.append(" SELECT ACTO FROM TADERPOL WHERE TADERPOL.COLECTIVO = ? AND TADERPOL.POLIZA = ? AND TADERPOL.ESPECIALIDAD = ? AND EXCLUIDO = 0");
strSql.append(" UNION");
//INCLUIDOS EN TADERCOL NO EXCLUIDOS EN TADERPOL
strSql.append(" SELECT ACTO FROM TADERCOL WHERE TADERCOL.COLECTIVO = ? AND TADERCOL.ESPECIALIDAD = ? AND EXCLUIDO = 0 AND ACTO NOT IN");
//EXCLUIDOS EN TADERPOL
strSql.append(" (SELECT ACTO FROM TADERPOL WHERE TADERPOL.COLECTIVO = ? AND TADERPOL.POLIZA = ? AND TADERPOL.ESPECIALIDAD = ? AND EXCLUIDO = 1)");
strSql.append(" UNION");
//INCLUIDOS EN TADERCAC Y NO EXCLUIDOS EN TADERCOL Y TADERPOL
strSql.append(" SELECT ACTO FROM TADERCAC WHERE TADERCAC.CONTRATO = ? AND TADERCAC.ESPECIALIDAD = ? AND EXCLUIDO = 0 AND ACTO NOT IN");
//EXCLUIDOS DE TADERCOL Y TADERPOL
//EXCLUIDOS EN TADERPOL
strSql.append(" (SELECT ACTO FROM TADERPOL WHERE TADERPOL.COLECTIVO = ? AND TADERPOL.POLIZA = ? AND TADERPOL.ESPECIALIDAD = ? AND EXCLUIDO = 1");
strSql.append(" UNION");
//EXCLUIDOS EN TADERCOL NO INCLUIDOS EN TADERPOL
strSql.append(" SELECT ACTO FROM TADERCOL WHERE TADERCOL.COLECTIVO = ? AND TADERCOL.ESPECIALIDAD = ? AND EXCLUIDO = 1 AND ACTO NOT IN");
//EXCLUIDOS EN TADERPOL
strSql.append(" (SELECT ACTO FROM TADERPOL WHERE TADERPOL.COLECTIVO = ? AND TADERPOL.POLIZA = ? AND TADERPOL.ESPECIALIDAD = ? AND EXCLUIDO = 0)");
strSql.append(" )");
strSql.append(" )");
aCondiciones = new Object[22];
//Preparar condiciones
aCondiciones[0] = Integer.valueOf(tarifa);
aCondiciones[1] = Integer.valueOf(especialidad);
aCondiciones[2] = Integer.valueOf(993999);
aCondiciones[3] = Integer.valueOf(acto);
aCondiciones[4] = Long.valueOf(colectivo);
aCondiciones[5] = Double.valueOf(poliza);
aCondiciones[6] = Integer.valueOf(especialidad);
aCondiciones[7] = Long.valueOf(colectivo);
aCondiciones[8] = Integer.valueOf(especialidad);
aCondiciones[9] = Long.valueOf(colectivo);
aCondiciones[10] = Double.valueOf(poliza);
aCondiciones[11] = Integer.valueOf(especialidad);
aCondiciones[12] = Integer.valueOf(contratoPoliza);
aCondiciones[13] = Integer.valueOf(especialidad);
aCondiciones[14] = Long.valueOf(colectivo);
aCondiciones[15] = Double.valueOf(poliza);
aCondiciones[16] = Integer.valueOf(especialidad);
aCondiciones[17] = Long.valueOf(colectivo);
aCondiciones[18] = Integer.valueOf(especialidad);
aCondiciones[19] = Long.valueOf(colectivo);
aCondiciones[20] = Double.valueOf(poliza);
aCondiciones[21] = Integer.valueOf(especialidad);
//Conexión
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
strSql.append(" order by ttactmed.acto");
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, strSql.toString(), aCondiciones);
//Rellenamos en vector
if(rs.next())
{
resultado = true;
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - OK - Acto("+acto+") para la especialidad("+especialidad+") permitido");
}else{
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - ERROR - El acto("+acto+") para la especialidad("+especialidad+") NO está permitido");
}
//Cerrar ResultSet
rs.close();
//Liberar Conexión
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
catch (ExcepcionTarisan sqle)
{
LogTarisan.logger.log(NivelLog.ERROR, "WebServiceEntidad - ActoPrescribible - Error en la selección de TTACTMED: " + Utilidades.obtenerSentenciaSQL(strSql, null, aCondiciones) );
throw (ExcepcionTarisan)sqle;
}
catch(SQLException sqle)
{
LogTarisan.logger.log(NivelLog.ERROR, "WebServiceEntidad - ActoPrescribible - Error en la selección de TTACTMED: " + Utilidades.obtenerSentenciaSQL(strSql, null, aCondiciones) );
throw new ExcepcionTarisan(sqle.getMessage());
}
catch(Exception sqle)
{
LogTarisan.logger.log(NivelLog.ERROR, "WebServiceEntidad - ActoPrescribible - Error en la selección de TTACTMED: " + Utilidades.obtenerSentenciaSQL(strSql, null, aCondiciones) );
throw new ExcepcionTarisan(sqle.getMessage());
}
catch(Throwable sqle)
{
LogTarisan.logger.log(NivelLog.ERROR, "WebServiceEntidad - ActoPrescribible - Error en la selección de TTACTMED: " + sqle + " (" + strSql.toString() + ")");
throw new ExcepcionTarisan(sqle.getMessage());
}
return resultado;
}
private Long obtenerCodigoAut(){
long codigoAut = 0;
try
{
String sqlSelect = "SELECT autorizacion_ws.nextval as auto FROM DUAL";
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, sqlSelect);
if(rs.next())
{
codigoAut = rs.getLong("auto");
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - OK - El código del movimiento es: "+codigoAut);
}else{
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - ERROR - Erro al obtener el código del movimiento");
}
rs.close();
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
catch (ExcepcionTarisan et) {
et.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return codigoAut;
}
private String obtenerMensajeRespuesta(Integer codigoRespuesta){
String mensaje = "";
try
{
String sqlSelect = "select DESCRIPCION from wsmensajes where codigo="+codigoRespuesta;
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, sqlSelect);
if(rs.next())
{
mensaje = rs.getString("DESCRIPCION");
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - OK - El mensaje para el codigo("+codigoRespuesta+") es: "+mensaje);
}else{
LogTarisan.logger.log(NivelLog.DEBUG, "WebServiceEntidad - ERROR - Error al obtener el mensaje de respuesta: " +sqlSelect);
}
rs.close();
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
catch (ExcepcionTarisan et) {
et.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return mensaje;
}
private void insertarPeticion(Long autorizacion, Integer medico, Integer especialidad, Integer acto, String tarjeta_chipcard)
{
String sqlInsert = "";
Object[] aValores = new Object[5];
try {
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
sqlInsert = "Insert into wspeticiones (autorizacion, medico, especialidad, acto, tarjeta_chipcard, fecha_hora) values (?, ?, ?, ?, ?, sysdate)";
aValores[0]=Long.valueOf(autorizacion);
aValores[1]=Integer.valueOf(medico);
aValores[2]=Integer.valueOf(especialidad);
aValores[3]=Integer.valueOf(acto);
aValores[4]=new String(tarjeta_chipcard);
ParametrosConfiguracion.dataStore.insertar(sqlInsert, aValores, conexion);
LogTarisan.logger.log(NivelLog.DEBUG, "WebService - OK - Peticion insertada correctamente: "+sqlInsert);
} catch (ExcepcionTarisan e) {
LogTarisan.logger.log(NivelLog.ERROR, "WebService - ERROR - Error al insertar el registro de wspeticiones: " +sqlInsert);
}
}
private void insertarMovimiento(Long autorizacion, String tarjeta, String respuesta, String mensaje, Integer terminal, String xml, Integer especialidad, Integer acto)
{
String sqlInsert = "";
Object[] aValores = new Object[8];
try {
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
sqlInsert = "Insert into wsmovimientos (autorizacion, tarjeta, respuesta, mensaje, terminal, xml, especialidad, acto, fecha_hora) values (?, ?, ?, ?, ?, ?, ?, ?, SYSDATE)";
aValores[0]=Long.valueOf(autorizacion);
aValores[1]=new String(tarjeta);
aValores[2]=new String(respuesta);
aValores[3]=new String(mensaje);
aValores[4]=Integer.valueOf(terminal);
aValores[5]=new String(xml);
aValores[6]=Integer.valueOf(especialidad);
aValores[7]=Integer.valueOf(acto);
ParametrosConfiguracion.dataStore.insertar(sqlInsert, aValores, conexion);
LogTarisan.logger.log(NivelLog.DEBUG, "WebService - OK - Movimiento insertado correctamente: "+sqlInsert);
} catch (ExcepcionTarisan e) {
LogTarisan.logger.log(NivelLog.ERROR, "WebService - ERROR - Error al insertar el registro de wsmovimientos: " +sqlInsert);
}
}
}
@@ -0,0 +1,553 @@
package com.tarisan.servlets;
import com.tarisan.log.LogTarisan;
import com.tarisan.log.NivelLog;
import com.tarisan.util.DES;
// import com.tarisan.persistencia.DataStore;
// import com.tarisan.persistencia.PersistenciaParametros;
// import com.tarisan.util.XML2PDF;
//import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
// import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
// import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
// import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
// import java.util.Enumeration;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
// import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
//import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
// import org.apache.log4j.Logger;
import com.tarisan.control.*;
import com.tarisan.data.Usuario;
import com.tarisan.excepcion.ExcepcionTarisan;
public class resultados_analisis extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
HttpSession sesion = req.getSession(true);
if ((sesion.isNew()) || (sesion.getAttribute("USUARIO") == null))
{
LogTarisan.logger.log(NivelLog.INFO, "Sesión invalidada");
try {
res.sendRedirect(req.getContextPath() + "/html/login.html");
} catch (IOException e) {
LogTarisan.logger.log(NivelLog.ERROR, "Sesión invalidada. Error: " + e.toString());
}
}
/*for (Enumeration e = sesion.getAttributeNames(); e.hasMoreElements(); ) {
String atrib = (String)e.nextElement();
System.out.println("Nombre: " + atrib);
System.out.println(". Valor: " + sesion.getAttribute(atrib) + ".");
}*/
//System.out.println("Médico: " + req.getParameter("solicitante"));
String peticion_izasa = new String();
String nombrePDF = "";
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();
DES encrypter = new DES(strMedico);
nombrePDF = req.getParameter("requestID");
nombrePDF = encrypter.decrypt(nombrePDF);
try
{
if ((req.getParameter("borrarPDF")!=null) && (req.getParameter("borrarPDF").compareTo("1")==0)){ // Se ha pulsado en Regenenerar. Borramos el pdf
/*File fichero = new File(ParametrosConfiguracion.ruta_pdf_resultados_analiticas + req.getParameter("requestID") + ".pdf");*/
File fichero = new File(ParametrosConfiguracion.ruta_pdf_resultados_analiticas + nombrePDF + ".pdf");
if(fichero.exists())
{
if (fichero.delete())
LogTarisan.logger.log(NivelLog.DEBUG, "El fichero ha sido borrado satisfactoriamente: "+fichero);
else
LogTarisan.logger.log(NivelLog.DEBUG, "El fichero no puede ser borrado: "+fichero);
}else{
/*fichero = new File(ParametrosConfiguracion.ruta_pdf_resultados_analiticas + req.getParameter("requestID") + ".PDF");*/
fichero = new File(ParametrosConfiguracion.ruta_pdf_resultados_analiticas + nombrePDF + ".PDF");
if(fichero.exists())
{
if (fichero.delete())
LogTarisan.logger.log(NivelLog.DEBUG, "El fichero ha sido borrado satisfactoriamente: "+fichero);
else
LogTarisan.logger.log(NivelLog.DEBUG, "El fichero no puede ser borrado: "+fichero);
}
}
}
/*String strSql = new String("select requestid from mg.request where requestlabel= " + req.getParameter("requestID"));*/
String strSql = new String("select requestid from mg.request where requestlabel= " + nombrePDF);
//String strSql = new String("select requestid from mg.request where requestlabel= " + -5);
Connection conexion_izasa = ParametrosConfiguracion.dataStore.obtenerConexion();
Statement st = conexion_izasa.prepareStatement(strSql);
ResultSet rs = st.executeQuery(strSql);
while (rs.next()) {
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 76");
peticion_izasa = rs.getString("requestid");
/*peticion_izasa = nombrePDF;*/
/*System.out.println("requestid izasa = " + rs.getString("requestid"));
System.out.println("peticion_izasa.length() = " + peticion_izasa.length());
*/
}
rs.close();
ParametrosConfiguracion.dataStore.liberarConexion(conexion_izasa);
}
catch (Exception e)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Error al obtener el requestid de izasa"+e.toString());
System.out.println("Error al obtener el requestid de izasa: ");
e.printStackTrace();
} catch (ExcepcionTarisan e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//if (peticion_izasa.length() > 0) {
/*String ruta = ParametrosConfiguracion.ruta_pdf_resultados;*/
String ruta = ParametrosConfiguracion.ruta_pdf_resultados_analiticas;
String sisop = System.getProperty("os.name");
String slash = "\\";
if (sisop.contains("indows"))
{
slash = "\\";
}
else {
slash = "/";
}
/*File pdf = new File(ruta + slash + req.getParameter("requestID") + ".pdf");*/
File pdf = new File(ruta + slash + nombrePDF + ".pdf");
if (!pdf.exists())
{
LogTarisan.logger.log(NivelLog.INFO, "El pdf no existe");
/*PDF_izasa("https://192.168.2.102/modulab/servlet/GetPDFReportNoRedirectServlet?username=admin&password=service&requestID=" + peticion_izasa, "HTTPS", req.getParameter("requestID"));
LogTarisan.logger.log(NivelLog.INFO, "Llega a 101. Peticion_izasa="+peticion_izasa+"requestid = "+req.getParameter("requestID"));*/
//PDF_izasa("https://192.168.2.102/modulab/servlet/GetPDFReportNoRedirectServlet?username=admin&password=service&requestID=" + peticion_izasa, "HTTPS", nombrePDF);
/*if (peticion_izasa.compareTo("")!=0){
PDF_izasa("https://192.168.2.102/modulab/servlet/GetPDFReportNoRedirectServlet?username=admin&password=service&requestID=" + peticion_izasa, "HTTPS", nombrePDF);
LogTarisan.logger.log(NivelLog.INFO, "Peticion_izasa="+peticion_izasa+"requestid = "+nombrePDF);
}else{
PDF_megalab("http://192.168.2.104/Sigloweb?accion=informe&usr=admin&pass=aHzQ9wHJNA&xdemo4=" + nombrePDF, "HTTP", nombrePDF);
LogTarisan.logger.log(NivelLog.INFO, "Peticion_megalab="+nombrePDF+"requestid = "+nombrePDF);
}*/
PDF_megalab("http://192.168.2.104/Sigloweb?accion=informe&usr=admin&pass=aHzQ9wHJNA&xdemo4=" + nombrePDF, "HTTP", nombrePDF);
LogTarisan.logger.log(NivelLog.INFO, "Peticion_megalab="+nombrePDF+"requestid = "+nombrePDF);
//LogTarisan.logger.log(NivelLog.INFO, "Llega a 101. Peticion_izasa="+peticion_izasa+"requestid = "+nombrePDF);
//https://192.168.2.102/modulab/servlet/GetPDFReportServlet?username=admin&password=service&requestID=" + String(requestID))
//conexionPOST("https://192.168.2.102/modulab/servlet/GetXMLRequestServlet?username=admin&password=service&requestID=" + peticion_izasa, "HTTPS");
//XML2PDF.transformar(peticion_izasa + ".xml", "resultados_izasa.xsl", req.getParameter("requestID") + ".pdf");
}
else
{
LogTarisan.logger.log(NivelLog.INFO, "El pdf ya existe, no hay que crearlo: "+ruta + slash + nombrePDF + ".pdf");
}
LogTarisan.logger.log(NivelLog.INFO, "Vamos a mostrar el pdf");
//ServletOutputStream stream = null;
//BufferedInputStream buf = null;
try {
/*
stream = res.getOutputStream();
res.setContentType("application/pdf");
res.setContentLength((int)pdf.length());
FileInputStream input = new FileInputStream(pdf);
buf = new BufferedInputStream(input);
int readBytes = 0;
while ((readBytes = buf.read()) != -1) {
stream.write(readBytes);
}
if (stream != null)
stream.close();
if (buf == null) return; buf.close();
*/
/*sesion.setAttribute("fichero", req.getParameter("requestID") + ".pdf");
LogTarisan.logger.log(NivelLog.DEBUG, "Setattribute.fichero: "+ req.getParameter("requestID") + ".pdf");*/
sesion.setAttribute("fichero", nombrePDF + ".pdf");
LogTarisan.logger.log(NivelLog.DEBUG, "Setattribute.fichero: "+ nombrePDF + ".pdf");
/*res.sendRedirect(req.getContextPath()+"/jsp/ver_pdf.jsp");*/
/*String rutaPDF = "";
rutaPDF = ParametrosConfiguracion.ruta_pdf_resultados_analiticas + req.getParameter("requestID") + ".pdf"; */
/*req.getRequestDispatcher("/servlet/GestorPacientes?OPCION=34&nombrePDF="+req.getParameter("requestID") + ".pdf&tipo=1").forward(req, res);*/
/* String nombrePDF = "";
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();
DES encrypter = new DES(strMedico);
nombrePDF = req.getParameter("requestID");
nombrePDF = encrypter.encrypt(nombrePDF); */
req.getRequestDispatcher("/servlet/GestorPacientes?OPCION=34&nombrePDF="+req.getParameter("requestID") + "&tipo=1").forward(req, res);
/*req.getRequestDispatcher("/servlet/GestorPacientes?OPCION=34&nombrePDF="+nombrePDF + "&tipo=1").forward(req, res);*/
}
catch (Exception ioe) {
LogTarisan.logger.log(NivelLog.DEBUG, "Error al generar el pdf "+ ioe.toString());
System.out.println("Error al generar el PDF" + ioe.toString());
}
/* }
else
{
try
{
ServletOutputStream stream = null;
BufferedInputStream buf = null;
stream = res.getOutputStream();
res.setContentType("text/html");
String contenido = new String();
contenido = "<head><title>No hay resultados</title></head><body><div align=\"center\">No se han encontrado resultados para la petici&oacute;n indicada </div></body>";
res.setContentLength(contenido.length());
stream.write(contenido.getBytes());
stream.close();
}
catch (Exception e)
{
System.out.println("Error al devolver el html sin resultados " + e.toString());
}
}
*/
}
public static void conexionPOST(String request, String protocolo, String ruta)
{
BufferedReader rd = null;
try
{
URL url = new URL(request);
if (protocolo.equals("HTTPS")) {
url = new URL(request);
HttpsURLConnection.setFollowRedirects(true);
HttpsURLConnection conn1 = (HttpsURLConnection)url.openConnection();
conn1.setDoOutput(true);
conn1.setHostnameVerifier(new NullHostnameVerifier());
conn1.setInstanceFollowRedirects(true);
OutputStream os = conn1.getOutputStream();
os.write(1);
os.close();
rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
String requestID = new String();
requestID = request.substring(request.lastIndexOf("requestID=") + 10);
String sisop = System.getProperty("os.name");
String slash = "\\";
if (sisop.contains("indows"))
{
slash = "\\";
}
else {
slash = "/";
}
FileOutputStream fileOutput = new FileOutputStream(ruta + slash + requestID + ".xml");
BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput);
byte[] array = new byte[1000];
int leidos = conn1.getInputStream().read(array);
while (leidos > 0)
{
bufferedOutput.write(array, 0, leidos);
leidos = conn1.getInputStream().read(array);
}
bufferedOutput.close();
System.out.println("Se ha generado el xml en: " + ruta + slash + requestID + ".xml");
} else {
URLConnection conn1 = url.openConnection();
rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
}
}
catch (Exception e)
{
System.out.println("Fallo en web request, " + e.toString());
if (rd != null)
try {
rd.close();
} catch (IOException ex) {
System.out.println("Problema al cerrar el objeto lector");
}
}
finally
{
if (rd != null)
try {
rd.close();
} catch (IOException ex) {
System.out.println("Problema al cerrar el objeto lector");
}
}
}
public static void conexionPOST(String request, String protocolo)
{
BufferedReader rd = null;
try
{
URL url = new URL(request);
if (protocolo.equals("HTTPS")) {
url = new URL(request);
HttpsURLConnection.setFollowRedirects(true);
HttpsURLConnection conn1 = (HttpsURLConnection)url.openConnection();
conn1.setDoOutput(true);
conn1.setHostnameVerifier(new NullHostnameVerifier());
conn1.setInstanceFollowRedirects(true);
OutputStream os = conn1.getOutputStream();
os.write(1);
os.close();
rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
String requestID = new String();
requestID = request.substring(request.lastIndexOf("requestID=") + 10);
String ruta = LogTarisan.getPathFichero();
String sisop = System.getProperty("os.name");
String slash = "\\";
if (sisop.contains("indows"))
{
slash = "\\";
}
else {
slash = "/";
}
FileOutputStream fileOutput = new FileOutputStream(ruta + slash + requestID + ".xml");
BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput);
byte[] array = new byte[1000];
int leidos = conn1.getInputStream().read(array);
while (leidos > 0)
{
bufferedOutput.write(array, 0, leidos);
leidos = conn1.getInputStream().read(array);
}
bufferedOutput.close();
} else {
URLConnection conn1 = url.openConnection();
rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
}
}
catch (Exception e)
{
System.out.println("Fallo en web request, " + e.toString());
if (rd != null)
try {
rd.close();
} catch (IOException ex) {
System.out.println("Problema al cerrar el objeto lector");
}
}
finally
{
if (rd != null)
try {
rd.close();
} catch (IOException ex) {
System.out.println("Problema al cerrar el objeto lector");
}
}
}
private static class DefaultTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public static void PDF_izasa(String request, String protocolo, String peticion_tarisan)
{
BufferedReader rd = null;
LogTarisan.logger.log(NivelLog.INFO, "Entramos en PDF_izasa");
try
{
URL url = new URL(request);
if (protocolo.equals("HTTPS")) {
url = new URL(request);
/*TEST
*
*/
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
/*
* FIN TEST
*/
HttpsURLConnection.setFollowRedirects(true);
HttpsURLConnection conn1 = (HttpsURLConnection)url.openConnection();
conn1.setDoOutput(true);
;
conn1.setHostnameVerifier(new NullHostnameVerifier());
conn1.setInstanceFollowRedirects(true);
OutputStream os = conn1.getOutputStream();
os.write(1);
os.close();
rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
// String requestID = new String();
// requestID = request.substring(request.lastIndexOf("requestID=") + 10);
/*String ruta = ParametrosConfiguracion.ruta_pdf_resultados;*/
String ruta = ParametrosConfiguracion.ruta_pdf_resultados_analiticas;
String sisop = System.getProperty("os.name");
String slash = "\\";
if (sisop.contains("indows"))
{
slash = "\\";
}
else {
slash = "/";
}
FileOutputStream fileOutput = new FileOutputStream(ruta + slash + peticion_tarisan + ".pdf");
BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput);
byte[] array = new byte[1000];
int leidos = conn1.getInputStream().read(array);
while (leidos > 0)
{
bufferedOutput.write(array, 0, leidos);
leidos = conn1.getInputStream().read(array);
}
bufferedOutput.close();
} else {
URLConnection conn1 = url.openConnection();
rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
}
}
catch (Exception e)
{
LogTarisan.logger.log(NivelLog.INFO, "Fallo en web request, " + e.toString());
if (rd != null)
try {
rd.close();
} catch (IOException ex) {
LogTarisan.logger.log(NivelLog.INFO, "Problema al cerrar el objeto lector");
}
}
finally
{
if (rd != null)
try {
rd.close();
} catch (IOException ex) {
LogTarisan.logger.log(NivelLog.INFO, "Problema al cerrar el objeto lector");
}
}
}
public static void PDF_megalab(String request, String protocolo, String peticion_tarisan)
{
BufferedReader rd = null;
LogTarisan.logger.log(NivelLog.INFO, "Entramos en PDF_megalab");
try
{
URL url = new URL(request);
URLConnection conn1 = url.openConnection();
rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
String ruta = ParametrosConfiguracion.ruta_pdf_resultados_analiticas;
String sisop = System.getProperty("os.name");
String slash = "\\";
if (sisop.contains("indows"))
{
slash = "\\";
}
else {
slash = "/";
}
FileOutputStream fileOutput = new FileOutputStream(ruta + slash + peticion_tarisan + ".pdf");
BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput);
byte[] array = new byte[1000];
int leidos = conn1.getInputStream().read(array);
while (leidos > 0)
{
bufferedOutput.write(array, 0, leidos);
leidos = conn1.getInputStream().read(array);
}
bufferedOutput.close();
}
catch (Exception e)
{
LogTarisan.logger.log(NivelLog.INFO, "Fallo en web request, " + e.toString());
if (rd != null)
try {
rd.close();
} catch (IOException ex) {
LogTarisan.logger.log(NivelLog.INFO, "Problema al cerrar el objeto lector");
}
}
finally
{
if (rd != null)
try {
rd.close();
} catch (IOException ex) {
LogTarisan.logger.log(NivelLog.INFO, "Problema al cerrar el objeto lector");
}
}
}
public static class NullHostnameVerifier
implements HostnameVerifier
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}
}