Projekt

Obecné

Profil

« Předchozí | Další » 

Revize d1c461a4

Přidáno uživatelem Tomáš Šimandl před více než 6 roky(ů)

Update and refactor models for DB access.

Zobrazit rozdíly:

sources/src/main/java/cz/zcu/kiv/offscreen/servlets/api/Register.java
42 42
			errors.put("email", "Please enter e-mail address.");
43 43
		} else if (!isEmailAddressValid(email)) {
44 44
			errors.put("email", "Please enter valid e-mail address.");
45
		} else if (user.existsEmail(email)) {
45
		} else if (user.isEmailExists(email)) {
46 46
			errors.put("email", "E-mail already exists.");
47 47
		}
48 48

  
49 49
		if (Strings.isNullOrEmpty(username)) {
50 50
			errors.put("username", "Please enter username.");
51
		} else if (user.existsNick(username)) {
51
		} else if (user.isNickExists(username)) {
52 52
			errors.put("username", "Nickname already exists.");
53 53
		}
54 54
    	
sources/src/main/java/cz/zcu/kiv/offscreen/user/DB.java
1 1
package cz.zcu.kiv.offscreen.user;
2 2

  
3
import java.sql.Connection;
4
import java.sql.DriverManager;
5
import java.sql.ResultSet;
6
import java.sql.SQLException;
7
import java.sql.Statement;
3
import java.sql.*;
8 4

  
9 5

  
10 6
import javax.servlet.ServletContext;
11 7

  
12 8
/**
13
 * Class Db is useful for comunication with mysql database.
9
 * Class Db is useful for communication with mysql database.
14 10
 * 
15 11
 * @author Daniel Bureš
16 12
 *
......
21 17
	
22 18
	/**
23 19
	 * Constructor opens connection do database. Access data must be save in ServletContext as InitParameter( DbUrl, DbName, DbUser, DbPsw ).
24
	 * 
25
	 * 
26 20
	 */
27 21
	public DB(ServletContext context){	
28 22
		    
29 23
			try {
30 24
				Class.forName("com.mysql.jdbc.Driver");
31
				
32
				conn = (Connection) DriverManager.getConnection(context.getInitParameter("DbUrl") + context.getInitParameter("DbName")+"?user="+ context.getInitParameter("DbUser") +"&password="+ context.getInitParameter("DbPsw") + "&useUnicode=true&characterEncoding=UTF-8");				
33
				open();
34
			} catch (ClassNotFoundException e) {
35
				System.out.println("classnotfound exception");
36
				e.printStackTrace();
37
			} catch (SQLException e) {
38
				
39
				System.out.println("sql exception");
25

  
26
				String dbUrl = context.getInitParameter("DbUrl");
27
				String dbName = context.getInitParameter("DbName");
28
				String dbUser = context.getInitParameter("DbUser");
29
				String dbPsw = context.getInitParameter("DbPsw");
30

  
31
				conn = DriverManager.getConnection(dbUrl + dbName + "?user=" + dbUser + "&password=" + dbPsw + "&useUnicode=true&characterEncoding=UTF-8");
32
				conn.setAutoCommit(true);
33
			} catch (ClassNotFoundException | SQLException e) {
40 34
				e.printStackTrace();
41 35
			}
42 36
	}
43
	
37

  
44 38
	/**
45
	 * Method creates sql tables in database. And insert users: admin, user1, user2, user3
39
	 * Method return prepared statement for inserting of values
40

  
41
	 * @param query query with ? on values.
42
	 * @param returnGeneratedKeys true - RETURN_GENERATED_KEYS flag is set, false - no flag is set
46 43
	 */
47
	public void open() throws SQLException{
48
		//conn = (Connection) DriverManager.getConnection(serverName +"?user="+ userName +"&password="+ password + "&useUnicode=true&characterEncoding=UTF-8");
49
		conn.setAutoCommit(true);
50
		Statement stat = conn.createStatement();
51
						
44
	PreparedStatement getPreparedStatement(String query, boolean returnGeneratedKeys) throws SQLException {
45
		if(returnGeneratedKeys)
46
			return conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
47
		else
48
			return conn.prepareStatement(query);
52 49
	}
53
	
50

  
54 51
	/**
55
	 * Method returns actual connection to database.
56
	 * 
57
	 * @return actual connection to database.
52
	 * Method execute sql query like SELECT created with prepared statement and returns affected rows as resultSet or null.
53
	 *
54
	 * @param preparedStatement prepared statement with query and set all parameters.
55
	 * @return ResultSet - data from database.
58 56
	 */
59
	public Connection getConn(){
60
		return conn;		
57
	ResultSet executeQuery(PreparedStatement preparedStatement){
58
		try {
59
			preparedStatement.execute();
60
			return preparedStatement.getResultSet();
61
		} catch (SQLException e) {
62
			e.printStackTrace();
63
		}
64
		return null;
61 65
	}
62
	
66

  
63 67
	/**
64
	 * Method execute sql query. Sql query can be INSERT, DELETE, UPDATE
65
	 * @return count of affected rows
68
	 * Method execute update or insert sql query created with prepared statement and return resultSet of generated keys or null.
69
	 * @param preparedStatement prepared statement with query and set all parameters.
70
	 * @return ResultSet - generated keys or null.
71
	 */
72
	ResultSet executeUpdate(PreparedStatement preparedStatement){
73
		try {
74
			preparedStatement.executeUpdate();
75
			return preparedStatement.getGeneratedKeys();
76
		} catch (SQLException e) {
77
			e.printStackTrace();
78
		}
79
		return null;
80
	}
81

  
82
	/**
83
	 * Method execute sql query like SELECT and returns affected rows as resultSet or null.
84
	 * @param sql - completed sql query
85
	 * @return ResultSet - data from database
86
	 */
87
	ResultSet executeQuery(String sql){
88
		try{
89
			Statement stat = conn.createStatement();
90
			stat.execute(sql);
91
			return stat.getResultSet();
92

  
93
		}catch(SQLException | NullPointerException e){
94
			e.printStackTrace();
95
		}
96
		return null;
97
	}
98

  
99
	/**
100
	 * Method execute prepared sql query. Sql query can be INSERT, DELETE, UPDATE
101
	 *
102
	 * @return count of affected rows or -1 on SQLException and -2 on NullPointerException
66 103
	 * */
67
	public int exStatement(String sql) {	
68
		Statement stat;
69
		
104
	int executeStatement(PreparedStatement preparedStatement) {
105

  
70 106
		try{
71
			stat = conn.createStatement();
72
			return stat.executeUpdate(sql);
107
			return preparedStatement.executeUpdate();
73 108
		}catch(SQLException e){
74 109
			e.printStackTrace();
75 110
			return -1;
76 111
		}catch (NullPointerException e){
77 112
			e.printStackTrace();
78 113
			return -2;
79
		}	
80
		
114
		}
81 115
	}
82
	
116

  
117

  
83 118
	/**
84
	 * Method execute sql query like SELECT and returns affected rows as resultSet or Null. 
85
	 * 
86
	 * @throws SQLException 
87
	 * @return ResultSet - data from database 
88
	 */
89
	public ResultSet exQuery(String sql){
90
		Statement stat;
91
		
119
	 * Method execute sql query. Sql query can be INSERT, DELETE, UPDATE
120
	 *
121
	 * @return count of affected rows or -1 on SQLException and -2 on NullPointerException
122
	 * */
123
	int executeStatement(String sql) {
124

  
92 125
		try{
93
			stat = conn.createStatement();
94
			stat.execute(sql);
95
			return stat.getResultSet();
126
			Statement stat = conn.createStatement();
127
			return stat.executeUpdate(sql);
96 128
		}catch(SQLException e){
97 129
			e.printStackTrace();
98
			return null;
130
			return -1;
99 131
		}catch (NullPointerException e){
100 132
			e.printStackTrace();
101
			return null;
102
		}			 
103
		
104
		
133
			return -2;
134
		}
105 135
	}
106 136

  
107 137
}
sources/src/main/java/cz/zcu/kiv/offscreen/user/Diagram.java
13 13
 */
14 14
public class Diagram {
15 15
    private DB db = null;
16
    private int id = -1;
16
    private int id = 0;
17 17

  
18 18

  
19 19
    public Diagram(DB db) {
20
        this(db, -1);
20
        this(db, 0);
21 21
    }
22 22

  
23 23
    public Diagram(DB db, int id) {
......
34 34
        return this.id;
35 35
    }
36 36

  
37
    /**
38
     * Return id of user which is owner of diagram.
39
     * @return user id
40
     */
37 41
    public int getUserId(){
38
        if(this.id < 0) return -1;
42
        if(this.id == 0) return 0;
39 43

  
40 44
        String qy = "SELECT user_id FROM diagram WHERE id = '" + this.id + "'";
41
        ResultSet rs = db.exQuery(qy);
45
        ResultSet rs = db.executeQuery(qy);
42 46

  
43 47
        try{
44 48
            if (rs != null && rs.next()) {
......
50 54
        return -1;
51 55
    }
52 56

  
57
    /**
58
     * Returns if diagram is public or not
59
     * @return true - diagram is public, false - diagram is not public
60
     */
53 61
    public boolean isPublic(){
54
        if(this.id < 0) return false;
62
        if(this.id == 0) return false;
55 63

  
56 64
        String qy = "SELECT public FROM diagram WHERE id = '" + this.id + "'";
57
        ResultSet rs = db.exQuery(qy);
65
        ResultSet rs = db.executeQuery(qy);
58 66

  
59 67
        try{
60 68
            if (rs != null && rs.next()) {
......
66 74
        return false;
67 75
    }
68 76

  
77
    /**
78
     * Returns json of diagram. Json can be send straight to frontend.
79
     */
69 80
    public String getJsonDiagram(){
70
        if(this.id < 0) return "";
81
        if(this.id == 0) return "";
71 82

  
72 83
        String qy = "SELECT graph_json FROM diagram WHERE id = '" + this.id + "'";
73
        ResultSet rs = db.exQuery(qy);
84
        ResultSet rs = db.executeQuery(qy);
74 85

  
75 86
        try{
76 87
            if (rs != null && rs.next()) {
......
88 99
     * @return created map.
89 100
     */
90 101
    public Map<String, String> getDiagram() {
91
        if (this.id < 0) return Collections.emptyMap();
102
        if (this.id == 0) return Collections.emptyMap();
92 103

  
93 104
        String qy = "SELECT * FROM diagram WHERE id = '" + this.id + "'";
94 105

  
95 106
        try {
96 107

  
97
            ResultSet rs = db.exQuery(qy);
108
            ResultSet rs = db.executeQuery(qy);
98 109
            if (rs != null && rs.next()) {
99 110
                return createMap(rs);
100 111
            }
......
113 124
     */
114 125
    public void update(Map<String, String> param) {
115 126
        try {
116
            if (this.id < 0) {
127
            if (this.id == 0) {
117 128
                // crating new diagram
118 129

  
119 130
                String name = param.get("name");
......
125 136
                String qy = "INSERT INTO diagram (name, created, last_update, user_id, public, graph_json ) " +
126 137
                        "VALUES (?, NOW(), NOW(), ?, ?, ?) ";
127 138

  
128
                PreparedStatement pst = db.getConn().prepareStatement(qy);
139
                PreparedStatement pst = db.getPreparedStatement(qy, true);
129 140
                pst.setString(1, name);
130 141
                pst.setString(2, userId);
131 142
                pst.setString(3, isPublic);
132 143
                pst.setString(4, graphJson);
133
                pst.executeUpdate();
134 144

  
135
                ResultSet rs = pst.getGeneratedKeys();
145
                ResultSet rs = db.executeUpdate(pst);
136 146

  
137
                if (rs.next()) {
147
                if (rs != null && rs.next()) {
138 148
                    this.id = rs.getInt(1);
139 149
                }
140 150
            } else {
......
144 154

  
145 155
                String qy = "UPDATE diagram SET name = ?, public = ?, graph_json = ?, last_update = NOW() WHERE id= ?";
146 156

  
147
                PreparedStatement pst = db.getConn().prepareStatement(qy);
157
                PreparedStatement pst = db.getPreparedStatement(qy, false);
148 158
                pst.setString(1, name);
149 159
                pst.setString(2, isPublic);
150 160
                pst.setString(3, graphJson);
151 161
                pst.setInt(4, this.id);
152
                pst.executeUpdate();
162

  
163
                db.executeStatement(pst);
153 164
            }
154 165
        } catch (SQLException e) {
155 166
            e.printStackTrace();
......
160 171
     * Method deletes diagram from database.
161 172
     */
162 173
    public void delete() {
163
        if (id < 0) return;
174
        if (id == 0) return;
164 175

  
165 176
        String qy = "DELETE FROM diagram WHERE id = '" + this.id + "' LIMIT 1";
166
        db.exStatement(qy);
177
        db.executeStatement(qy);
167 178
    }
168 179

  
169 180
    /**
......
173 184
     * @return number of affected rows in database
174 185
     */
175 186
    public int updateGraphJson(String graphJson){
176
        if(this.id < 0) return 0;
187
        if(this.id == 0) return 0;
177 188

  
178 189
        String qy = "UPDATE diagram SET graph_json = ? WHERE id = ?";
179 190

  
180 191
        try {
181
            PreparedStatement pst = db.getConn().prepareStatement(qy);
192
            PreparedStatement pst = db.getPreparedStatement(qy, false);
182 193
            pst.setString(1, graphJson);
183 194
            pst.setInt(2, this.id);
184
            pst.executeUpdate();
185
            return pst.getUpdateCount();
195
            return db.executeStatement(pst);
186 196

  
187 197
        } catch (SQLException e) {
188 198
            e.printStackTrace();
......
199 209
    public ArrayList<Map<String, String>> getDiagramListByUserId(int user_id) {
200 210
        String qy = "SELECT * FROM diagram WHERE user_id = '" + user_id + "' ORDER BY created DESC ";
201 211

  
202
        return createListOfMap(db.exQuery(qy));
212
        return createListOfMap(db.executeQuery(qy));
203 213
    }
204 214

  
205 215

  
......
212 222

  
213 223
        String qy = "SELECT * FROM diagram WHERE public = 1 ORDER BY name ASC ";
214 224

  
215
        return createListOfMap(db.exQuery(qy));
225
        return createListOfMap(db.executeQuery(qy));
216 226
    }
217 227

  
218 228
    /**
......
242 252
     *
243 253
     * @param rs not null result set
244 254
     * @return map of all parameters.
245
     * @throws SQLException
246 255
     */
247 256
    private Map<String,String> createMap(ResultSet rs) throws SQLException {
248 257
        HashMap<String, String> item_map = new HashMap<>();
sources/src/main/java/cz/zcu/kiv/offscreen/user/User.java
1 1
package cz.zcu.kiv.offscreen.user;
2
import java.sql.PreparedStatement;
2 3
import java.sql.ResultSet;
3 4
import java.sql.SQLException;
4
import java.sql.Statement;
5
import java.util.Collections;
5 6
import java.util.HashMap;
6 7
import java.util.Map;
7 8

  
8
import javax.servlet.ServletContext;
9

  
10 9
/**
11
 * Class CUser is used for creating, updating or loading user from database.
10
 * Class User is used for creating, updating or loading user from database.
12 11
 *
13 12
 * @author Daniel Bureš
14 13
 *
......
16 15
public class User {
17 16
	private DB db = null;
18 17
	private int id = 0;
19
	private ResultSet rs;
20
	private Map<String,String> paramStr = new HashMap<String,String>(10);
21

  
22 18

  
23 19
	/**
24 20
	 * Constructs object, where is saved db connection.
......
33 29
	public User(DB db, int id){
34 30
		this.db = db;
35 31
		this.id = id;
36

  
37
		if(id > 0){
38
			load();
39
		}
40

  
41
	}
42

  
43
	/**
44
	 * Method loads user from database. User is loaded by his id, which must be saved in object of this class.
45
	 */
46
	public void load(){
47
		String qy = "SELECT * FROM user WHERE id = '"+this.id+"' ";
48
		try {
49
			rs = db.exQuery(qy);
50
			if ( rs != null && rs.next() ) {
51
				this.id = rs.getInt("id");
52

  
53

  
54
				paramStr.put("nick", rs.getString("nick")  );
55

  
56
			}else{
57
				this.id = 0;
58
			}
59

  
60
		} catch (SQLException e) {
61
			e.printStackTrace();
62
		}
63

  
64
	}
65

  
66

  
67
	/**
68
	 * Method sets session for current user and save session to database.
69
	 *
70
	 * @param session
71
	 */
72
	public void setSession(String session){
73
		if(id > 0){
74
			String qy = "UPDATE user SET session='"+session+"' WHERE id='"+ this.id +"'";
75
			db.exStatement(qy);
76
		}
77 32
	}
78 33

  
79 34
	/**
80 35
	 * Method try to login user by his nick name and password. If login is OK then returns true else  returns false;
81 36
	 *
82
	 * @param nick
83
	 * @param psw
37
	 * @param nick users login name
38
	 * @param psw users password
84 39
	 * @return true - login ok
85 40
	 * 		   false - login failed
86 41
	 */
87 42
	public boolean login(String nick, String psw){
88
		String qy = "SELECT * FROM user WHERE nick LIKE '"+nick+"' AND psw LIKE '"+Util.MD5(psw)+"' AND active = '1' LIMIT 1";
89
		try {
90
			rs = db.exQuery(qy);
91
			if ( rs.next() ) {
43
		String qy = "SELECT * FROM user WHERE nick LIKE ? AND psw LIKE ? AND active = '1' LIMIT 1";
44

  
45
		try{
46
			PreparedStatement pst = db.getPreparedStatement(qy, false);
47
			pst.setString(1, nick);
48
			pst.setString(2, Util.MD5(psw));
49
			ResultSet rs = db.executeQuery(pst);
50

  
51
			if ( rs != null && rs.next() ) {
92 52
				if(rs.getInt("id") > 0){
93 53
					this.id = rs.getInt("id");
94
					load();
95 54
					return true;
96 55
				}
97 56
			}
......
99 58
			e.printStackTrace();
100 59
		}
101 60

  
102

  
103 61
		return false;
104 62
	}
105 63

  
106

  
107

  
108
	public void register(Map<String, String> param){
109
		try {
110
				if ( this.id  == 0 ) {
111

  
112
					String qy = "INSERT INTO user (id,created,active, nick,name, psw,session,email) " +
113
										"VALUES (	'0', " +
114
										"			NOW(), " +
115
										"			'1', " +
116
										"			'" + param.get("nick") + "',"+
117
										"			'" + param.get("name") + "',"+
118
										"			'" + Util.MD5(param.get("password")) + "'," +
119
										" 			'" + param.get("session") + "',"+
120
										" 			'" + param.get("email") + "' ) ";
121
					Statement st = db.getConn().createStatement();
122
					st.executeUpdate(qy, Statement.RETURN_GENERATED_KEYS);
123
					ResultSet rs = st.getGeneratedKeys();
124

  
125
					if(rs.next()){
126
						this.id = rs.getInt(1);
127
					}
128
				}
129

  
130
			} catch (SQLException e) {
131
				e.printStackTrace();
132
			}
133

  
134
	}
135

  
136 64
	/**
137
	 * Method saves parameters into database. if is not loaded user then is created new User.
65
	 * Method register new user to database. Id of user (variable id) must not be set.
66
	 * When register is success variable id is set.
138 67
	 *
139
	 * @param param - parameters to save
140
	 * @param cx
68
	 * @param param Parameters which describing user. Keys must be: nick, name, password, session, email.
141 69
	 */
142
	public void update(Map<String, String> param,ServletContext cx){
70
	public void register(Map<String, String> param){
143 71
		try {
144 72
			if ( this.id  == 0 ) {
145 73

  
146
					String qy = "INSERT INTO user (id,created,active) " +
147
										"VALUES ('0', NOW(), '1' ) ";
148
					Statement st = db.getConn().createStatement();
149
					st.executeUpdate(qy, Statement.RETURN_GENERATED_KEYS);
150
					ResultSet rs = st.getGeneratedKeys();
74
				String qy = "INSERT INTO user (id, created, active, nick, name, psw, session, email) " +
75
						"VALUES ( ?, NOW(), ?, ?, ?, ?, ?, ?)";
151 76

  
152
					if(rs.next()){
153
						this.id = rs.getInt(1);
154
					}
77
				PreparedStatement pst = db.getPreparedStatement(qy, true);
78
				pst.setInt(1, 0);
79
				pst.setInt(2, 1);
80
				pst.setString(3, param.get("nick"));
81
				pst.setString(4, param.get("name"));
82
				pst.setString(5, Util.MD5(param.get("password")));
83
				pst.setString(6, param.get("session"));
84
				pst.setString(7, param.get("email"));
155 85

  
86
				ResultSet rs = db.executeUpdate(pst);
156 87

  
88
				if(rs != null && rs.next()){
89
					this.id = rs.getInt(1);
90
				}
157 91
			}
158 92

  
159
			String tmp_info = param.get("info");
160
			tmp_info = tmp_info.replaceAll("\\<","&lt;");
161
			tmp_info = tmp_info.replaceAll("\\>","&gt;");
162
			tmp_info = tmp_info.replaceAll("\\n","<br \\/>");
163
			param.put("info",tmp_info);
164

  
165

  
166
			db.exStatement(	"UPDATE user " +
167
							"SET  email = '"+param.get("email")+"',"+
168
								  "nick = '"+param.get("nick")+"',"+
169
								  (param.get("noSavePsw")!=null?"":",psw = '"+param.get("psw")+"' " )+
170
								  (param.get("active")!= null && Integer.valueOf(param.get("active")) >= 0 ? ",active = '" + param.get("active") + "'": "" )+
171
								  " WHERE id = '" + this.id +"'");
172

  
173

  
174

  
93
		} catch (SQLException e) {
94
			e.printStackTrace();
95
		}
96
	}
175 97

  
98
	/**
99
	 * Return all information about user from database stored in map. Keys of map are: id, nick, name, psw, session,
100
	 * active, created, email.
101
	 *
102
	 * @return created map or empty map.
103
	 */
104
	public Map<String, String> getUser(){
105
		String qy = "SELECT * FROM user WHERE id = '" + this.id + "'";
106
		try {
107
			ResultSet rs = db.executeQuery(qy);
176 108

  
109
			if ( rs != null && rs.next() ) {
110
				Map<String, String> params = new HashMap<>(8);
111
				params.put("id", rs.getString("id"));
112
				params.put("nick", rs.getString("nick"));
113
				params.put("name", rs.getString("name"));
114
				params.put("psw", rs.getString("psw"));
115
				params.put("session", rs.getString("session"));
116
				params.put("active", rs.getString("active"));
117
				params.put("created", rs.getString("created"));
118
				params.put("email", rs.getString("email"));
119

  
120
				return params;
121

  
122
			} else {
123
				this.id = 0;
124
			}
177 125
		} catch (SQLException e) {
178
			cx.setAttribute("DEBUG", "e " + e.getMessage() + " state: "+e.getSQLState() + " sqlerrcode" + e.getErrorCode());
179

  
180 126
			e.printStackTrace();
181 127
		}
182 128

  
129
		return Collections.emptyMap();
183 130
	}
184 131

  
185

  
186 132
	/**
187
	 * Returns id of loaded user.
133
	 * Returns id of user. Value 0 indicates not existing user.
188 134
	 *
189
	 * @return int
135
	 * @return int with user id or 0.
190 136
	 */
191 137
	public int getId(){
192 138
		return id;
193 139
	}
194 140

  
195 141
	/**
196
	 * Returns loaded parameters, which are saved in Map<String,String>.
197
	 * @return Map<String,String> loaded parameters, which are saved in Map<String,String>.
142
	 * Method sets session for current user and save session to database.
198 143
	 */
199
	public Map<String,String> getParam(){
200
		return paramStr;
144
	public void setSession(String session){
145
		if(id > 0){
146
			String qy = "UPDATE user SET session= ? WHERE id='" + this.id + "'";
147

  
148
			try {
149

  
150
				PreparedStatement pst = db.getPreparedStatement(qy, false);
151
				pst.setString(1, session);
152
				db.executeStatement(pst);
153

  
154
			} catch (SQLException e) {
155
				e.printStackTrace();
156
			}
157
		}
201 158
	}
202 159

  
203 160
	/**
204
	 * Method returns nick of loaded user.
205
	 * @return
161
	 * Method saves parameters into database. Method can change only email, nick and active parameters.
162
	 * @param param - parameters to save
206 163
	 */
207
	public String getNick(){
208
		return paramStr.get("nick");
164
	public void update(Map<String, String> param) {
165
		if ( this.id  != 0 ) {
166
			try {
167
				String qy = "UPDATE user SET  email = ?, nick = ?, active = ? WHERE id = ?";
168

  
169
				PreparedStatement pst = db.getPreparedStatement(qy, false);
170
				pst.setString(1, param.get("email"));
171
				pst.setString(2, param.get("nick"));
172
				pst.setString(3, param.get("active"));
173
				pst.setInt(4, this.id);
174

  
175
				db.executeStatement(pst);
176
			} catch (SQLException e) {
177
				e.printStackTrace();
178
			}
179
		}
209 180
	}
210 181

  
211 182
	/**
212
	 * Method checks if exists user with nick.
213
	 * @param testNick
214
	 * @return
183
	 * Returns nick of user or empty string when no user is loaded.
215 184
	 */
216
	public boolean existsNick(String testNick){
217
		boolean exists = false;
218

  
219
		String qy = "SELECT * FROM user WHERE LOWER(nick) LIKE '"+testNick.toLowerCase()+"' LIMIT 1";
220
		try {
221
			rs = db.exQuery(qy);
185
	public String getNick(){
186
		if (this.id != 0) {
187
			String qy = "SELECT nick FROM user WHERE id = '" + this.id + "'";
188
			ResultSet rs = db.executeQuery(qy);
222 189

  
223
			if ( rs.next() ) {
224
				if(rs.getInt("id") > 0){
225
					return true;
190
			try{
191
				if (rs != null && rs.next()) {
192
					return rs.getString("nick");
226 193
				}
194
			}  catch (SQLException e){
195
				e.printStackTrace();
227 196
			}
228

  
229
		} catch (SQLException e) {
230
			e.printStackTrace();
231 197
		}
232 198

  
233
		return exists;
199
		return "";
200
	}
234 201

  
202
	/**
203
	 * Method checks if exists user with input nick.
204
	 *
205
	 * @return true - nick already exists, false - otherwise
206
	 */
207
	public boolean isNickExists(String testNick){
208
		return isExists("nick", testNick);
235 209
	}
236 210

  
211
	/**
212
	 * Method checks if exists user with input e-mail.
213
	 *
214
	 * @return true - e-mail already exists, false otherwise
215
	 */
216
	public boolean isEmailExists(String testEmail){
217
		return isExists("email", testEmail);
218
	}
237 219

  
238 220
	/**
239
	 * Method checks if user exists by him e-mail.
221
	 * Method checks if exists user whose attribute given by name exists with given value
240 222
	 *
241
	 * @param testEmail
242
	 * @return
223
	 * @return true - minimal one user exists, false - otherwise
243 224
	 */
244
	public boolean existsEmail(String testEmail){
245
		boolean exists = false;
225
	private boolean isExists(String name, String value){
226
		String qy = "SELECT * FROM user WHERE LOWER(" + name + ") LIKE ? LIMIT 1";
246 227

  
247
		String qy = "SELECT * FROM user WHERE LOWER(email) LIKE '"+testEmail.toLowerCase()+"' LIMIT 1";
248 228
		try {
249
			rs = db.exQuery(qy);
229
			PreparedStatement pst = db.getPreparedStatement(qy, false);
230
			pst.setString(1, value.toLowerCase());
231
			ResultSet rs = db.executeQuery(pst);
250 232

  
251
			if ( rs.next() ) {
252
				if ( rs.getInt("id") > 0 ) {
253
					return true;
254
				}
233
			if ( rs != null && rs.next() && rs.getInt("id") > 0) {
234
				return true;
255 235
			}
256

  
257 236
		} catch (SQLException e) {
258 237
			e.printStackTrace();
259 238
		}
260 239

  
261
		return exists;
262

  
240
		return false;
263 241
	}
264

  
265

  
266

  
267 242
}
sources/src/main/java/cz/zcu/kiv/offscreen/user/Util.java
1 1
package cz.zcu.kiv.offscreen.user;
2 2

  
3
import net.sf.json.JSONObject;
4

  
5
import java.util.ArrayList;
6
import java.util.Iterator;
7
import java.util.Map;
8 3
import java.util.regex.Matcher;
9 4
import java.util.regex.Pattern;
10 5

  
11
public class Util {
12
	
13
	
14
	
6
class Util {
7

  
15 8
	/**
16 9
	 *	Method do a hash code from string.
17 10
	 *
18 11
	 * @param md5 - String to hash
19 12
	 * @return String - hashcode 
20 13
	 */
21
	public static String MD5(String md5) {
14
	static String MD5(String md5) {
22 15
		   try {
23 16
		        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
24 17
		        byte[] array = md.digest(md5.getBytes());
......
31 24
		    }
32 25
		    return null;
33 26
	}
34
	
35
	
36
	public static String formatDate(String date){	
27

  
28
	static String formatDate(String date){
37 29
		String pattern = "(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}).*";
38 30
		Pattern pat = Pattern.compile(pattern);
39 31
		Matcher matches = pat.matcher(date);
......
45 37
		
46 38
		return formatedDate;
47 39
	}
48

  
49
	
50
	
51
	
52
	
53 40
}

Také k dispozici: Unified diff