Subiendo el proyecto

parents
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="ejbModule"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry exported="true" kind="lib" path="lib/commons-dbcp2-2.0.jar"/>
<classpathentry exported="true" kind="lib" path="lib/commons-pool2-2.3.jar"/>
<classpathentry exported="true" kind="lib" path="lib/json-io-2.2.29.jar"/>
<classpathentry exported="true" kind="lib" path="lib/junit-4.11.jar"/>
<classpathentry exported="true" kind="lib" path="lib/postgresql-9.1-901-1.jdbc4.jar"/>
<classpathentry exported="true" kind="lib" path="lib/commons-logging-1.2.jar"/>
<classpathentry exported="true" kind="lib" path="lib/javax.mail.jar"/>
<classpathentry exported="true" kind="lib" path="lib/activation.jar"/>
<classpathentry exported="true" kind="lib" path="lib/hornetq-commons.jar"/>
<classpathentry exported="true" kind="lib" path="lib/hornetq-core-client.jar"/>
<classpathentry exported="true" kind="lib" path="lib/hornetq-jms-client.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jboss-ejb-client.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jboss-jms-api_1.1_spec.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jboss-logging.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jboss-marshalling-river.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jboss-marshalling.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jboss-remote-naming.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jboss-remoting.jar"/>
<classpathentry exported="true" kind="lib" path="lib/netty.jar"/>
<classpathentry exported="true" kind="lib" path="lib/xnio-api.jar"/>
<classpathentry exported="true" kind="lib" path="lib/commons-fileupload-1.3.1.jar"/>
<classpathentry exported="true" kind="lib" path="lib/commons-io-2.4.jar"/>
<classpathentry exported="true" kind="lib" path="lib/slf4j-api-1.5.8.jar"/>
<classpathentry exported="true" kind="lib" path="lib/slf4j-log4j12-1.5.8.jar"/>
<classpathentry exported="true" kind="lib" path="lib/commons-lang3-3.4.jar"/>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.jboss.ide.eclipse.as.core.server.runtime.runtimeTarget/JBoss EAP 6.1+ Runtime"/>
<classpathentry kind="lib" path="lib/jackson-core-asl-1.7.1.jar"/>
<classpathentry kind="lib" path="lib/jackson-jaxrs-1.7.1.jar"/>
<classpathentry kind="lib" path="lib/jackson-mapper-asl-1.7.1.jar"/>
<classpathentry kind="lib" path="lib/jackson-xc-1.7.1.jar"/>
<classpathentry kind="lib" path="lib/jersey-client-1.8.jar"/>
<classpathentry kind="lib" path="lib/jersey-core-1.8.jar"/>
<classpathentry kind="lib" path="lib/jersey-json-1.8.jar"/>
<classpathentry kind="lib" path="lib/javax.ejb-api-3.2.jar"/>
<classpathentry kind="lib" path="lib/httpclient-4.2.jar"/>
<classpathentry kind="lib" path="lib/httpcore-4.2.4.jar"/>
<classpathentry kind="lib" path="lib/xnio-nio.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="build/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ReceiverJMS</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.zeroturnaround.eclipse.rebelXmlBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.zeroturnaround.eclipse.jrebelNature</nature>
</natures>
<variableList>
<variable>
<name>JBOSS_HOME</name>
<value>file:/home/emendez/Servidores/jboss-eap-6.3</value>
</variable>
</variableList>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6
eclipse.preferences.version=1
org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="ReceiverJMS">
<wb-resource deploy-path="/" source-path="/ejbModule" tag="defaultRootSource"/>
<property name="java-output-path" value="/ReceiverJMS/build/classes"/>
</wb-module>
</project-modules>
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="java"/>
<fixed facet="jst.ejb"/>
<installed facet="java" version="1.6"/>
<installed facet="jst.ejb" version="3.1"/>
</faceted-project>
eclipse.preferences.version=1
org.jboss.ide.eclipse.as.core.singledeployable.deployableList=
#PLANTILLA DE CORREO ENVIADO AL CIUDADANO
# VARIABLES DE LA PLANTILLA
# nombre: nombre del ciudadano
# processDescription : descripcion del proceso
# f_final: fecha final
# revision: decision del evaluador
# tramite: numero de tramite
# taskDescription: descripcion de la tarea
# tramite: numero de tramite
# f_solicitud: fecha de solicitud
# f_cita: fecha de la cita
# causasDevolucion: causas de devolucion
#variables disponibles: nombre, processDescription, f_final,revision, taskDescription, tramite
#PLANTILLA DE LAS NOTIFICACIONES QUE SE LE MANDAN AL CIUDADANO AL FINALIZAR CADA TAREA
TEMPLATE_SUBJECT_CIUDADANO = Notificacion tramite numero ${tramite}, ${processDescription}
TEMPLATE_BODY_CIUDADANO = Estimado ${ciudadano}, en fecha ${f_final} el tramite ${numero} de ${processDescription} finalizó la etapa de ${taskDescription}.
#PLANTILLA DE LA NOTIFICACION ENVIADA AL CIUDADANO CON EL DOCUMENTO ANEXO
#variables disponibles: numero, cedula,nombre, f_solicitud, revision,f_cita
TEMPLATE_SUBJECT_NOTIFICACION_DOC = Resultado de tramite numero ${tramite}, ${processDescription}
TEMPLATE_BODY_NOTIFICACION_DOC = Estimado ${nombre}, cumplimos con informarle que la solicitud numero ${tramite}, de fecha ${f_solicitud} ha sido ${revision}. Se anexa documento con el resultado del trámite.
#PLANTILLA DE LA NOTIFICACION ENVIADA AL CIUDADANO CON EL FECHA DE CITA
#variables disponibles: tramite, cedula,nombre, f_solicitud, revision,f_cita, notificacion
TEMPLATE_SUBJECT_NOTIFICACION_CITA = Resultado de tramite numero ${tramite}, ${processDescription}
TEMPLATE_BODY_NOTIFICACION_CITA = Estimado ${nombre}, cumplimos con informarle que la solicitud numero ${tramite}, de fecha ${f_solicitud} ha sido ${revision}. Debe acudir en fecha ${f_cita}, para continuar con su trámite
# PLANTILLA DE LA NOTIFICACION ENVIADA AL CIUDADANO CUANDO SE RECHAZA UN TRAMITE
TEMPLATE_SUBJECT_NOTIFICACION_RECH = Resultado de tramite numero ${tramite}, ${processDescription}
TEMPLATE_BODY_NOTIFICACION_RECH = Estimado ${nombre}, cumplimos con informarle que la solicitud numero ${tramite}, de fecha ${f_solicitud} ha sido ${revision}, por las siguientes causas de devolución: ${causasDevolucion}.
# database bonita configuration y worflow engine: relacionado con el proceso para llenar la tabla proceso_instancias_hist y con la conexion con el motor de procesos
#Indicar el servidor y el nombre de la Base de datos en Postgres
DATABASE_URL=jdbc:postgresql://xx.xx.xx.xx:5432/bonita
DATABASE_USER=xxxx
DATABASE_PASSWORD=xxxx
MAX_CONNECTION=5
INITIAL_CONNECTION=0
MAX_IDLE=10
MIN_IDLE = 0
REMOVE_ABANDONED = true
REMOVE_ABANDONED_TIME = 10
#Indicar la URL del Portal de Bonita
BONITA_REST_URL=http://xx.xx.xx.xx:8080/bonita
ADMIN_PROCESS_USERNAME = xxxx
ADMIN_PROCESS_PASSWORD = xxxx
# jms configuration
DEFAULT_CONNECTION_FACTORY = jms/RemoteConnectionFactory
DEFAULT_USERS_ACTIVITIES_DESTINATION = jms/queue/ciudadano
DEFAULT_PROCESS_REGISTRY_NOTIFICATION = jms/queue/notification
DEFAULT_PROCESS_REGISTRY_RECOVER = jms/queue/recover
DEFAULT_USERNAME = xxxxxx
DEFAULT_PASSWORD = xxxxxx
INITIAL_CONTEXT_FACTORY = org.jboss.naming.remote.client.InitialContextFactory
#Indicar la URL y el puerto del servidor de mensajeria
PROVIDER_URL = remote://xx.xx.xx.xx:4447
# email configuration
EMAIL_SERVER = dominio.xxx.xxx.xxx
EMAIL_USER_NAME = correo@dominio.xx.xx
EMAIL_PASSWORD = xxxxx
EMAIL_TRANSPORT = smtps
EMAIL_FILE_TEMP =/tmp/
EMAIL_PORT = 465
EMAIL_FROM_ADDRESS = correo@dominio.xx.xx
EMAIL_AUTH = true
EMAIL_STARTSSL = true
EMAIL_SSL_TRUST = *
EMAIL_SERVER_IDENTITY = false
#Indicar la URL del portal de Sistema de Gestión Interna SGI
URL_SISTEMA = http://xx.xx.xx.xx:xxxx/TramitesGI
# Repositorio configuration
# Indicar la URL del servidor del repositorio
REPOSITORY_URL = http://xx.xx.xx.xx:xxxx/repository/
#PLANTILLAS DE CORREO ENVIADO AL FUNCIONARIO DE GESTION INTERNA Y DEL SISTEMA DE TRAMITES
# VARIABLES DE LA PLANTILLA
# nombre: nombre del ciudadano
# processDescription : descripcion del proceso
# f_final: fecha final
# revision: decision del evaluador
# tramite: numero de tramite
# taskDescription: descripcion de la tarea
# tramite: numero de tramite
# f_solicitud: fecha de solicitud
# cedula: cedula del ciudadano
# password: hash enviado al funcionario de gestion interna para consulta de los documentos
# url: url del sistema donde se consultaran los documentos.
# f_cita: fecha de la cita
# notificacion: texto enviado por el funcionario de gestion interna para aclarar el motivo del rechazo
#PLANTILLA DE CORREO ENVIADO AL FUNCIONARIO DE GESTION INTERNA PARA QUE INGRESE A REVISAR LOS DOCUMENTOS DE UN TRAMITE EN PARTICULAR
#variables posibles: cedula,f_solicitud,ciudadano,tramite,password,url
TEMPLATE_SUBJECT_GI = Nuevo Caso ${tramite}: Nombre=${nombre}, Cedula=${cedula}, Fecha de Solicitud=${f_solicitud}
TEMPLATE_BODY_GI = Copie la siguiente clave de acceso ${password}, e ingrésela en la direccion ${url}, para acceder a los datos de esta solicitud
#PLANTILLA DE CORREO ENVIADO AL FUNCIONARIO DE GESTION INTERNA PARA QUE RECUPERE LOS TRAMITES QUE SE LE HAN SIDO ASIGNADOS
TEMPLATE_SUBJECT_GI_RECOVER = Lista de Casos Asignados
TEMPLATE_BODY_GI_RECOVER = Estimado usuario, para consultar la lista de casos que le han sido asignados ingrese a la siguiente direccion ${url}, a continuación se muestra la lista sus casos:\r\n\r\n\r\n
#PLANTILLA DE LA NOTIFICACION ENVIADA AL FUNCIONARIO CON EL DOCUMENTO ANEXO, EMITIDO POR EL FUNCIONARIO DE GESTION INTERNA
#variables disponibles: taskName, taskDescription,processName,processDescription,f_solicitud, nombre,tramite
,
TEMPLATE_SUBJECT_RESPUESTA_DOC = Resultado de tramite numero ${tramite}, ${processDescription}
TEMPLATE_BODY_RESPUESTA_DOC = Se anexa documento con el resultado del tramite número ${tramite}. Favor ingresar al sistema de tramitación para continuar con el procesamiento de esta solicitud.
#PLANTILLA DE LA NOTIFICACION ENVIADA AL FUNCIONARIO CON FECHA DE CITA, EMITIDO POR EL FUNCIONARIO DE GESTION INTERNA
#variables disponibles: taskName, taskDescription,processName,processDescription,f_solicitud, nombre,tramite
,
TEMPLATE_SUBJECT_RESPUESTA_CITA = Resultado de tramite numero ${tramite}, ${processDescription}
TEMPLATE_BODY_RESPUESTA_CITA = El tramite número ${tramite} tiene como resultado fecha de cita ${f_cita}. Favor ingresar al sistema de tramitación para continuar con el procesamiento de esta solicitud.
#PLANTILLA DE LA NOTIFICACION ENVIADA AL FUNCIONARIO CON UNA NOTA DE RECHAZO, EMITIDO POR EL FUNCIONARIO DE GESTION INTERNA
#variables disponibles: tramite, notificacion
TEMPLATE_SUBJECT_RESPUESTA_NOTI = Resultado de tramite numero ${tramite}, ${processDescription}
TEMPLATE_BODY_RESPUESTA_NOTI = El tramite número ${tramite} rechazado, debido a ${notificacion}. Favor ingresar al sistema de tramitación para continuar con el procesamiento de esta solicitud.
package ve.gob.cnti.beans;
import java.util.Date;
public class Ciudadano implements ICiudadano {
String hash;
long idTramite;
String tipoTramite;
String descripcion;
String nombre;
Date fechaSolicitud;
String cedula;
long taskId;
String taskName;
String taskDescription;
String emailGenerico;
String emailFuncionario;
String revision;
public Ciudadano() {
// TODO Auto-generated constructor stub
}
public Ciudadano(String hash, long idTramite, String tipoTramite,
String descripcion, String nombre, Date fechaSolicitud,
String cedula, long taskId, String taskName,
String taskDescription, String emailGenerico,
String emailFuncionario) {
super();
this.hash = hash;
this.idTramite = idTramite;
this.tipoTramite = tipoTramite;
this.descripcion = descripcion;
this.nombre = nombre;
this.fechaSolicitud = fechaSolicitud;
this.cedula = cedula;
this.taskId = taskId;
this.taskName = taskName;
this.taskDescription = taskDescription;
this.emailGenerico = emailGenerico;
this.emailFuncionario = emailFuncionario;
}
public Ciudadano(String hash, long idTramite, String tipoTramite,
String descripcion, String nombre, Date fechaSolicitud,
String cedula, long taskId, String taskName,
String taskDescription, String emailGenerico
) {
super();
this.hash = hash;
this.idTramite = idTramite;
this.tipoTramite = tipoTramite;
this.descripcion = descripcion;
this.nombre = nombre;
this.fechaSolicitud = fechaSolicitud;
this.cedula = cedula;
this.taskId = taskId;
this.taskName = taskName;
this.taskDescription = taskDescription;
this.emailGenerico = emailGenerico;
}
public String getEmailGenerico() {
return emailGenerico;
}
public void setEmailGenerico(String emailGenerico) {
this.emailGenerico = emailGenerico;
}
public String getEmailFuncionario() {
return emailFuncionario;
}
public void setEmailFuncionario(String emailFuncionario) {
this.emailFuncionario = emailFuncionario;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public long getIdTramite() {
return idTramite;
}
public void setIdTramite(long idTramite) {
this.idTramite = idTramite;
}
public String getTipoTramite() {
return tipoTramite;
}
public void setTipoTramite(String tipoTramite) {
this.tipoTramite = tipoTramite;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Date getFechaSolicitud() {
return fechaSolicitud;
}
public void setFechaSolicitud(Date fechaSolicitud) {
this.fechaSolicitud = fechaSolicitud;
}
public String getCedula() {
return cedula;
}
public void setCedula(String cedula) {
this.cedula = cedula;
}
public long getTaskId() {
return taskId;
}
public void setTaskId(long taskId) {
this.taskId = taskId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
@Override
public String toString() {
return "Ciudadano [hash=" + hash + ", idTramite=" + idTramite
+ ", tipoTramite=" + tipoTramite + ", descripcion="
+ descripcion + ", nombre=" + nombre + ", fechaSolicitud="
+ fechaSolicitud + ", cedula=" + cedula + ", taskId=" + taskId
+ ", taskName=" + taskName + ", taskDescription="
+ taskDescription + ", emailGenerico=" + emailGenerico
+ ", emailFuncionario=" + emailFuncionario + ", revision="
+ revision + "]";
}
}
package ve.gob.cnti.beans;
public class FileAlfresco implements IFileAlfresco{
String name;
int size;
String type;
String id;
String url;
public FileAlfresco() {
// TODO Auto-generated constructor stub
}
public FileAlfresco(String name, String id) {
super();
this.name = name;
this.id = id;
}
public FileAlfresco(String name, int size, String type, String id, String url) {
super();
this.name = name;
this.size = size;
this.type = type;
this.id = id;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package ve.gob.cnti.beans;
import java.util.Date;
public interface ICiudadano {
public String getHash();
public void setHash(String hash);
public long getIdTramite();
public void setIdTramite(long idTramite);
public String getTipoTramite();
public void setTipoTramite(String tipoTramite);
public String getDescripcion();
public void setDescripcion(String descripcion) ;
public String getNombre();
public void setNombre(String nombre);
public Date getFechaSolicitud();
public void setFechaSolicitud(Date fechaSolicitud);
public String getCedula();
public void setCedula(String cedula);
public long getTaskId();
public void setTaskId(long taskId);
public String getTaskName();
public void setTaskName(String taskName);
public String getTaskDescription();
public void setTaskDescription(String taskDescription);
public String getEmailGenerico();
public void setEmailGenerico(String emailGenerico);
public String getEmailFuncionario();
public String getRevision();
public void setRevision(String revision);
}
package ve.gob.cnti.beans;
public interface IFileAlfresco {
public String getName();
public void setName(String name);
public int getSize();
public void setSize(int size);
public String getType();
public void setType(String type);
public String getId();
public void setId(String id);
public String getUrl();
public void setUrl(String url);
}
package ve.gob.cnti.beans;
/**
* @author emendez
*
*/
public interface IVariableBonita {
public long getId();
public String getName();
public String getType();
public String getValue();
}
package ve.gob.cnti.beans;
public class VariableBonita implements IVariableBonita{
long id;
String name;
String type;
String value;
public VariableBonita() {
// TODO Auto-generated constructor stub
}
public VariableBonita(long id, String name, String type, String value) {
super();
this.id = id;
this.name = name;
this.type = type;
this.value = value;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
package ve.gob.cnti.bonita;
public interface ISession {
/**
*
* @param user
* @param pass
*/
public void startConection(String user, String pass);
/**
*
*/
public void stopConection();
}
package ve.gob.cnti.bonita;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.SchemeRegistryFactory;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import ve.gob.cnti.receiver.utils.PropertiesReader;
/**TODO Cambiar la accesibilidad de los metodos y atributos de esta clase
*
* @author usuario
*
*/
public class SessionImpl implements ISession{
PropertiesReader pr = new PropertiesReader("/home/emendez/Servidores/jboss-eap-6.3/standalone/configuration/receiverEJB","eee");
public HttpClient httpClient;
public void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
private HttpContext httpContext;
private String bonitaURI = pr.getProperty("BONITA_REST_URL");
public String response;
/** TODO
*
* Conexion a bonita mediante servicios rest
*/
public static PoolingClientConnectionManager getConnectionManager() {
PoolingClientConnectionManager conMan = new PoolingClientConnectionManager(SchemeRegistryFactory.createDefault());
conMan.setMaxTotal(200);
conMan.setDefaultMaxPerRoute(200);
return conMan;
}
public HttpResponse executeGetRequest(String apiURI) {
try {
System.out.println(bonitaURI + apiURI);
HttpGet getRequest = new HttpGet(bonitaURI + apiURI);
HttpResponse response = httpClient.execute(getRequest, httpContext);
return response;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void loginAs(String username, String password) {
try {
CookieStore cookieStore = new BasicCookieStore();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
String loginURL = "/loginservice";
// If you misspell a parameter you will get a HTTP 500 error
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", username));
urlParameters.add(new BasicNameValuePair("password", password));
urlParameters.add(new BasicNameValuePair("redirect", "false"));
// UTF-8 is mandatory otherwise you get a NPE
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters, "utf-8");
executePostRequest(loginURL, entity);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void logout() {
consumeResponse(executeGetRequest("/logoutservice"),false);
}
private int executePostRequest(String apiURI, UrlEncodedFormEntity entity) {
try {
HttpPost postRequest = new HttpPost(bonitaURI + apiURI);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest, httpContext);
return consumeResponse(response, true);
} catch (HttpHostConnectException e) {
throw new RuntimeException("Bonita bundle may not have been started, or the URL is invalid. Please verify hostname and port number. URL used is: " + bonitaURI,e);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public HttpResponse executePostRequest(String apiURI, String payloadAsString) {
try {
HttpPost postRequest = new HttpPost(bonitaURI + apiURI);
StringEntity input = new StringEntity(payloadAsString);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest, httpContext);
return response;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public HttpResponse executePutRequest(String apiURI, String payloadAsString) {
try {
HttpPut putRequest = new HttpPut(bonitaURI + apiURI);
putRequest.addHeader("Content-Type", "application/json");
StringEntity input = new StringEntity(payloadAsString);
input.setContentType("application/json");
putRequest.setEntity(input);
return httpClient.execute(putRequest, httpContext);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**TODO
*
* Implementar una forma de consumir la respuesta en un bean
*
* @param response
* @param printResponse
* @return
*/
public int consumeResponse(HttpResponse response, boolean printResponse) {
String responseAsString = consumeResponseIfNecessary(response);
if(printResponse) {
this.response = responseAsString;
}
return ensureStatusOk(response);
}
public String consumeResponseIfNecessary(HttpResponse response) {
if (response.getEntity() != null) {
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
} catch (Exception e) {
throw new RuntimeException("Failed to consume response.", e);
}
} else {
return "";
}
}
private int ensureStatusOk(HttpResponse response) {
if (response.getStatusLine().getStatusCode() != 201 && response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " : "
+ response.getStatusLine().getReasonPhrase());
}
return response.getStatusLine().getStatusCode();
}
public void makeSureLocaleIsActive() {
consumeResponse(executeGetRequest("/API/system/i18ntranslation?f=locale%3den"), false);
}
/**
* Autenticación de usuarios para pruebas
*/
public void loginAsAdmin() {
loginAs("admin", "admin");
}
/**
* Inicia la sesion y prepara el gestos de peticiones
* @param user
* @param pass
*/
public void startConection(String user, String pass){
PoolingClientConnectionManager conMan = SessionImpl.getConnectionManager();
this.setHttpClient(new DefaultHttpClient(conMan));
this.loginAs(user, pass);
this.makeSureLocaleIsActive();
}
/**
* Cierra la Conexion y desloguea al usuario
*/
public void stopConection(){
this.logout();
this.httpClient.getConnectionManager().shutdown();
}
}
package ve.gob.cnti.bonita;
public class TestRest {
public TestRest() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//IRestConnection rest=new RestConnection();
//System.out.println(rest.getVariable("a_cedula","166"));
SessionImpl session=new SessionImpl();
session.startConection("admin", "admin");
//session.executeGetRequest("/loginservice?username=admin&redirect=false&password=admin");
//System.out.println(session.executeGetRequest("/API/bpm/caseVariable/166/a_cedula"));
//session.executePutRequest("/API/bpm/caseVariable/166/a_cedula", "{\"value\":\"8888\",\"type\":\"java.lang.Integer\"}");
System.out.println(session.consumeResponseIfNecessary(session.executeGetRequest("/API/bpm/caseVariable/166/a_cedula")));
//session.executePutRequest("http://localhost:8080/bonita/API/bpm/activity/5", payloadAsString)
//{"variables": [{"name": "stringVariable", "value": "aValue"}}
}
}
package ve.gob.cnti.gestion.alfresco;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import org.apache.commons.io.FileUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import ve.gob.cnti.receiver.utils.PropertiesReader;
import ve.gob.cnti.gestion.alfresco.ICmisController;
import ve.gob.cnti.gestion.alfresco.FileMessage;
/**
* Loads the images in a local folder into a CMIS repo. Extend CloudExampleBase
* to load into Alfresco in the cloud. Extend LocalExampleBase to load into a
* local repo.
*
* @author jpotts
*
*/
public class AlfrescoLoadFiles implements ICmisController {
ve.gob.cnti.receiver.utils.PropertiesReader pr = new PropertiesReader();
public String REPOSITORY_URL = pr.getProperty("REPOSITORY_URL");
/**
* Uploads all files in a local directory to the CMIS server.
*
* @throws IOException
*/
public String uploadDocument(File file, String pathFolder,
String nameFile) {
String id = "";
byte[] stream=null;
try {
stream = FileUtils.readFileToByteArray(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileMessage fileMessage=new FileMessage(pathFolder,file.getName(),stream,"application/pdf");
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client
.resource(REPOSITORY_URL+"rest/fileUpload/upload");
ClientResponse response = webResource.accept("application/json")
.type("application/json").post(ClientResponse.class,fileMessage);
long value=response.getEntity(long.class);
if (value== 0) {
throw new RuntimeException("El archivo no se almaceno en el repositorio");
}
id=String.valueOf(value);
return id;
}
public ContentStream getDocument(String documentID) {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client
.resource(REPOSITORY_URL+"rest/fileDownload/download");
ClientResponse response = webResource.queryParam("identify", documentID).accept("application/json")
.type("application/json").get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
FileMessage output = response.getEntity(FileMessage.class);
InputStream stream = new ByteArrayInputStream(output.getFileUp());
ContentStream contentStream=new ContentStream(output.getName(),stream,output.getContenttype(),output.getFileUp().length,BigInteger.valueOf(output.getFileUp().length));
return contentStream;
}
public FileMessage getFileMessage(String documentID) {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client
.resource(REPOSITORY_URL+"rest/fileDownload/download");
ClientResponse response = webResource.queryParam("identify", documentID).accept("application/json")
.type("application/json").get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
FileMessage output = response.getEntity(FileMessage.class);
return output;
}
public void deletedDocument(String documentID) {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client
.resource(REPOSITORY_URL+"rest/fileDelete/delete");
ClientResponse response = webResource.queryParam("identify", documentID).accept("application/json")
.type("application/json").delete(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
}
}
package ve.gob.cnti.gestion.alfresco;
import java.io.InputStream;
import java.math.BigInteger;
public class ContentStream {
private BigInteger bigLength;
private String fileName;
private long length;
private String mimeType;
private InputStream stream;
public ContentStream(){
super();
}
public ContentStream(String fileName, InputStream stream, String mimeType, long length, BigInteger bigLength) {
super();
this.bigLength = bigLength;
this.fileName = fileName;
this.length = length;
this.mimeType = mimeType;
this.stream = stream;
}
public BigInteger getBigLength() {
return bigLength;
}
public void setBigLength(BigInteger bigLength) {
this.bigLength = bigLength;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStream getStream() {
return stream;
}
public void setStream(InputStream stream) {
this.stream = stream;
}
}
package ve.gob.cnti.gestion.alfresco;
public class DocumentVO {
private String name;
private String url;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package ve.gob.cnti.gestion.alfresco;
import java.io.Serializable;
import java.util.Arrays;
import org.codehaus.jackson.annotate.JsonIgnore;
public class FileMessage implements Serializable{
/**
*
*/
private static final long serialVersionUID = 5413789852539857776L;
/**
*
*/
public String uri;
public String name;
public byte[] fileUp;
public String contenttype;
public String identify;
public FileMessage() {
super();
}
public FileMessage(String uri, String name, byte[] fileUp, String contenttype) {
super();
this.uri = uri;
this.name = name;
this.fileUp = fileUp;
this.contenttype = contenttype;
}
public FileMessage(String uri, String name, byte[] fileUp, String contenttype, String identify) {
super();
this.uri = uri;
this.name = name;
this.fileUp = fileUp;
this.contenttype = contenttype;
this.identify = identify;
}
@JsonIgnore
public String getUri() {
return uri;
}
@JsonIgnore
public void setUri(String uri) {
this.uri = uri;
}
@JsonIgnore
public String getName() {
return name;
}
@JsonIgnore
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public byte[] getFileUp() {
return fileUp;
}
@JsonIgnore
public void setFileUp(byte[] fileUp) {
this.fileUp = fileUp;
}
@JsonIgnore
public String getContenttype() {
return contenttype;
}
@JsonIgnore
public void setContenttype(String contenttype) {
this.contenttype = contenttype;
}
@JsonIgnore
public String getIdentify() {
return identify;
}
@JsonIgnore
public void setIdentify(String identify) {
this.identify = identify;
}
@Override
public String toString() {
return "FileMessage [uri=" + uri + ", name=" + name + ", fileUp=" + Arrays.toString(fileUp) + ", contenttype="
+ contenttype + ", identify=" + identify + "]";
}
}
package ve.gob.cnti.gestion.alfresco;
import java.io.File;
import ve.gob.cnti.gestion.alfresco.ContentStream;
import ve.gob.cnti.gestion.alfresco.FileMessage;
public interface ICmisController {
// public String uploadDocument(File file,String pathFolder);
// public String uploadDocument(UploadedFile ufile,String pathFolder,String name);
public String uploadDocument(File ufile,String pathFolder,String name);
public FileMessage getFileMessage(String documentID);
public ContentStream getDocument(String documentID);
public void deletedDocument(String documentID);
}
package ve.gob.cnti.receiver.ejb;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import ve.gob.cnti.receiver.mail.IMail;
import ve.gob.cnti.receiver.mail.Mailer;
import ve.gob.cnti.receiver.utils.IMapMessageConverter;
import ve.gob.cnti.receiver.utils.IPropertiesReader;
import ve.gob.cnti.receiver.utils.MapMessageConverter;
import ve.gob.cnti.receiver.utils.PropertiesReader;
/**
* Message-Driven Bean implementation class for: ReceiverNotificacion
*/
@MessageDriven(
activationConfig = { @ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/queue/notificacion"), @ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue")
},
mappedName = "jms/queue/notificacion")
public class ReceiverNotificacion implements MessageListener {
private static final Logger log = Logger.getLogger(ReceiverNotificacion.class.getName());
/**
* Default constructor.
*/
public ReceiverNotificacion() {
// TODO Auto-generated constructor stub
}
/**
* @see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
MapMessage incoming = (MapMessage)message;
IMapMessageConverter mapConverter=new MapMessageConverter();
Map<String,String> map=mapConverter.converMapMessageToMap(incoming);
IMail mail=new Mailer();
IPropertiesReader properties=new PropertiesReader("templatesistema");
String TEMPLATE_SUBJECT_NOTIFICACION = null;
String TEMPLATE_BODY_NOTIFICACION = null;
if(map.get("respuesta").equals("Aprobado")){
if(map.get("tipo").equals("cita")){
TEMPLATE_SUBJECT_NOTIFICACION = properties.getProperty("TEMPLATE_SUBJECT_RESPUESTA_CITA");
TEMPLATE_BODY_NOTIFICACION = properties.getProperty("TEMPLATE_BODY_RESPUESTA_CITA");
}else{
TEMPLATE_SUBJECT_NOTIFICACION = properties.getProperty("TEMPLATE_SUBJECT_RESPUESTA_DOC");
TEMPLATE_BODY_NOTIFICACION = properties.getProperty("TEMPLATE_BODY_RESPUESTA_DOC");
}
}else{
TEMPLATE_SUBJECT_NOTIFICACION = properties.getProperty("TEMPLATE_SUBJECT_RESPUESTA_NOTI");
TEMPLATE_BODY_NOTIFICACION = properties.getProperty("TEMPLATE_BODY_RESPUESTA_NOTI");
}
byte[] arr=null;
try {
arr = TEMPLATE_SUBJECT_NOTIFICACION.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
TEMPLATE_SUBJECT_NOTIFICACION= new String(arr);
mail.setSubject(TEMPLATE_SUBJECT_NOTIFICACION.
replace("${tramite}", map.get("tramite")).
replace("${processDescription}", map.get("processDescription")));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${tramite}",map.get("tramite"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${cedula}",map.get("cedula"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${taskDescription}",map.get("taskDescription"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${processDescription}",map.get("processDescription"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${nombre}",map.get("nombre"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${f_solicitud}",map.get("fechaSolicitud"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${revision}",map.get("revision"));
//TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${notificacion}",map.get("notificacion"));
if(map.get("respuesta").equals("Aprobado")){
if(map.get("tipo").equals("cita")){
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${f_cita}", map.get("f_cita"));
}/*else{
try {
mail.setReceiveFile(incoming.getBytes("Bytes_FILE_Planilla"));
mail.setFileName(map.get("_FILE_Planilla_Nombre"));
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}else{
log.info("paso notificacin");
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${notificacion}",map.get("notificacion"));
}
try {
arr = TEMPLATE_BODY_NOTIFICACION.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
TEMPLATE_BODY_NOTIFICACION= new String(arr);
mail.setBody(TEMPLATE_BODY_NOTIFICACION);
mail.setToAddress(map.get("email"));
mail.send();
}
}
package ve.gob.cnti.receiver.ejb;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import ve.gob.cnti.receiver.mail.IMail;
import ve.gob.cnti.receiver.mail.Mailer;
import ve.gob.cnti.receiver.utils.PropertiesReader;
/**
* Message-Driven Bean implementation class for: ReceiverRecover
*/
@MessageDriven(
activationConfig = { @ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/queue/recover"), @ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue")
},
mappedName = "jms/queue/recover")
public class ReceiverRecover implements MessageListener {
private static final Logger log = Logger.getLogger(ReceiverRecover.class.getName());
/**
* Default constructor.
*/
public ReceiverRecover() {
// TODO Auto-generated constructor stub
}
/**
* @see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
PropertiesReader properties = new PropertiesReader("templatesistema");
String TEMPLATE_SUBJECT_GI_RECOVER = properties.getProperty("TEMPLATE_SUBJECT_GI_RECOVER");
String TEMPLATE_BODY_GI_RECOVER = properties.getProperty("TEMPLATE_BODY_GI_RECOVER");
PropertiesReader propertiesCongiguration = new PropertiesReader();
MapMessage incoming = (MapMessage)message;
IMail mail=new Mailer();
String subject=TEMPLATE_SUBJECT_GI_RECOVER;
log.info("asunto"+subject+TEMPLATE_SUBJECT_GI_RECOVER);
String texto=TEMPLATE_BODY_GI_RECOVER;
log.info("templates"+TEMPLATE_SUBJECT_GI_RECOVER+TEMPLATE_BODY_GI_RECOVER+"url sistema"+propertiesCongiguration.getProperty("URL_SISTEMA"));
texto=texto.replace("${url}", propertiesCongiguration.getProperty("URL_SISTEMA").trim());
mail=new Mailer();
try {
log.info("email and body"+incoming.getString("body")+" "+incoming.getString("email"));
texto+=incoming.getString("body");
byte[] arr=null;
try {
arr = subject.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
subject= new String(arr);
try {
arr = texto.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
texto= new String(arr);
mail.setToAddress(incoming.getString("email"));
mail.setSubject(subject);
mail.setBody(texto);
mail.send();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package ve.gob.cnti.receiver.ejb;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import ve.gob.cnti.receiver.mail.IMail;
import ve.gob.cnti.receiver.mail.Mailer;
import ve.gob.cnti.receiver.utils.IMapMessageConverter;
import ve.gob.cnti.receiver.utils.IPropertiesReader;
import ve.gob.cnti.receiver.utils.MapMessageConverter;
import ve.gob.cnti.receiver.utils.PropertiesReader;
/**
* Message-Driven Bean implementation class for: ReceiverRespuesta
*/
@MessageDriven(
activationConfig = { @ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/queue/respuesta"), @ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue")
},
mappedName = "jms/queue/respuesta")
public class ReceiverRespuesta implements MessageListener {
private static final Logger log = Logger.getLogger(ReceiverRespuesta.class.getName());
/**
* Default constructor.
*/
public ReceiverRespuesta() {
// TODO Auto-generated constructor stub
}
/**
* @see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
MapMessage incoming = (MapMessage)message;
IMapMessageConverter mapConverter=new MapMessageConverter();
Map<String,String> map=mapConverter.converMapMessageToMap(incoming);
IPropertiesReader properties=new PropertiesReader(map.get("processName"));
String TEMPLATE_SUBJECT_NOTIFICACION = null;
String TEMPLATE_BODY_NOTIFICACION = null;
log.info("paso a la respuesta"+map.get("revision"));
if(map.get("revision").equals("Aprobado")){
if(map.get("f_cita")!=null&&!map.get("f_cita").equals("")&&!map.get("f_cita").equals("null")){
TEMPLATE_SUBJECT_NOTIFICACION = properties.getProperty("TEMPLATE_SUBJECT_NOTIFICACION_CITA");
TEMPLATE_BODY_NOTIFICACION = properties.getProperty("TEMPLATE_BODY_NOTIFICACION_CITA");
}else{
TEMPLATE_SUBJECT_NOTIFICACION = properties.getProperty("TEMPLATE_SUBJECT_NOTIFICACION_DOC");
TEMPLATE_BODY_NOTIFICACION = properties.getProperty("TEMPLATE_BODY_NOTIFICACION_DOC");
log.info("la plantilla es la siguiente"+TEMPLATE_BODY_NOTIFICACION);
}
}else{
TEMPLATE_SUBJECT_NOTIFICACION = properties.getProperty("TEMPLATE_SUBJECT_NOTIFICACION_RECH");
TEMPLATE_BODY_NOTIFICACION = properties.getProperty("TEMPLATE_BODY_NOTIFICACION_RECH");
TEMPLATE_BODY_NOTIFICACION = properties.getProperty("TEMPLATE_BODY_NOTIFICACION_RECH").replace("${causasDevolucion}", map.get("causasDevolucion").replace("[", "").replace("]", ""));
}
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${tramite}",map.get("tramite"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${cedula}",map.get("cedula"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${taskDescription}",map.get("taskDescription"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${processDescription}",map.get("processDescription"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${nombre}",map.get("nombre")+" "+map.get("apellido"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${f_solicitud}",map.get("f_solicitud"));
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${revision}",map.get("revision"));
byte[] arr=null;
try {
arr = TEMPLATE_SUBJECT_NOTIFICACION.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
TEMPLATE_SUBJECT_NOTIFICACION= new String(arr);
try {
arr = TEMPLATE_BODY_NOTIFICACION.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
TEMPLATE_BODY_NOTIFICACION= new String(arr);
IMail mail=new Mailer();
if(map.get("f_cita")!=null&&!map.get("f_cita").equals("")){
TEMPLATE_BODY_NOTIFICACION=TEMPLATE_BODY_NOTIFICACION.replace("${f_cita}", map.get("f_cita"));
}else if (map.get("_FILE_decision")!=null&&!map.get("_FILE_decision").equals("")){
try {
mail.setReceiveFile(incoming.getBytes("Bytes_FILE_Planilla"));
mail.setFileName(map.get("_FILE_Planilla_Nombre"));
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mail.setToAddress(map.get("email"));
mail.setSubject(TEMPLATE_SUBJECT_NOTIFICACION.
replace("${tramite}", map.get("tramite")).
replace("${processDescription}", map.get("processDescription")));
mail.setBody(TEMPLATE_BODY_NOTIFICACION);
mail.send();
}
}
package ve.gob.cnti.receiver.ejb;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import ve.gob.cnti.receiver.utils.ConverDate;
import ve.gob.cnti.receiver.utils.IConvertDate;
import ve.gob.cnti.receiver.utils.IMapMessageConverter;
import ve.gob.cnti.receiver.utils.MapMessageConverter;
import ve.gob.cnti.receiver.utils.PropertiesReader;
import ve.gob.cnti.receiver.jms.ISenderJMS;
import ve.gob.cnti.receiver.jms.SenderJMS;
import ve.gob.cnti.receiver.mail.IMail;
import ve.gob.cnti.receiver.mail.Mailer;
/**
* Message-Driven Bean implementation class for: ReciberActivity
*/
@MessageDriven(
activationConfig = { @ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/queue/activities"), @ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue")
},
mappedName = "jms/queue/activities")
public class ReciverActivity implements MessageListener {
/**
* Default constructor.
*/
private static final Logger log = Logger.getLogger(ReciverActivity.class.getName());
public ReciverActivity() {
// TODO Auto-generated constructor stub
}
/**
* @see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
log.info("usando el ejb para enviar el mensaje al portal ciudadano de las actividades");
MapMessage incoming = (MapMessage)message;
try {
log.info("paso y deja el id de la actividad"+incoming.getString("taskId"));
} catch (JMSException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ISenderJMS senderJMS=new SenderJMS();
senderJMS.sendActivitiesRegistry(incoming);
IMapMessageConverter converter=new MapMessageConverter();
IConvertDate converterDate=new ConverDate();
Map<String,String> map=converter.converMapMessageToMap(incoming);
PropertiesReader properties = new PropertiesReader(map.get("processName"));
String TEMPLATE_SUBJECT_CIUDADANO = properties.getProperty("TEMPLATE_SUBJECT_CIUDADANO");
String TEMPLATE_BODY_CIUDADANO = properties.getProperty("TEMPLATE_BODY_CIUDADANO");
String subject=TEMPLATE_SUBJECT_CIUDADANO.replace("${tramite}", map.get("id")).
replace("${processDescription}",map.get("processDescription"));
byte[] arr= subject.getBytes("UTF-8");
subject= new String(arr);
String text=TEMPLATE_BODY_CIUDADANO.replace("${numero}", map.get("id"));;
text=text.replace("${processName}",map.get("processName"));
text=text.replace("${ciudadano}",(map.get("nombre"))+" "+map.get("apellido"));
text=text.replace("${processDescription}",map.get("processDescription"));
text=text.replace("${taskName}",map.get("taskName"));
text=text.replace("${taskDescription}",map.get("taskDescription"));
text=text.replace("${f_final}",converterDate.getFormattedLongDateDate("dd-MM-yyyy",map.get("lastupdate")));
arr = text.getBytes("UTF-8");
text= new String(arr);
IMail mailSender=new Mailer();
mailSender.setToAddress(map.get("email"));
mailSender.setSubject(subject);
mailSender.setBody(text);
mailSender.send();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package ve.gob.cnti.receiver.ejb;
import java.util.Map;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import ve.gob.cnti.receiver.jdbc.ConnectionJDBC;
import ve.gob.cnti.receiver.jdbc.FuncionarioGI;
import ve.gob.cnti.receiver.jdbc.IConnectionJDBC;
import ve.gob.cnti.receiver.jdbc.IFuncionarioGI;
import ve.gob.cnti.receiver.mail.IMail;
import ve.gob.cnti.receiver.mail.Mailer;
import ve.gob.cnti.receiver.utils.ConverDate;
import ve.gob.cnti.receiver.utils.IConvertDate;
import ve.gob.cnti.receiver.utils.IMapMessageConverter;
import ve.gob.cnti.receiver.utils.MapMessageConverter;
import ve.gob.cnti.receiver.utils.PropertiesReader;
/**
* Message-Driven Bean implementation class for: ReceiberEmail
*/
@MessageDriven(
activationConfig = { @ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/queue/email"), @ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue")
},
mappedName = "jms/queue/email")
public class ReciverEmail implements MessageListener {
private static final Logger log = Logger.getLogger(ReciverEmail.class.getName());
/**
* Default constructor.
*/
public ReciverEmail() {
// TODO Auto-generated constructor stub
}
/**
* @see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
log.info("usando el ejb para enviar el correo al funcionario");
MapMessage incoming = (MapMessage)message;
String subject=null;
String text=null;
IMail mailSender=new Mailer();
try {
PropertiesReader properties=new PropertiesReader("templatesistema");
log.info("esto es una prueba"+properties.getProperty("TEMPLATE_SUBJECT_GI"));
IConnectionJDBC connection=new ConnectionJDBC();
IMapMessageConverter converterMessage=new MapMessageConverter();
Map<String,String> map=converterMessage.converMapMessageToMap(incoming);
IFuncionarioGI funcionarioGI=new FuncionarioGI();
if(!(map.get("asignado")!=null))
map.put("emailSGI", funcionarioGI.getEmail(map.get("tipo_tramite")));
if(!connection.verifyUser(map.get("hash")))
connection.insertRecordCiudadanoArchivos(map);
IConvertDate convertDate=new ConverDate();
String pattern="dd-MM-yyyy";
connection.closeConnection();
subject = properties.getProperty("TEMPLATE_SUBJECT_GI").replace("${cedula}",map.get("cedula"));
if(map.get("asignado")==null)
subject = subject.replace("${f_solicitud}",convertDate.getFormattedLongDateDate(pattern,map.get("f_solicitud")));
else
subject = subject.replace("${f_solicitud}",convertDate.getFormattedShortDateDate(pattern,map.get("f_solicitud")));
subject = subject.replace("${nombre}",map.get("nombre")+" "+map.get("apellido"));
subject = subject.replace("${tramite}",map.get("id_tramite"));
byte[] arr= subject.getBytes("UTF-8");
subject= new String(arr);
text = properties.getProperty("TEMPLATE_BODY_GI").replace("${login}",map.get("email"));
text = text.replace("${password}",map.get("hash"));
text = text.replace("${usuario}",map.get("emailSGI"));
PropertiesReader propertiesConfiguracion=new PropertiesReader("receiverEJB");
text = text.replace("${url}",propertiesConfiguracion.getProperty("URL_SISTEMA"));
log.info("correo"+map.get("emailSGI"));
arr = text.getBytes("UTF-8");
text= new String(arr);
mailSender.setToAddress(map.get("emailSGI"));
mailSender.setSubject(subject);
mailSender.setBody(text);
mailSender.send();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package ve.gob.cnti.receiver.ejb;
import java.util.Map;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import ve.gob.cnti.receiver.jdbc.ConnectionJDBC;
import ve.gob.cnti.receiver.jdbc.IConnectionJDBC;
import ve.gob.cnti.receiver.utils.IMapMessageConverter;
import ve.gob.cnti.receiver.utils.MapMessageConverter;
/**
* Message-Driven Bean implementation class for: ReciberJMS
*/
@MessageDriven(
activationConfig = { @ActivationConfigProperty(
propertyName = "destination", propertyValue = "java:/jms/queue/process"), @ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue")
},
mappedName = "java:/jms/queue/process")
public class ReciverProcess implements MessageListener {
private static final Logger log = Logger.getLogger(ReciverProcess.class.getName());
/**
* Default constructor.
*/
public ReciverProcess() {
// TODO Auto-generated constructor stub
}
/**
* @see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
log.info("timer 1 segundos");
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
log.info("usando el ejb para ingresar el proceso finalizado en la bd");
MapMessage incoming = (MapMessage)message;
IConnectionJDBC connection=new ConnectionJDBC();
IMapMessageConverter converterMessage=new MapMessageConverter();
Map<String,String> map=converterMessage.converMapMessageToMap(incoming);
connection.insertRecordProcess(map);
//connection.deleteRecordDocuments(Long.valueOf(map.get("id_instancia")));
connection.closeConnection();
}
}
package ve.gob.cnti.receiver.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.apache.commons.dbcp2.BasicDataSource;
import ve.gob.cnti.receiver.utils.IRamdomNumber;
import ve.gob.cnti.receiver.utils.PropertiesReader;
import ve.gob.cnti.receiver.utils.RamdomNumber;
/**
* Esta clase se encarga de extraer informacion de la tabla arch_process_instance_lastupdate, process_instance y data_instance
* para implementar esta clase utilice la clase CaseImpl.java
* @author Yamil Orozco
*/
public class FuncionarioGI implements IFuncionarioGI {
Connection cnn=null;
Statement ps = null;
ResultSet rs=null;
private BasicDataSource basicDataSource=new BasicDataSource();
PropertiesReader properties = new PropertiesReader();
public String DATABASE_URL = properties.getProperty("DATABASE_URL");
public String DATABASE_USER = properties.getProperty("DATABASE_USER");
public String DATABASE_PASSWORD = properties.getProperty("DATABASE_PASSWORD");
public Integer MAX_CONNECTION = Integer.valueOf(properties.getProperty("MAX_CONNECTION"));
public Integer INITIAL_CONNECTION = Integer.valueOf(properties.getProperty("INITIAL_CONNECTION"));
public Integer MAX_IDLE = Integer.valueOf(properties.getProperty("MAX_IDLE"));
public Integer MIN_IDLE = Integer.valueOf(properties.getProperty("MIN_IDLE"));
public Boolean REMOVE_ABANDONED = Boolean.valueOf(properties.getProperty("REMOVE_ABANDONED"));
public Integer REMOVE_ABANDONED_TIME = Integer.valueOf(properties.getProperty("REMOVE_ABANDONED_TIME"));
private static final Logger log = Logger.getLogger(ConnectionJDBC.class.getName());
Boolean next=null;
public FuncionarioGI(){
basicDataSource.setDriverClassName("org.postgresql.Driver");
basicDataSource.setUrl(DATABASE_URL);
basicDataSource.setUsername(DATABASE_USER);
basicDataSource.setPassword(DATABASE_PASSWORD);
basicDataSource.setMaxTotal(MAX_CONNECTION);
basicDataSource.setInitialSize(INITIAL_CONNECTION);
basicDataSource.setValidationQuery("select 1");
basicDataSource.setRemoveAbandonedOnBorrow(REMOVE_ABANDONED);
basicDataSource.setRemoveAbandonedTimeout(REMOVE_ABANDONED_TIME);
basicDataSource.setMaxIdle(MAX_IDLE);
basicDataSource.setMinIdle(MIN_IDLE);
}
public String getEmail(String tramite){
List<String> emails=new ArrayList<String>();
String query="select distinct email from tramite_interno where tramite='"+tramite+"' and nivel=1";
System.out.println(query);
String email=null;
try {
cnn =basicDataSource.getConnection();
ps=cnn.createStatement();
rs = ps.executeQuery(query);
while(rs.next()){
emails.add(rs.getString("email"));
System.out.println("email"+rs.getString("email"));
}
int total=emails.size();
int tamanoEmails=emails.size();
System.out.println("el correo es "+tamanoEmails);
IRamdomNumber ramdom=new RamdomNumber();
int numeroFuncionario=ramdom.randInt(0, total-1);
System.out.println("el numero aleatorio es"+String.valueOf(numeroFuncionario));
email=emails.get(numeroFuncionario);
try {
if(rs!=null)rs.close();
if(ps!=null) ps.close();
if(cnn!=null) cnn.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return email;
}
public void closeConnection(){
try {
//ps.close();
//cnn.close();
if(basicDataSource!=null)
basicDataSource.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}
package ve.gob.cnti.receiver.jdbc;
import java.util.Map;
public interface IConnectionJDBC {
public void openConnection();
public void insertRecordProcess(Map<String,String> variables);
public void insertRecordCiudadanoArchivos(Map<String,String> variables);
public void deleteRecordDocuments(long instanceProcessId);
public Boolean verifyUser(String hash);
public void closeConnection();
}
package ve.gob.cnti.receiver.jdbc;
public interface IFuncionarioGI {
public String getEmail(String tramite);
public void closeConnection();
}
package ve.gob.cnti.receiver.jdbc;
import ve.gob.cnti.receiver.utils.IRamdomNumber;
import ve.gob.cnti.receiver.utils.RamdomNumber;
public class testFuncionario {
public testFuncionario() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
IRamdomNumber ramdon=new RamdomNumber();
System.out.println(ramdon.randInt(0, 2));
}
}
package ve.gob.cnti.receiver.jms;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Logger;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import ve.gob.cnti.receiver.utils.PropertiesReader;
public class ConnectionJMS implements IConnectionJMS{
PropertiesReader properties = new PropertiesReader();
private final String DEFAULT_CONNECTION_FACTORY = properties.getProperty("DEFAULT_CONNECTION_FACTORY");
public final String DEFAULT_EMAIL_DESTINATION = properties.getProperty("DEFAULT_EMAIL_DESTINATION");
public final String DEFAULT_PROCESS_REGISTRY_DESTINATION = properties.getProperty("DEFAULT_PROCESS_REGISTRY_DESTINATION");
public final String DEFAULT_USERS_ACTIVITIES_DESTINATION = properties.getProperty("DEFAULT_USERS_ACTIVITIES_DESTINATION");
private final String DEFAULT_USERNAME = properties.getProperty("DEFAULT_USERNAME");
private final String DEFAULT_PASSWORD = properties.getProperty("DEFAULT_PASSWORD");
private final String INITIAL_CONTEXT_FACTORY = properties.getProperty("INITIAL_CONTEXT_FACTORY");
private final String PROVIDER_URL = properties.getProperty("PROVIDER_URL");
private ConnectionFactory connectionFactory = null;
private Connection connection = null;
private Session session = null;
private MessageProducer producer = null;
private MessageConsumer consumer = null;
private Destination destination = null;
private MapMessage mapMessage = null;
private Context context = null;
private ObjectMessage objMessage = null;
private static final Logger log = Logger.getLogger(SenderJMS.class.getName());
public void openConnection(final String COLA_DESTINO) {
// TODO Auto-generated method stub
try {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME));
env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD));
try {
context = new InitialContext(env);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\"");
this.setConnectionFactory((ConnectionFactory) context.lookup(connectionFactoryString));
log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI");
String destinationString = System.getProperty("destination", COLA_DESTINO);
log.info("Attempting to acquire destination \"" + destinationString + "\"");
this.setDestination((Destination) context.lookup(destinationString));
log.info("Found destination \"" + destinationString + "\" in JNDI");
// Create the JMS connection, session, producer, and consumer
this.setConnection(connectionFactory.createConnection(System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD)));
this.setSession(connection.createSession(false, Session.AUTO_ACKNOWLEDGE));
this.setProducer(session.createProducer(destination));
// consumer = session.createConsumer(destination);
connection.start();
mapMessage = session.createMapMessage();
} catch (Exception e){
e.printStackTrace();
}
}
@Override
public void closeConection() {
// TODO Auto-generated method stub
try{
if (this.getContext() != null) {
getContext().close();
}
// closing the connection takes care of the session, producer, and consumer
if (this.getConnection() != null) {
this.getConnection().close();
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ConnectionFactory getConnectionFactory() {
return connectionFactory;
}
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public Connection getConnection() {
return connection;
}
public void setConnection(Connection connection) {
this.connection = connection;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public MessageProducer getProducer() {
return producer;
}
public void setProducer(MessageProducer producer) {
this.producer = producer;
}
public MessageConsumer getConsumer() {
return consumer;
}
public void setConsumer(MessageConsumer consumer) {
this.consumer = consumer;
}
public Destination getDestination() {
return destination;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
public MapMessage getMapMessage() {
return mapMessage;
}
public void setMapMessage(MapMessage mapMessage) {
this.mapMessage = mapMessage;
}
public void setMapMessage(Map<String,String> map) {
Iterator<Entry<String, String>> interator=map.entrySet().iterator();
while(interator.hasNext()) {
Entry<String, String> thisEntry = (Entry<String, String>) interator.next();
String key = (String)thisEntry.getKey();
String value = (String)thisEntry.getValue();
try {
this.mapMessage.setString(key, value);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setMapMessage(String key, String value) {
try {
this.mapMessage.setString(key,value);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setMapMessage(String key, byte[] value) {
try {
this.mapMessage.setBytes(key, value,0, value.length);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendInfo(){
try {
producer.send(this.mapMessage);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public ObjectMessage getObjMessage() {
return objMessage;
}
public void setObjMessage(ObjectMessage objMessage) {
this.objMessage = objMessage;
}
public String getDEFAULT_USERS_ACTIVITIES_DESTINATION() {
return DEFAULT_USERS_ACTIVITIES_DESTINATION;
}
}
package ve.gob.cnti.receiver.jms;
import java.util.Map;
import javax.jms.MapMessage;
public interface IConnectionJMS {
public void openConnection(final String COLA_DESTINO);
public void sendInfo();
public void closeConection();
public MapMessage getMapMessage();
public void setMapMessage(MapMessage map);
public void setMapMessage(Map<String,String> map);
public void setMapMessage(String key, String value);
public void setMapMessage(String key, byte[] value);
public String getDEFAULT_USERS_ACTIVITIES_DESTINATION();
}
package ve.gob.cnti.receiver.jms;
import javax.jms.MapMessage;
public interface ISenderJMS {
public void sendActivitiesRegistry(MapMessage messages);
}
package ve.gob.cnti.receiver.jms;
import java.util.logging.Logger;
import javax.jms.JMSException;
import javax.jms.MapMessage;
public class SenderJMS implements ISenderJMS {
private static final Logger log = Logger.getLogger(SenderJMS.class.getName());
IConnectionJMS connectionJMS=new ConnectionJMS();
public SenderJMS(){
}
@Override
public void sendActivitiesRegistry(MapMessage menssagesFrondEnd) {
log.info("Enviando el mensaje para el portal ciudadano");
connectionJMS.openConnection(connectionJMS.getDEFAULT_USERS_ACTIVITIES_DESTINATION());
try {
System.out.println("la cedula es "+menssagesFrondEnd.getString("cedula"));
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectionJMS.setMapMessage(menssagesFrondEnd);
connectionJMS.sendInfo();
connectionJMS.closeConection();
}
}
package ve.gob.cnti.receiver.mail;
import java.io.File;
import java.io.Serializable;
public interface IMail extends Serializable{
public void send();
public String getSubject();
public String getBody();
public File getAttachFile();
public byte[] getReceiveFile();
public void setSubject(String subject);
public void setBody(String body);
public void setAttachFile(File attachFile);
public void setReceiveFile(byte[] file);
public void setToAddress(String toAddress);
public void setFileName(String fileName);
public void setFileExtention(String fileExtention);
public void setHtmlFormat(boolean htmlFormat);
}
package ve.gob.cnti.receiver.mail;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import ve.gob.cnti.receiver.utils.ConverFile;
import ve.gob.cnti.receiver.utils.IConverFile;
import ve.gob.cnti.receiver.utils.PropertiesReader;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;
/***********************************************
/* JavaMail SSL + Authentication - Example Code
/************************************************/
public class Mailer implements IMail
{
/**
*
*/
private static final long serialVersionUID = 6351639313038048762L;
private static final Logger log = Logger.getLogger(Mailer.class.getName());
PropertiesReader properties=new PropertiesReader();
private final String EMAIL_SERVER = properties.getProperty("EMAIL_SERVER");
private final String EMAIL_USER_NAME = properties.getProperty("EMAIL_USER_NAME");
private final String EMAIL_PASSWORD = properties.getProperty("EMAIL_PASSWORD");
private final String EMAIL_TRANSPORT = properties.getProperty("EMAIL_TRANSPORT");
private final String EMAIL_FROM_ADDRESS = properties.getProperty("EMAIL_FROM_ADDRESS");
private final String EMAIL_AUTH = properties.getProperty("EMAIL_AUTH");
private final String EMAIL_STARTSSL = properties.getProperty("EMAIL_STARTSSL");
private final String EMAIL_SSL_TRUST = properties.getProperty("EMAIL_SSL_TRUST");
private final String EMAIL_PORT = properties.getProperty("EMAIL_PORT");
private final String EMAIL_SERVER_IDENTITY = properties.getProperty("EMAIL_SERVER_IDENTITY");
private String toAddress = null;
private String cc = null;
private String bcc = null;
private String fileName=null;
private String fileExtention=null;
private boolean htmlFormat = false;
private String subject = null;
private String body = null;
private byte[] receiveFile=null;
private File attachFile=null;
public void send()
{
Properties parameters=new Properties();
parameters.put("mail."+EMAIL_TRANSPORT+".host", EMAIL_SERVER );
parameters.put("mail."+EMAIL_TRANSPORT+".port", EMAIL_PORT );
parameters.put("mail."+EMAIL_TRANSPORT+".auth", EMAIL_AUTH);
parameters.put("mail."+EMAIL_TRANSPORT+".starttls.enable", EMAIL_STARTSSL);
parameters.put("mail."+EMAIL_TRANSPORT+".ssl.checkserveridentity", EMAIL_SERVER_IDENTITY);
parameters.put("mail."+EMAIL_TRANSPORT+".ssl.trust", EMAIL_SSL_TRUST);
Session ses = Session.getInstance(parameters);
log.info("enviando correo");
ses.setDebug(false);
try{
MimeMessage msg = new MimeMessage(ses);
log.info("esta es el correo de "+EMAIL_FROM_ADDRESS);
msg.setFrom(new InternetAddress(EMAIL_FROM_ADDRESS));
if (toAddress != null)
{
msg.addRecipients(Message.RecipientType.TO, this.getToAddress());
}
if (cc != null)
{
msg.setRecipients(Message.RecipientType.CC
,InternetAddress.parse(this.getCc(), false));
}
if (bcc != null)
{
msg.setRecipients(Message.RecipientType.BCC
,InternetAddress.parse(this.getBcc(), false));
}
/*if (htmlFormat)
{
msg.setContent(this.getBody(), "text/html");
}
else
{
msg.setContent(this.getBody(), "text/plain");
} */
log.info("asunto atachado al correo"+this.getSubject());
log.info("contenido atachado al correo"+this.getBody());
msg.setSubject(this.getSubject());
if(this.getReceiveFile()!=null){
Multipart multipart = new MimeMultipart();
/*MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");*/
MimeBodyPart attachPart = new MimeBodyPart();
MimeBodyPart attachPart1 = new MimeBodyPart();
try {
IConverFile converFile=new ConverFile();
this.setAttachFile(converFile.converterBytesToFile(this.getReceiveFile()));
attachPart.attachFile(this.getAttachFile());
attachPart.setFileName(fileName);
if (htmlFormat)
{
attachPart1.setContent(this.getBody(), "text/plain; charset=UTF-8");
}
else
{
attachPart1.setContent(this.getBody(), "text/plain; charset=UTF-8");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
multipart.addBodyPart(attachPart);
multipart.addBodyPart(attachPart1);
msg.setContent(multipart);
}else {
if (htmlFormat)
{
msg.setContent(this.getBody(), "text/html; charset=UTF-8");
}
else
{
msg.setContent(this.getBody(), "text/plain; charset=UTF-8");
}
}
msg.saveChanges();
Transport tr = ses.getTransport(EMAIL_TRANSPORT);
tr.connect(EMAIL_SERVER ,EMAIL_USER_NAME, EMAIL_PASSWORD);
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();
}
catch(MessagingException e)
{
e.printStackTrace();
}
}
public String getCc() {
return cc;
}
public void setCc(String cc) {
this.cc = cc;
}
public String getBcc() {
return bcc;
}
public void setBcc(String bcc) {
this.bcc = bcc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public PropertiesReader getProperties() {
return properties;
}
public void setProperties(PropertiesReader properties) {
this.properties = properties;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddres) {
this.toAddress = toAddres;
}
public byte[] getReceiveFile() {
return receiveFile;
}
public void setReceiveFile(byte[] receiveFile) {
this.receiveFile = receiveFile;
}
public File getAttachFile() {
return attachFile;
}
public void setAttachFile(File attachFile) {
this.attachFile = attachFile;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileExtention() {
return fileExtention;
}
public void setFileExtention(String fileExtention) {
this.fileExtention = fileExtention;
}
public boolean isHtmlFormat() {
return htmlFormat;
}
public void setHtmlFormat(boolean htmlFormat) {
this.htmlFormat = htmlFormat;
}
}
class MyPasswordAuthenticator extends Authenticator
{
String user;
String pw;
public MyPasswordAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
\ No newline at end of file
package ve.gob.cnti.receiver.test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.cedarsoftware.util.io.JsonReader;
import com.cedarsoftware.util.io.JsonWriter;
public class JMSTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String> data=new HashMap<String,String>();
for(int i=0;i<20;i++){
data.put("data","data");
data.put("data1", "cisco"+i);
String json;
try {
json = JsonWriter.objectToJson(data);
System.out.println(json);
Map<String, String> values= JsonReader.jsonToMaps(json);
System.out.println(values.get("data"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package ve.gob.cnti.receiver.test;
import java.util.ResourceBundle;
import ve.gob.cnti.receiver.utils.PropertiesReader;
public class PropertiesTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//PropertiesReader properties=new PropertiesReader();
}
}
package ve.gob.cnti.receiver.test;
import java.util.HashMap;
import java.util.Map;
import ve.gob.cnti.receiver.jdbc.ConnectionJDBC;
import ve.gob.cnti.receiver.jdbc.IConnectionJDBC;
public class TestDataBase {
public static void main(String[] arg){
Map<String, String> data=new HashMap<String,String>();
data.put("id","1001");
data.put("cedula","10009973");
data.put("fechasolicitud", "2014-01-16 00:12:00.0 UTC");
data.put("lastupdate", "2014-01-16 00:12:00.0 UTC");
data.put("fecha_nac", "2014-01-16 00:12:00.0 UTC");
data.put("nombres", "Yamil Orozco");
data.put("sexo", "M");
data.put("pais_orig", "VEN");
data.put("estado_orig", "CSS");
data.put("parroquia_orig", "ALT");
data.put("municipio_orig", "LIB");
data.put("tramite", "OTORGAMIENTOJUBILACIONES");
data.put("pregunta", "donde esta la cedula");
data.put("aclaratoria", "no hay data");
IConnectionJDBC connection=new ConnectionJDBC();
connection.insertRecordProcess(data);
}
}
package ve.gob.cnti.receiver.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Logger;
public class ConverDate implements IConvertDate{
private static final Logger log = Logger.getLogger(ConverDate.class.getName());
public String getFormattedTimeStampDate(String pattern, String date) {
String fecha = null;
log.info("convirtiendo fecha");
date=date.replace("<?xml version=\"1.0\" ?><date>", "").replace("</date>", "").trim();
try {
DateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:MM:ss",
Locale.ENGLISH);
Date dateObj = df.parse(date);
fecha = new SimpleDateFormat(pattern,Locale.ENGLISH).format(dateObj);
} catch (ParseException e1) {
e1.printStackTrace();
}
return fecha;
}
public String getFormattedLongDateDate(String pattern, String date) {
String fecha = null;
log.info("convirtiendo fecha");
date=date.replace("<?xml version=\"1.0\" ?><date>", "").replace("</date>", "").trim();
try {
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy",
Locale.ENGLISH);
Date dateObj = df.parse(date);
fecha = new SimpleDateFormat(pattern,Locale.ENGLISH).format(dateObj);
} catch (ParseException e1) {
e1.printStackTrace();
}
return fecha;
}
public String getFormattedShortDateDate(String pattern, String date) {
String fecha = null;
log.info("convirtiendo fecha");
date=date.replace("<?xml version=\"1.0\" ?><date>", "").replace("</date>", "").trim();
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd",
Locale.ENGLISH);
Date dateObj = df.parse(date);
fecha = new SimpleDateFormat(pattern,Locale.ENGLISH).format(dateObj);
} catch (ParseException e1) {
e1.printStackTrace();
}
return fecha;
}
}
package ve.gob.cnti.receiver.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Logger;
public class ConverFile implements IConverFile{
private File fileSender;
private long systemCurrentTime;
PropertiesReader propertiesReader=new PropertiesReader();
private final String EMAIL_FILE_TEMP=propertiesReader.getProperty("EMAIL_FILE_TEMP");
private static final Logger log = Logger.getLogger(ConverFile.class.getName());
public File converterBytesToFile(byte[] fileReceive){
log.info("convirtiendo el archivo de tipo byte[] a file");
FileOutputStream fileOuputStream;
String file=EMAIL_FILE_TEMP;
systemCurrentTime=System.currentTimeMillis() / 1000L;
file+=String.valueOf(systemCurrentTime);
log.info("convirtiendo el archivo de tipo byte[] a file");
log.info("ruta del archivo a enviar"+file);
try {
fileOuputStream = new FileOutputStream(file);
fileOuputStream.write(fileReceive);
fileOuputStream.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileSender=new File(file);
return fileSender;
}
}
package ve.gob.cnti.receiver.utils;
import java.io.File;
public interface IConverFile {
public File converterBytesToFile(byte[] fileReceive);
}
package ve.gob.cnti.receiver.utils;
public interface IConvertDate {
public String getFormattedTimeStampDate(String pattern, String date);
public String getFormattedLongDateDate(String pattern, String date);
public String getFormattedShortDateDate(String pattern, String date);
}
package ve.gob.cnti.receiver.utils;
import java.util.Map;
import javax.jms.MapMessage;
public interface IMapMessageConverter {
public Map<String,String> converMapMessageToMap(MapMessage mapMessage);
}
package ve.gob.cnti.receiver.utils;
public interface IPropertiesReader {
public String getProperty(String key);
}
package ve.gob.cnti.receiver.utils;
public interface IRamdomNumber {
public int randInt(int min, int max);
}
package ve.gob.cnti.receiver.utils;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.jms.JMSException;
import javax.jms.MapMessage;
public class MapMessageConverter implements IMapMessageConverter{
private static final Logger log = Logger.getLogger(MapMessageConverter.class.getName());
@SuppressWarnings("rawtypes")
public Map<String,String> converMapMessageToMap(MapMessage mapMessage){
Enumeration mapNames;
Map<String,String> values=new HashMap<String,String>();
try {
mapNames = mapMessage.getMapNames();
String eachName;
String eachValue;
while ( mapNames.hasMoreElements() ){
eachName = (String) mapNames.nextElement();
if(eachName.indexOf("Bytes")<0){
eachValue = (String) mapMessage.getObject(eachName);
values.put(eachName,eachValue);
log.info("nombre"+eachName+"value"+eachValue);
}
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return values;
}
}
package ve.gob.cnti.receiver.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;
import java.util.logging.Logger;
public class PropertiesReader implements IPropertiesReader {
Properties props = new Properties();
private static final Logger log = Logger.getLogger(PropertiesReader.class.getName());
public PropertiesReader(){
log.info("Ubicacion del Archivo de configuracion="+System.getProperty("jboss.server.config.dir")+"/"+"receiverEJB.properties");
FileInputStream inputStream = null;
String path=System.getProperty("jboss.server.config.dir")+"/"+"receiverEJB.properties";
try {
inputStream = new FileInputStream(path);
props.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public PropertiesReader(String processName){
log.info("Ubicacion del Archivo de configuracion="+System.getProperty("jboss.server.config.dir")+"/"+processName);
InputStream inputStream = null;
String path=System.getProperty("jboss.server.config.dir")+"/"+processName+".properties";
try {
inputStream = new FileInputStream(path);
Reader reader = new InputStreamReader(inputStream, "UTF-8");
props.load(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getProperty(String key){
//System.out.println("clave="+key+"resultado"+props.getProperty(key));
return props.getProperty(key);
}
public PropertiesReader(String pathtest,String test){
//log.info("Ubicacion del Archivo de configuracion="+System.getProperty("jboss.server.config.dir")+"/"+processName);
FileInputStream inputStream = null;
String path=pathtest+".properties";
try {
inputStream = new FileInputStream(path);
props.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package ve.gob.cnti.receiver.utils;
import java.util.Random;
public class RamdomNumber implements IRamdomNumber{
public RamdomNumber() {
// TODO Auto-generated constructor stub
}
public int randInt(int min, int max) {
// NOTE: Usually this should be a field rather than a method
// variable so that it is not re-seeded every call.
Random rand = new Random(System.currentTimeMillis());
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
File added
CREATE TABLE proceso_instancias_hist
(
id_instancia bigint NOT NULL,
fecha_inicio date NOT NULL,
fecha_fin date NOT NULL,
cedula character varying(10) NOT NULL,
nombre character varying(100) NOT NULL,
sexo character varying(10) NOT NULL,
fecha_nac date NOT NULL,
pais_orig character varying(50) NOT NULL,
estado_orig character varying(50),
municipio_orig character varying(50),
tramite character varying(70) NOT NULL,
datos_sol xml,
apellido character varying(70),
parroquia_orig character varying(50),
nacionalidad character varying(1) NOT NULL,
descripcion_proceso character varying(255),
CONSTRAINT ig_pk_inscantia PRIMARY KEY (id_instancia)
);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment