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

Java tutorial

Introduction

Here is the source code for net.sheehantech.cherry.pool.KeyedPooledPushSocketFactory.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 org.apache.commons.pool2.BaseKeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLSocketFactory;
import java.net.Socket;
import java.util.Map;

public class KeyedPooledPushSocketFactory<K> extends BaseKeyedPooledObjectFactory<K, PooledPushSocket> {

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

    private Map<K, SSLSocketFactory> socketFactories;
    private Map<K, String> gateways;
    private Map<K, Integer> ports;

    public KeyedPooledPushSocketFactory(Map<K, SSLSocketFactory> socketFactories, Map<K, String> gateways,
            Map<K, Integer> ports) {
        super();
        this.socketFactories = socketFactories;
        this.gateways = gateways;
        this.ports = ports;
    }

    @Override
    public PooledPushSocket create(K k) throws Exception {
        Socket socket = socketFactories.get(k).createSocket(gateways.get(k), ports.get(k));
        socket.setKeepAlive(true);
        PooledPushSocket pushSocket = new PooledPushSocket(socket);
        pushSocket.prepare();
        logger.info("Initialised new socket {}", pushSocket);
        return pushSocket;
    }

    @Override
    public PooledObject wrap(PooledPushSocket pushSocket) {
        logger.debug("Wrapping push socket {}", pushSocket);
        return (new DefaultPooledObject<PooledPushSocket>(pushSocket));
    }

    @Override
    public void destroyObject(K k, PooledObject<PooledPushSocket> pooledObject) {
        PooledPushSocket pushSocket = pooledObject.getObject();
        pushSocket.close();
        logger.debug("Closed push socket {}", pushSocket);
    }

    @Override
    public boolean validateObject(K k, PooledObject<PooledPushSocket> pooledObject) {
        logger.debug("Validating socket {}", pooledObject.getObject());
        return (pooledObject.getObject().test());
    }

}