001: /*
002: * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
003: *
004: * This file is part of Resin(R) Open Source
005: *
006: * Each copy or derived work must preserve the copyright notice and this
007: * notice unmodified.
008: *
009: * Resin Open Source is free software; you can redistribute it and/or modify
010: * it under the terms of the GNU General Public License as published by
011: * the Free Software Foundation; either version 2 of the License, or
012: * (at your option) any later version.
013: *
014: * Resin Open Source is distributed in the hope that it will be useful,
015: * but WITHOUT ANY WARRANTY; without even the implied warranty of
016: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
017: * of NON-INFRINGEMENT. See the GNU General Public License for more
018: * details.
019: *
020: * You should have received a copy of the GNU General Public License
021: * along with Resin Open Source; if not, write to the
022: * Free Software Foundation, Inc.
023: * 59 Temple Place, Suite 330
024: * Boston, MA 02111-1307 USA
025: *
026: * @author Scott Ferguson
027: */
028:
029: package com.caucho.amber;
030:
031: import com.caucho.util.L10N;
032:
033: import java.sql.SQLException;
034:
035: /**
036: * Context for amber.
037: */
038: public class AmberContext {
039: private static final L10N L = new L10N(AmberContext.class);
040:
041: private static final ThreadLocal<AmberContext> _localContext = new ThreadLocal<AmberContext>();
042:
043: private AmberFactory _factory;
044: private int _depth;
045: private AmberConnection _aConn;
046:
047: /**
048: * Creates a new AmberContext.
049: */
050: private AmberContext(AmberFactory factory) {
051: _factory = factory;
052: }
053:
054: /**
055: * Creates a new amber context.
056: */
057: public static AmberContext create(AmberFactory factory) {
058: AmberContext context = _localContext.get();
059:
060: if (context != null)
061: context._depth++;
062: else {
063: context = new AmberContext(factory);
064: _localContext.set(context);
065: }
066:
067: return context;
068: }
069:
070: /**
071: * Gets the current connection.
072: */
073: public static AmberConnection getConnection() throws SQLException {
074: AmberContext context = _localContext.get();
075:
076: if (context == null)
077: throw new AmberException(L
078: .l("No amber context is available."));
079:
080: if (context._aConn == null)
081: context._aConn = context._factory.getConnection();
082:
083: return context._aConn;
084: }
085:
086: /**
087: * Closes the connection.
088: */
089: public static void close() {
090: AmberContext context = _localContext.get();
091:
092: if (context._depth == 0) {
093: _localContext.set(null);
094:
095: AmberConnection conn = context._aConn;
096: if (conn != null)
097: conn.close();
098: } else
099: context._depth--;
100: }
101: }
|