summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cmscore/connector/HttpConnFactory.java
blob: 208fc5e7f9b2afe589063fbcf5d2267c15c81414 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// 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
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.connector;


import com.netscape.certsrv.base.*;
import com.netscape.certsrv.logging.*;
import com.netscape.certsrv.apps.*;
import com.netscape.certsrv.connector.*;
import com.netscape.cmscore.connector.*;
import com.netscape.certsrv.logging.*;
import com.netscape.cmsutil.http.*;
import com.netscape.cmsutil.net.*;
import com.netscape.certsrv.authority.*;
import java.util.*;
import java.io.*;


/**
 * Factory for getting HTTP Connections to a HTTPO server
 */
public class HttpConnFactory {
    protected int mMinConns = 1;
    protected int mMaxConns = 30;

    private ILogger mLogger = CMS.getLogger();

    private int mNumConns = 0;      // number of available conns in array
    private int mTotal = 0;		// total num conns 
    private IHttpConnection mMasterConn = null; // master connection object.
    private IHttpConnection mConns[];
    private IAuthority mSource = null;
    private IRemoteAuthority mDest = null;
    private String mNickname = "";
    private int    mTimeout = 0;

    /**
     * default value for the above at init time.
     */
    private boolean mDefErrorIfDown = false;

    /**
     * Constructor for initializing from the config store.
     * must be followed by init(IConfigStore)
     */
    public HttpConnFactory() {
    }

    /**
     * Constructor for HttpConnFactory
     * @param minConns minimum number of connections to have available
     * @param maxConns max number of connections to have available. This is 
     * @param serverInfo server connection info - host, port, etc.
     */
    public HttpConnFactory(int minConns, int maxConns, IAuthority source, IRemoteAuthority dest, String nickname, int timeout
    ) throws EBaseException {

        CMS.debug("In HttpConnFactory constructor mTimeout " + timeout);
        mSource = source;
        mDest = dest;
        mNickname = nickname;
        mTimeout = timeout;

        init(minConns, maxConns);
    }

    /**
     * initialize parameters obtained from either constructor or 
     * config store
     * @param minConns minimum number of connection handls to have available.
     * @param maxConns maximum total number of connections to ever have.
     * @param connInfo ldap connection info.
     * @param authInfo ldap authentication info.
     * @exception ELdapException if any error occurs. 
     */
    private void init(int minConns, int maxConns 
    ) 
        throws EBaseException {

        CMS.debug("min conns " + minConns + " maxConns " + maxConns);
        if (minConns <= 0 || maxConns <= 0 || minConns > maxConns) {
            CMS.debug("bad values from CMS.cfg");   

        } else {

            mMinConns = minConns;
            mMaxConns = maxConns;
        }

        CMS.debug("before creating httpconn array");

        mConns = new IHttpConnection[mMaxConns];

        // Create connection handle and make initial connection

        CMS.debug("before makeConnection");

        CMS.debug(
            "initializing HttpConnFactory with mininum " + mMinConns + " and maximum " + mMaxConns +
            " connections to ");

        // initalize minimum number of connection handles available.
        //makeMinimum();

        CMS.debug("leaving HttpConnFactory init.");
    }

    private IHttpConnection createConnection() throws EBaseException {

        IHttpConnection retConn = null;

        CMS.debug("In HttpConnFactory.createConnection.");

        try {
            ISocketFactory tFactory = new JssSSLSocketFactory(mNickname);
        
            if (mTimeout == 0) {
                retConn = CMS.getHttpConnection(mDest, tFactory);
            } else {
                retConn = CMS.getHttpConnection(mDest, tFactory, mTimeout);
            }

        }  catch (Exception e) {

            CMS.debug("can't make new Htpp Connection");

            throw new EBaseException(
                    "Can't create new Http Connection"); 
        }
       
        return retConn;
    }

    /**
     * makes the minumum number of connections
     */
    private void makeMinimum() throws EBaseException {

        CMS.debug("In HttpConnFactory.makeMinimum.");
        int increment;

        if (mNumConns < mMinConns && mTotal <= mMaxConns) {

            increment = Math.min(mMinConns - mNumConns, mMaxConns - mTotal);

            if (increment == 0)
                return;

            CMS.debug(
                "increasing minimum connections by " + increment);
            for (int i = increment - 1; i >= 0; i--) {
                mConns[i] = (IHttpConnection) createConnection();
            }
            mTotal += increment;
            mNumConns += increment;
            CMS.debug("new total available http connections " + mTotal);
            CMS.debug("new number of http connections " + mNumConns);
        }
    }

    /**
     * gets a conenction from this factory. 
     * All connections obtained from the factory must be returned by 
     * returnConn() method.
     * The best thing to do is to put returnConn in a finally clause so it
     * always gets called. For example, 
     * <pre>
     *	  IHttpConnection c = null;
     *    try { 
     *		c = factory.getConn();
     * 		myclass.do_something_with_c(c);
     *	  }
     *    catch (EBaseException e) {
     *		handle_error_here();
     *	  }
     *	  finally {
     *		factory.returnConn(c);
     *    }
     * </pre>
     */
    public IHttpConnection getConn() 
        throws EBaseException {
        return getConn(true);
    }

    /**
     * Returns a Http connection - a clone of the master connection.
     * All connections should be returned to the factory using returnConn()
     * to recycle connection objects.
     * If not returned the limited max number is affected but if that 
     * number is large not much harm is done.
     * Returns null if maximum number of connections reached.
     * The best thing to do is to put returnConn in a finally clause so it
     * always gets called. For example, 
     * <pre>
     *	  IHttpConnnection c = null;
     *    try { 
     *		c = factory.getConn();
     * 		myclass.do_something_with_c(c);
     *	  }
     *    catch (EBaseException e) {
     *		handle_error_here();
     *	  }
     *	  finally {
     *		factory.returnConn(c);
     *    }
     * </pre>
     */ 
    public synchronized IHttpConnection getConn(boolean waitForConn) 
        throws EBaseException {
        boolean waited = false;

        CMS.debug("In HttpConnFactory.getConn");
        if (mNumConns == 0) 
            makeMinimum();
        if (mNumConns == 0) {
            if (!waitForConn)
                return null;
            try {
                CMS.debug("getConn: out of http connections");
                log(ILogger.LL_WARN, 
                    "Ran out of http connections available " 
                );
                waited = true;
                CMS.debug("HttpConn:about to wait for a new http connection");
                while (mNumConns == 0) 
                    wait();

                CMS.debug("HttpConn:done waiting for new http connection");
            } catch (InterruptedException e) {
            }
        } 
        mNumConns--;
        IHttpConnection conn = mConns[mNumConns];

        mConns[mNumConns] = null;

        if (waited) {
            CMS.debug("HttpConn:had to wait for an available connection from pool");
            log(ILogger.LL_WARN, 
                "Http connections are available again in http connection pool " 
            );
        }
        CMS.debug("HttpgetConn: mNumConns now " + mNumConns);

        return conn;
    }

    /**
     * Teturn connection to the factory. 
     * This is mandatory after a getConn().
     * The best thing to do is to put returnConn in a finally clause so it
     * always gets called. For example, 
     * <pre>
     *	  IHttpConnection c = null;
     *    try { 
     *		c = factory.getConn();
     * 		myclass.do_something_with_c(c);
     *	  }
     *    catch (EBaseException e) {
     *		handle_error_here();
     *	  }
     *	  finally {
     *		factory.returnConn(c);
     *    }
     * </pre>
     */
    public synchronized void returnConn(IHttpConnection conn) {

        CMS.debug("In HttpConnFactory.returnConn");
        if (conn == null) {
            return;
        }
        IHttpConnection boundconn = (IHttpConnection) conn;

        for (int i = 0; i < mNumConns; i++) {
            if (mConns[i] == conn) {
                CMS.debug(
                    "returnConn: previously returned connection. " + conn);

            }
        }
        mConns[mNumConns++] = boundconn;
        CMS.debug("HttpreturnConn: mNumConns now " + mNumConns);
        notify();
    }

    /**
     * handy routine for logging in this class.
     */
    private void log(int level, String msg) {
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_LDAP, level,
            "In Http (bound) connection pool to" +
            msg);
    }

    protected void finalize()
        throws Exception {
    }
}