01: /*
02: * HA-JDBC: High-Availability JDBC
03: * Copyright (c) 2004-2007 Paul Ferraro
04: *
05: * This library is free software; you can redistribute it and/or modify it
06: * under the terms of the GNU Lesser General Public License as published by the
07: * Free Software Foundation; either version 2.1 of the License, or (at your
08: * option) any later version.
09: *
10: * This library is distributed in the hope that it will be useful, but WITHOUT
11: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
13: * for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public License
16: * along with this library; if not, write to the Free Software Foundation,
17: * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18: *
19: * Contact: ferraro@users.sourceforge.net
20: */
21: package net.sf.hajdbc.sql;
22:
23: import java.sql.SQLException;
24: import java.util.NoSuchElementException;
25: import java.util.SortedMap;
26: import java.util.TreeMap;
27:
28: import net.sf.hajdbc.Balancer;
29: import net.sf.hajdbc.Database;
30: import net.sf.hajdbc.DatabaseCluster;
31: import net.sf.hajdbc.Messages;
32:
33: /**
34: * @author Paul Ferraro
35: * @param <D>
36: * @param <T>
37: * @param <R>
38: */
39: public class DatabaseReadInvocationStrategy<D, T, R> implements
40: InvocationStrategy<D, T, R> {
41: /**
42: * @see net.sf.hajdbc.sql.InvocationStrategy#invoke(net.sf.hajdbc.sql.SQLProxy, net.sf.hajdbc.sql.Invoker)
43: */
44: @Override
45: public R invoke(SQLProxy<D, T> proxy, Invoker<D, T, R> invoker)
46: throws Exception {
47: SortedMap<Database<D>, R> map = this .invokeAll(proxy, invoker);
48:
49: return map.get(map.firstKey());
50: }
51:
52: protected SortedMap<Database<D>, R> invokeAll(SQLProxy<D, T> proxy,
53: Invoker<D, T, R> invoker) throws Exception {
54: DatabaseCluster<D> cluster = proxy.getDatabaseCluster();
55: Balancer<D> balancer = cluster.getBalancer();
56:
57: try {
58: while (true) {
59: Database<D> database = balancer.next();
60: T object = proxy.getObject(database);
61:
62: try {
63: balancer.beforeInvocation(database);
64:
65: R result = invoker.invoke(database, object);
66:
67: SortedMap<Database<D>, R> resultMap = new TreeMap<Database<D>, R>();
68:
69: resultMap.put(database, result);
70:
71: return resultMap;
72: } catch (Exception e) {
73: proxy.handleFailure(database, e);
74: } finally {
75: balancer.afterInvocation(database);
76: }
77: }
78: } catch (NoSuchElementException e) {
79: throw new SQLException(Messages.getMessage(
80: Messages.NO_ACTIVE_DATABASES, cluster));
81: }
82: }
83: }
|