summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openslx/imagemaster/db/Database.java
blob: 765f782a7bb45e4b6233f09ba06c3383e9432513 (plain) (blame)
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
package org.openslx.imagemaster.db;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.log4j.Logger;
import org.openslx.imagemaster.util.Util;

public class Database
{

	private static final Logger LOGGER = Logger.getLogger( Database.class );
	/**
	 * Pool of available connections.
	 */
	private static final Queue<MysqlConnection> pool = new ConcurrentLinkedQueue<>();

	/**
	 * Set of connections currently handed out.
	 */
	private static final Set<MysqlConnection> busyConnections = Collections.newSetFromMap( new ConcurrentHashMap<MysqlConnection, Boolean>() );

	private static final String host;
	private static final String dbname;
	private static final String user;
	private static final String password;

	/**
	 * Static initializer for setting up the database connection.
	 * This gets called implicitly as soon as the class loader loads
	 * the class. In most cases that happens when the class is being
	 * accessed for the first time during run time.
	 */
	static
	{
		// Load connection info from class (TODO: Make pretty)
		Properties properties = new Properties();
		try {
			final BufferedInputStream stream = new BufferedInputStream(
					new FileInputStream(
							"config/mysql.properties" ) );
			properties.load( stream );
			stream.close();
		} catch ( FileNotFoundException e ) {
			LOGGER.fatal( "config/mysql.properties not found!" );
			System.exit( 1 );
		} catch ( IOException e ) {
			LOGGER.fatal( "Error reading from config/mysql.properties: " + e.getMessage() );
			System.exit( 1 );
		} catch ( Exception e ) {
			LOGGER.fatal( "Generic error loading mysql properties file." );
			e.printStackTrace();
			System.exit( 1 );
		}
		host = properties.getProperty( "host" );
		dbname = properties.getProperty( "db" );
		user = properties.getProperty( "user" );
		password = properties.getProperty( "password" );

		Util.notNullFatal( host, "host not set in mysql properties" );
		Util.notNullFatal( dbname, "db not set in mysql properties" );
		Util.notNullFatal( user, "user not set in mysql properties" );
		Util.notNullFatal( password, "password not set in mysql properties" );

		try {
			Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
		} catch ( InstantiationException | IllegalAccessException | ClassNotFoundException e ) {
			LOGGER.fatal( "Cannot get mysql JDBC driver!", e );
			System.exit( 1 );
		}
	}

	/**
	 * Get a connection to the database. If there is a valid connection in the
	 * pool, it will be returned. Otherwise, a new connection is created. If
	 * there are more than 20 busy connections, <code>null</code> is returned.
	 * 
	 * @return connection to database, or <code>null</code>
	 */
	public static MysqlConnection getConnection()
	{
		MysqlConnection con;
		for ( ;; ) {
			con = pool.poll();
			if ( con == null )
				break;
			if ( !con.isValid() ) {
				con.release();
				continue;
			}
			if ( !busyConnections.add( con ) )
				throw new RuntimeException( "Tried to hand out a busy connection!" );
			return con;
		}
		// No pooled connection
		if ( busyConnections.size() > 20 ) {
			LOGGER.warn( "Too many open MySQL connections. Possible connection leak!" );
			return null;
		}
		try {
			// Create fresh connection
			String uri = "jdbc:mysql://" + host + "/" + dbname
					+ "?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8"
					+ "&characterSetResults=utf8&connectionCollation=utf8mb4_unicode_ci";
			Connection rawConnection = DriverManager.getConnection( uri,
					user, password );
			// By convention in our program we don't want auto commit
			rawConnection.setAutoCommit( false );
			// Wrap into our proxy
			con = new MysqlConnection( rawConnection );
			// Keep track of busy mysql connection
			if ( !busyConnections.add( con ) )
				throw new RuntimeException( "Tried to hand out a busy connection!" );
			return con;
		} catch ( SQLException e ) {
			LOGGER.info( "Failed to connect to local mysql server", e );
		}
		return null;
	}

	/**
	 * Called by a {@link MysqlConnection} when its <code>close()</code>-method
	 * is called, so the connection will be added to the pool of available
	 * connections again.
	 * 
	 * @param connection
	 */
	static void returnConnection( MysqlConnection connection )
	{
		if ( !busyConnections.remove( connection ) )
			throw new RuntimeException( "Tried to return a mysql connection to the pool that was not taken!" );
		pool.add( connection );
	}

	/**
	 * Return true if the given sql exception is "duplicate entry XXXX for key YYYY.
	 */
	public static boolean isDuplicateKeyException( SQLException e )
	{
		return e != null && e.getErrorCode() == 1062;
	}

	//

	public static void printCharsetInformation()
	{
		LOGGER.info( "MySQL charset related variables:" );
		try ( MysqlConnection connection = Database.getConnection() ) {
			MysqlStatement stmt = connection.prepareStatement( "SHOW VARIABLES LIKE :what" );
			stmt.setString( "what", "char%" );
			ResultSet rs = stmt.executeQuery();
			while ( rs.next() ) {
				LOGGER.info( rs.getString( "Variable_name" ) + ": " + rs.getString( "Value" ) );
			}
			stmt.setString( "what", "collat%" );
			rs = stmt.executeQuery();
			while ( rs.next() ) {
				LOGGER.info( rs.getString( "Variable_name" ) + ": " + rs.getString( "Value" ) );
			}
		} catch ( SQLException e ) {
			LOGGER.error( "Query failed in Database.printCharsetInformation()", e );
		}
		LOGGER.info( "End of variables" );
	}

	public static void printDebug()
	{
		LOGGER.info( "Available: " + pool.size() );
		LOGGER.info( "Busy: " + busyConnections.size() );
	}

}// end class