net.sheehantech.cherry.pool.KeyedPooledSendNotificationTask.java Source code

Java tutorial

Introduction

Here is the source code for net.sheehantech.cherry.pool.KeyedPooledSendNotificationTask.java

Source

/*
 * This file is part of Cherry.
 *
 * Cherry is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cherry 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
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cherry.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package net.sheehantech.cherry.pool;

import net.sheehantech.cherry.Notification;
import net.sheehantech.cherry.ProtocolException;
import net.sheehantech.cherry.PushFailedException;
import net.sheehantech.cherry.PushResult;
import org.apache.commons.pool2.KeyedObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;

public class KeyedPooledSendNotificationTask<K> implements Callable<PushResult> {

    private Logger logger = LoggerFactory.getLogger(KeyedPooledSendNotificationTask.class);

    private KeyedObjectPool<K, PooledPushSocket> pool;
    private K k;
    private Notification notification;

    public KeyedPooledSendNotificationTask(KeyedObjectPool<K, PooledPushSocket> pool, K k,
            Notification notification) {
        this.pool = pool;
        this.k = k;
        this.notification = notification;
    }

    @Override
    public PushResult call() throws PushFailedException, ProtocolException {
        try {
            PooledPushSocket pushSocket = pool.borrowObject(k);
            logger.debug("Borrowed push socket {} for key {}", pushSocket, k);
            pushSocket.write(notification);
            PushResult pushResult = pushSocket.read();
            pool.returnObject(k, pushSocket);
            logger.debug("Returned push socket {} for key {}", pushSocket, k);
            return pushResult;
        } catch (PushFailedException e) {
            throw (e);
        } catch (ProtocolException e) {
            throw (e);
        } catch (Exception e) {
            logger.warn("Push notification to token {} failed: {}", notification.getToken(), e.getMessage());
            logger.warn("Error", e);
            throw (new PushFailedException(e));
        }
    }
}