Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.bbva.kyob;
- import java.io.ByteArrayOutputStream;
- import javax.jms.JMSException;
- import javax.persistence.EntityManager;
- import javax.xml.bind.JAXBContext;
- import javax.xml.bind.JAXBException;
- import javax.xml.bind.Marshaller;
- import javax.xml.transform.stream.StreamResult;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.jms.connection.CachingConnectionFactory;
- import org.springframework.jms.core.JmsTemplate;
- import com.bbva.kyob.domain.StatesConfig;
- import com.bbva.kyob.services.IRespuestaEstadosMessageCreator;
- import com.bbva.kyob.services.impl.EstadoMonitorizacionService;
- import com.bbva.kyob.services.impl.RespuestaEstadosMessageCreator;
- import com.bbva.kyob.util.AlertasPatrolEnum;
- import com.tibco.tibjms.TibjmsTopicConnectionFactory;
- import javax.jms.Connection;
- import javax.jms.ConnectionFactory;
- import javax.jms.MessageConsumer;
- import javax.jms.MessageProducer;
- import javax.jms.Queue;
- import javax.jms.Session;
- import javax.jms.TextMessage;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- import java.util.Hashtable;
- import java.util.UUID;
- /**
- * Recuperacion estado y grupo estados
- * Business Logic implementation.
- */
- public class KYOBTS0301ESTransaction extends AbstractKYOBTS0301ESTransaction {
- /** El Log para la transaccion. */
- private static final Logger LOGGER = LoggerFactory.getLogger(KYOBTS0301ESTransaction.class);
- /**
- * JMS_TIBCO_URL_KEY
- */
- public static final String JMS_TIBCO_URL_KEY = "tibco.ems.url";
- /**
- * JMS_TIBCO_USER_KEY
- */
- public static final String JMS_TIBCO_USER_KEY = "tibco.ems.user";
- /**
- * JMS_TIBCO_PSSWD_KEY
- */
- public static final String JMS_TIBCO_PSSWD_KEY = "tibco.ems.passw";
- /**
- * The constant CONNECTION_FACTTORY.
- */
- public static final String JMS_TIBCO_CONN_FACT = "tibco.ems.connectionFactory";
- /**
- * The constant PROVIDER_CTX_FACTRY.
- */
- private static final String PROVIDER_CTX_FACTRY = "com.tibco.tibjms.naming.TibjmsInitialContextFactory";
- /**
- * The Connection factory.
- */
- private transient ConnectionFactory connectionFactory;
- /**
- * The Connection.
- */
- private transient final ThreadLocal<Connection> connection = new ThreadLocal<Connection>();
- /**
- * The User name.
- */
- private final String userName;
- /**
- * The Password.
- */
- private final String password;
- /**
- * The Client iD.
- */
- private final String clientID;
- /**
- * The Timeout.
- */
- private final Long timeout;
- @Override
- public void execute() {
- try {
- long tTotalInicio = System.currentTimeMillis();
- LOGGER.info("Iniciando TXs KYOBTS0301ES.");
- EntityManager entityManager = this.getEntityManagerFactory().createEntityManager();
- EstadoMonitorizacionService estadoMonitorizacionService = new EstadoMonitorizacionService(entityManager);
- StatesConfig statesConfig = new StatesConfig(estadoMonitorizacionService.findAllEstadosMonitorizacion());
- if (statesConfig.getTmEstadoMonitorizacion() == null) {
- LOGGER.error(AlertasPatrolEnum.A01_ONE_ELA_EST.toString());
- LOGGER.error("statesConfig.getTmEstadosMonitorizacion is null");
- } else {
- // Creación del mensaje
- IRespuestaEstadosMessageCreator respuestaEstadosMessageCreator = new RespuestaEstadosMessageCreator();
- respuestaEstadosMessageCreator.setXmlDocument(marshaller(statesConfig).toString());
- respuestaEstadosMessageCreator.setQueueDestination(this.getProperty("queueEstadoGrupo.name"));
- // EnvÃo Mensaje
- sendMessage(respuestaEstadosMessageCreator);
- }
- long tTotalFinal = System.currentTimeMillis();
- LOGGER.info("Tiempo Total en envÃo correcto XML TXs KYOBTS0301ES: " + (tTotalFinal - tTotalInicio) + " ms.");
- } catch (JAXBException e) {
- LOGGER.error(AlertasPatrolEnum.A02_ONE_ELA_EST.toString());
- LOGGER.error("JAXBException" + e.getMessage());
- } catch (JMSException e) {
- LOGGER.error(AlertasPatrolEnum.A02_ONE_ELA_EST.toString());
- LOGGER.error("JMSException" + e.getMessage());
- }
- }
- /**
- * EnvÃo del mensaje
- *
- * @param respuestaEstadosMessageCreator Mensaje a enviar
- * @throws JMSException
- */
- private ConnectionFactory crearConexion(final String tibcoUrl,
- final String defaultConnectionFactory,
- final String tibcoUser, final String tibcoPsswd, final Long timeout,
- final String clientID) throws JMSException{
- this.userName = tibcoUser;
- this.password = tibcoPsswd;
- this.timeout = timeout;
- this.clientID = clientID;
- final Hashtable<String,String> env = new Hashtable<String,String>();
- env.put(Context.INITIAL_CONTEXT_FACTORY, PROVIDER_CTX_FACTRY);
- env.put(Context.PROVIDER_URL, tibcoUrl);
- if (this.userName != null) {
- env.put(Context.SECURITY_PRINCIPAL, this.userName);
- if (this.password != null) {
- env.put(Context.SECURITY_CREDENTIALS, this.password);
- }
- }
- try {
- final InitialContext jndiContext = new InitialContext(env);
- LOGGER.debug("Iniciando factoria de conexion EMS:"+tibcoUrl);
- this.connectionFactory = (ConnectionFactory)jndiContext.lookup(defaultConnectionFactory);
- LOGGER.debug("Devolviendo factoria de conexion EMS:"+tibcoUrl);
- } catch (NamingException ne) {
- LOGGER.error("Lookup error for provider url: "+ tibcoUrl, ne);
- }
- return this.connectionFactory;
- }
- private void sendMessage(final IRespuestaEstadosMessageCreator respuestaEstadosMessageCreator) throws JMSException {
- //TibjmsTopicConnectionFactory connectionFactory = new TibjmsTopicConnectionFactory(this.getProperty("tibco.ems.url"));
- //connectionFactory.setUserName(this.getProperty("tibco.ems.user"));
- //connectionFactory.setUserPassword(this.getProperty("tibco.ems.passw"));
- Session session = null;
- MessageProducer producer = null;
- ConnectionFactory connectionFactory;
- if(connectionFactory == null)
- {
- CachingConnectionFactory connection = new crearConexion(JMS_TIBCO_URL_KEY, defaultConnectionFactory, JMS_TIBCO_USER_KEY, JMS_TIBCO_PSSWD_KEY, timeout, clientID);
- }
- session = this.connection.get().createSession(false, Session.AUTO_ACKNOWLEDGE);
- try{
- final Queue destinationSend = session.createQueue(sendQueue);
- producer = session.createProducer(destinationSend);
- final String correlationId = UUID.randomUUID().toString();
- final TextMessage message = session.createTextMessage(requestMessage);
- // Set the JMSReplyTo
- message.setJMSReplyTo(destinationReply);
- message.setJMSCorrelationID(correlationId);
- LOGGER.debug("Created Message with correlationID----->" + correlationId);
- // And, send the request
- producer.send(message);
- LOGGER.debug("Message send!! with correlationID=" + correlationId + " to queue:" + sendQueue);
- LOGGER.debug("Data connection : " + this.connection.get().toString());
- }catch(JMSException jmex){
- LOGGER.error("SendAndReceiveTextMessage Error with clientID '"+ this.connection.get().getClientID() +"', " +
- "error: "+jmex.getMessage(), jmex);
- throw jmex;
- }
- finally{
- if(producer!=null){
- producer.close();
- LOGGER.debug("Producer closed..");
- }
- if(session!=null){
- session.close();
- LOGGER.debug("Session closed..");
- }
- }
- //CachingConnectionFactory connection = new CachingConnectionFactory(connectionFactory);
- // Configuracion
- //JmsTemplate jmsTemplateSend = new JmsTemplate(connection);
- //jmsTemplateSend.setDefaultDestinationName(this.getProperty("queueEstadoGrupo.name"));
- //jmsTemplateSend.setPubSubDomain(true);
- // Time to live
- //jmsTemplateSend.setExplicitQosEnabled(true);
- //jmsTemplateSend.setTimeToLive(Long.valueOf(this.getProperty("queueEstadoGrupo.timeToLive")));
- jmsTemplateSend.send(respuestaEstadosMessageCreator);
- connection.destroy();
- }
- /**
- * Método que prepara y parsea el objeto recibido como parámetro
- *
- * @param statesConfig Estados de monitorización y grupos asociados
- * @return XML generado
- * @throws JAXBException
- */
- private ByteArrayOutputStream marshaller(final StatesConfig statesConfig) throws JAXBException {
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- JAXBContext jaxbContext = JAXBContext.newInstance(StatesConfig.class);
- Marshaller estadosGruposMarshaller = jaxbContext.createMarshaller();
- // Encoding
- estadosGruposMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- // Output pretty printed
- estadosGruposMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- // Localización del esquema
- estadosGruposMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, this.getProperty("urlEsquemaXML"));
- // Conversión
- estadosGruposMarshaller.marshal(statesConfig, new StreamResult(byteArrayOutputStream));
- return byteArrayOutputStream;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement