Advertisement
Guest User

Untitled

a guest
Oct 14th, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
XBasic 9.41 KB | None | 0 0
  1. package com.bbva.kyob;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4.  
  5. import javax.jms.JMSException;
  6. import javax.persistence.EntityManager;
  7. import javax.xml.bind.JAXBContext;
  8. import javax.xml.bind.JAXBException;
  9. import javax.xml.bind.Marshaller;
  10. import javax.xml.transform.stream.StreamResult;
  11.  
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.jms.connection.CachingConnectionFactory;
  15. import org.springframework.jms.core.JmsTemplate;
  16.  
  17. import com.bbva.kyob.domain.StatesConfig;
  18. import com.bbva.kyob.services.IRespuestaEstadosMessageCreator;
  19. import com.bbva.kyob.services.impl.EstadoMonitorizacionService;
  20. import com.bbva.kyob.services.impl.RespuestaEstadosMessageCreator;
  21. import com.bbva.kyob.util.AlertasPatrolEnum;
  22. import com.tibco.tibjms.TibjmsTopicConnectionFactory;
  23.  
  24. import javax.jms.Connection;
  25. import javax.jms.ConnectionFactory;
  26. import javax.jms.MessageConsumer;
  27. import javax.jms.MessageProducer;
  28. import javax.jms.Queue;
  29. import javax.jms.Session;
  30. import javax.jms.TextMessage;
  31. import javax.naming.Context;
  32. import javax.naming.InitialContext;
  33. import javax.naming.NamingException;
  34. import java.util.Hashtable;
  35. import java.util.UUID;
  36.  
  37. /**
  38.  * Recuperacion estado y grupo estados
  39.  * Business Logic implementation.
  40.  */
  41. public class KYOBTS0301ESTransaction extends AbstractKYOBTS0301ESTransaction {
  42.     /** El Log para la transaccion. */  
  43.     private static final Logger LOGGER = LoggerFactory.getLogger(KYOBTS0301ESTransaction.class);
  44.        
  45.         /**
  46.      * JMS_TIBCO_URL_KEY
  47.      */
  48.     public static final String JMS_TIBCO_URL_KEY          = "tibco.ems.url";
  49.     /**
  50.      * JMS_TIBCO_USER_KEY
  51.      */
  52.     public static final String JMS_TIBCO_USER_KEY         = "tibco.ems.user";
  53.     /**
  54.      * JMS_TIBCO_PSSWD_KEY
  55.      */
  56.     public static final String JMS_TIBCO_PSSWD_KEY   = "tibco.ems.passw";
  57.  
  58.     /**
  59.      * The constant CONNECTION_FACTTORY.
  60.      */
  61.     public static final String JMS_TIBCO_CONN_FACT   = "tibco.ems.connectionFactory";
  62.  
  63.     /**
  64.      * The constant PROVIDER_CTX_FACTRY.
  65.      */
  66.     private static final String  PROVIDER_CTX_FACTRY = "com.tibco.tibjms.naming.TibjmsInitialContextFactory";
  67.  
  68.     /**
  69.      * The Connection factory.
  70.      */
  71.     private transient ConnectionFactory connectionFactory;
  72.  
  73.     /**
  74.      * The Connection.
  75.      */
  76.     private transient final ThreadLocal<Connection> connection = new ThreadLocal<Connection>();
  77.  
  78.     /**
  79.      * The User name.
  80.      */
  81.     private final String userName;
  82.  
  83.     /**
  84.      * The Password.
  85.      */
  86.     private final String password;
  87.  
  88.     /**
  89.      * The Client iD.
  90.      */
  91.     private final String clientID;
  92.  
  93.     /**
  94.      * The Timeout.
  95.      */
  96.     private final Long timeout;
  97.        
  98.        
  99.     @Override
  100.     public void execute() {
  101.         try {  
  102.             long tTotalInicio = System.currentTimeMillis();
  103.             LOGGER.info("Iniciando TXs KYOBTS0301ES.");
  104.            
  105.             EntityManager entityManager = this.getEntityManagerFactory().createEntityManager();
  106.            
  107.             EstadoMonitorizacionService estadoMonitorizacionService = new EstadoMonitorizacionService(entityManager);
  108.            
  109.             StatesConfig statesConfig = new StatesConfig(estadoMonitorizacionService.findAllEstadosMonitorizacion());
  110.            
  111.             if (statesConfig.getTmEstadoMonitorizacion() == null) {
  112.                 LOGGER.error(AlertasPatrolEnum.A01_ONE_ELA_EST.toString());
  113.                 LOGGER.error("statesConfig.getTmEstadosMonitorizacion is null");
  114.             } else {
  115.                 // Creación del mensaje
  116.                 IRespuestaEstadosMessageCreator respuestaEstadosMessageCreator = new RespuestaEstadosMessageCreator();
  117.  
  118.                 respuestaEstadosMessageCreator.setXmlDocument(marshaller(statesConfig).toString());
  119.                 respuestaEstadosMessageCreator.setQueueDestination(this.getProperty("queueEstadoGrupo.name"));
  120.                
  121.                 // Envío Mensaje
  122.                 sendMessage(respuestaEstadosMessageCreator);
  123.             }
  124.            
  125.             long tTotalFinal = System.currentTimeMillis();
  126.             LOGGER.info("Tiempo Total en envío correcto XML TXs KYOBTS0301ES: " + (tTotalFinal - tTotalInicio) + " ms.");
  127.         } catch (JAXBException e) {
  128.             LOGGER.error(AlertasPatrolEnum.A02_ONE_ELA_EST.toString());
  129.             LOGGER.error("JAXBException" + e.getMessage());
  130.         } catch (JMSException e) {
  131.             LOGGER.error(AlertasPatrolEnum.A02_ONE_ELA_EST.toString());
  132.             LOGGER.error("JMSException" + e.getMessage());
  133.         }
  134.     }
  135.    
  136.     /**
  137.      * Envío del mensaje
  138.      *
  139.      * @param respuestaEstadosMessageCreator Mensaje a enviar
  140.      * @throws JMSException
  141.      */
  142.      private ConnectionFactory crearConexion(final String tibcoUrl,
  143.             final String defaultConnectionFactory,
  144.             final String tibcoUser, final String tibcoPsswd, final Long timeout,
  145.             final String clientID) throws JMSException{
  146.        
  147.         this.userName = tibcoUser;
  148.         this.password = tibcoPsswd;
  149.         this.timeout = timeout;
  150.         this.clientID = clientID;
  151.                
  152.          final Hashtable<String,String> env = new Hashtable<String,String>();
  153.             env.put(Context.INITIAL_CONTEXT_FACTORY, PROVIDER_CTX_FACTRY);
  154.             env.put(Context.PROVIDER_URL, tibcoUrl);
  155.  
  156.             if (this.userName != null) {
  157.                 env.put(Context.SECURITY_PRINCIPAL, this.userName);
  158.  
  159.                 if (this.password != null) {
  160.                     env.put(Context.SECURITY_CREDENTIALS, this.password);
  161.                 }
  162.             }
  163.  
  164.             try {
  165.                 final InitialContext jndiContext = new InitialContext(env);
  166.                 LOGGER.debug("Iniciando factoria de conexion EMS:"+tibcoUrl);
  167.                 this.connectionFactory = (ConnectionFactory)jndiContext.lookup(defaultConnectionFactory);
  168.                 LOGGER.debug("Devolviendo factoria de conexion EMS:"+tibcoUrl);
  169.             } catch (NamingException ne) {
  170.                 LOGGER.error("Lookup error for provider url: "+ tibcoUrl, ne);
  171.             }
  172.            return  this.connectionFactory;
  173.     }
  174.      
  175.      
  176.      
  177.      
  178.      
  179.     private void sendMessage(final IRespuestaEstadosMessageCreator respuestaEstadosMessageCreator) throws JMSException {
  180.         //TibjmsTopicConnectionFactory connectionFactory = new TibjmsTopicConnectionFactory(this.getProperty("tibco.ems.url"));
  181.         //connectionFactory.setUserName(this.getProperty("tibco.ems.user"));
  182.         //connectionFactory.setUserPassword(this.getProperty("tibco.ems.passw"));
  183.         Session session = null;
  184.         MessageProducer producer = null;
  185.         ConnectionFactory connectionFactory;
  186.        
  187.         if(connectionFactory == null)
  188.         {          
  189.             CachingConnectionFactory connection = new crearConexion(JMS_TIBCO_URL_KEY, defaultConnectionFactory, JMS_TIBCO_USER_KEY, JMS_TIBCO_PSSWD_KEY, timeout, clientID);
  190.         }
  191.  
  192.         session = this.connection.get().createSession(false, Session.AUTO_ACKNOWLEDGE);
  193.         try{
  194.             final Queue destinationSend = session.createQueue(sendQueue);
  195.             producer = session.createProducer(destinationSend);
  196.            
  197.             final String correlationId = UUID.randomUUID().toString();
  198.             final TextMessage message = session.createTextMessage(requestMessage);
  199.             // Set the JMSReplyTo
  200.             message.setJMSReplyTo(destinationReply);
  201.             message.setJMSCorrelationID(correlationId);
  202.  
  203.             LOGGER.debug("Created Message with correlationID----->" + correlationId);
  204.  
  205.             // And, send the request
  206.             producer.send(message);
  207.             LOGGER.debug("Message send!! with correlationID=" + correlationId + " to queue:" + sendQueue);
  208.             LOGGER.debug("Data connection : " + this.connection.get().toString());
  209.            
  210.         }catch(JMSException jmex){
  211.              LOGGER.error("SendAndReceiveTextMessage Error with clientID '"+ this.connection.get().getClientID() +"', " +
  212.                     "error: "+jmex.getMessage(), jmex);
  213.             throw jmex;
  214.         }
  215.         finally{
  216.  
  217.             if(producer!=null){
  218.                 producer.close();
  219.                 LOGGER.debug("Producer closed..");
  220.             }
  221.             if(session!=null){
  222.                 session.close();
  223.                 LOGGER.debug("Session closed..");
  224.             }
  225.         }
  226.  
  227.            
  228.             //CachingConnectionFactory connection = new CachingConnectionFactory(connectionFactory);
  229.            
  230.             // Configuracion
  231.             //JmsTemplate jmsTemplateSend = new JmsTemplate(connection);
  232.             //jmsTemplateSend.setDefaultDestinationName(this.getProperty("queueEstadoGrupo.name"));
  233.             //jmsTemplateSend.setPubSubDomain(true);
  234.            
  235.             // Time to live
  236.             //jmsTemplateSend.setExplicitQosEnabled(true);
  237.             //jmsTemplateSend.setTimeToLive(Long.valueOf(this.getProperty("queueEstadoGrupo.timeToLive")));
  238.            
  239.             jmsTemplateSend.send(respuestaEstadosMessageCreator);
  240.            
  241.             connection.destroy();
  242.  
  243.     }
  244.    
  245.     /**
  246.      * Método que prepara y parsea el objeto recibido como parámetro
  247.      *
  248.      * @param statesConfig Estados de monitorización y grupos asociados
  249.      * @return XML generado
  250.      * @throws JAXBException
  251.      */
  252.      
  253.      
  254.      
  255.     private ByteArrayOutputStream marshaller(final StatesConfig statesConfig) throws JAXBException  {
  256.         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  257.        
  258.         JAXBContext jaxbContext = JAXBContext.newInstance(StatesConfig.class);
  259.        
  260.         Marshaller estadosGruposMarshaller = jaxbContext.createMarshaller();
  261.        
  262.         // Encoding
  263.         estadosGruposMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
  264.         // Output pretty printed
  265.         estadosGruposMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  266.         // Localización del esquema
  267.         estadosGruposMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, this.getProperty("urlEsquemaXML"));
  268.        
  269.         // Conversión
  270.         estadosGruposMarshaller.marshal(statesConfig, new StreamResult(byteArrayOutputStream));
  271.        
  272.         return byteArrayOutputStream;
  273.     }
  274. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement