com.davidak.bet.XmppAppender.java Source code

Java tutorial

Introduction

Here is the source code for com.davidak.bet.XmppAppender.java

Source

/**
 * Copyright 2010 CosmoCode GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.davidak.bet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.springframework.util.StringUtils;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.boolex.EvaluationException;
import ch.qos.logback.core.boolex.EventEvaluator;

/**
 * XMPP appender for logback.
 */
public final class XmppAppender extends AppenderBase<LoggingEvent> {

    private String host;
    private Integer port;
    private String domain;
    private String user;
    private String password;
    private Boolean SASLAuthenticationEnabled;
    private Set<String> contacts;

    private XMPPConnection xmpp;

    private EventEvaluator<LoggingEvent> evaluator;

    @Override
    public void start() {
        ConnectionConfiguration config = new ConnectionConfiguration(host, port, domain);
        config.setSASLAuthenticationEnabled(SASLAuthenticationEnabled);

        try {
            xmpp = new XMPPConnection(config);
            xmpp.connect();
            xmpp.login(user, password);
        } catch (XMPPException e) {
            addError(e.getMessage());
            return;
        }
        super.start();
    }

    @Override
    protected void append(LoggingEvent eventObject) {
        if (evaluate(eventObject)) {
            if (xmpp != null) {
                if (xmpp.isConnected() && xmpp.isAuthenticated()) {

                    boolean sendToAll = true;
                    if (contacts != null && contacts.size() > 0) {
                        sendToContacts(contacts, eventObject);
                        sendToAll = false;
                    }

                    if (sendToAll) {
                        sendToAll(eventObject);
                    }

                } else {
                    addError("Error sending message to xmpp host and recipient, connection is closed or"
                            + "the user is not authenticated ");
                }
            }
        }
    }

    private boolean evaluate(LoggingEvent event) {
        if (evaluator == null) {
            return true;
        }
        try {
            return evaluator.evaluate(event);
        } catch (EvaluationException e) {
            return false;
        }
    }

    private void sendToContacts(Collection<String> contacts, LoggingEvent eventObject) {
        for (String contact : contacts) {
            sentMessageToContact(contact, eventObject);
        }
    }

    private void sendToAll(LoggingEvent eventObject) {
        Roster roster = xmpp.getRoster();
        List<String> contacts = new ArrayList<String>(roster.getEntries().size());

        for (RosterEntry entry : roster.getEntries()) {
            contacts.add(entry.getUser());
        }

        sendToContacts(contacts, eventObject);
    }

    private void sentMessageToContact(String contact, LoggingEvent eventObject) {
        ChatManager chatManager = xmpp.getChatManager();

        Chat chat = chatManager.createChat(contact, new MessageListener() {
            @Override
            public void processMessage(Chat arg0, Message arg1) {
            }
        });

        try {
            chat.sendMessage(eventObject.getFormattedMessage());

        } catch (XMPPException e) {
            addError("Error sending message to xmpp contact " + contact, e);
        }

    }

    public void setHost(final String host) {
        this.host = host;
    }

    public void setPort(final Integer port) {
        this.port = port;
    }

    public void setDomain(final String domain) {
        this.domain = domain;
    }

    public void setUser(final String user) {
        this.user = user;
    }

    public void setPassword(final String password) {
        this.password = password;
    }

    public void setSASLAuthenticationEnabled(final Boolean SASLAuthenticationEnabled) {
        this.SASLAuthenticationEnabled = SASLAuthenticationEnabled;
    }

    public void setContacts(final String contacts) {
        this.contacts = parseContacts(contacts);
    }

    private static Set<String> parseContacts(String contacts) {
        return StringUtils.commaDelimitedListToSet(contacts);
    }

    public void setEvaluator(final EventEvaluator<LoggingEvent> evaluator) {
        this.evaluator = evaluator;
    }
}