Java tutorial
/* * Copyright (c) 2013 The Finnish Board of Education - Opetushallitus * * This program is free software: Licensed under the EUPL, Version 1.1 or - as * soon as they will be approved by the European Commission - subsequent versions * of the EUPL (the "Licence"); * * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ package fi.vm.sade.log.client; import org.springframework.jms.core.JmsTemplate; import fi.vm.sade.log.model.LogEvent; import fi.vm.sade.log.model.Tapahtuma; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import javax.jms.TextMessage; import org.slf4j.LoggerFactory; import org.springframework.jms.core.MessageCreator; public class LoggerJms implements Logger { private static final org.slf4j.Logger log = LoggerFactory.getLogger(LoggerJms.class); private JmsTemplate jmsTemplate; @Override public void log(final Tapahtuma tapahtuma) { log.debug("log({})", tapahtuma); if (jmsTemplate == null) { throw new IllegalStateException("LoggerJms - invalid configuration 'jsmTemplate' not available!"); } final LogEvent event = new LogEvent(tapahtuma); // Convert message to TextMessage with LogEvent as XML in payload jmsTemplate.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage(); message.setText(encode(event)); log.debug(" sending log message - text={}", message.getText()); return message; } }); } public void setJmsTemplate(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } /** * Encode messages to string (xml). * * @param event * @return */ public static String encode(LogEvent event) { if (event == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLEncoder xmlEncoder = new XMLEncoder(baos); xmlEncoder.writeObject(event); xmlEncoder.close(); return baos.toString(); } /** * Decode XML to LogEvent. Encoded in "encode" method. * * @param xml * @return */ public static LogEvent decode(String xml) { if (xml == null) { return null; } ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); XMLDecoder xmlDecoder = new XMLDecoder(bais); LogEvent logEvent = (LogEvent) xmlDecoder.readObject(); xmlDecoder.close(); return logEvent; } }