Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 346e9ba2

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

Simplify communication with DB

- use of MyBatis framework

Zobrazit rozdíly:

sources/imiger-core/pom.xml
145 145
            <artifactId>mysql-connector-java</artifactId>
146 146
            <version>8.0.15</version>
147 147
        </dependency>
148
        <dependency>
149
            <groupId>org.mybatis</groupId>
150
            <artifactId>mybatis</artifactId>
151
            <version>3.5.0</version>
152
        </dependency>
148 153
    </dependencies>
149 154
</project>
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/DataAccessError.java
2 2

  
3 3
import com.google.gson.Gson;
4 4
import com.google.gson.JsonObject;
5
import org.apache.logging.log4j.LogManager;
6
import org.apache.logging.log4j.Logger;
5 7

  
6 8
import javax.servlet.ServletException;
7 9
import javax.servlet.http.HttpServlet;
......
11 13
import java.io.PrintWriter;
12 14

  
13 15
public class DataAccessError extends HttpServlet {
16
    private static final Logger logger = LogManager.getLogger();
14 17

  
15 18
    @Override
16 19
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
......
25 28

  
26 29
    private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
27 30
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
31
        logger.error("Data access exception: ", throwable);
32

  
28 33
        response.setContentType("application/json");
29 34
        PrintWriter out = response.getWriter();
30 35

  
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/UploadFiles.java
2 2

  
3 3
import cz.zcu.kiv.offscreen.modularization.ModuleProvider;
4 4
import cz.zcu.kiv.offscreen.storage.FileLoader;
5
import cz.zcu.kiv.offscreen.user.DB;
6 5
import cz.zcu.kiv.offscreen.user.DataAccessException;
7
import cz.zcu.kiv.offscreen.user.Diagram;
6
import cz.zcu.kiv.offscreen.user.dao.DiagramDAO;
8 7
import org.apache.commons.lang3.StringUtils;
9 8
import org.apache.logging.log4j.LogManager;
10 9
import org.apache.logging.log4j.Logger;
......
30 29

  
31 30
        logger.debug("Processing request");
32 31

  
33
        List<Map<String, String>> userDiagramList = new ArrayList<>();
34
        List<Map<String, String>> publicDiagramList = new ArrayList<>();
32
        List<Map<String, Object>> userDiagramList = new ArrayList<>();
33
        List<Map<String, Object>> publicDiagramList = new ArrayList<>();
35 34
        try {
36
            DB db = new DB(getServletContext());
37
            Diagram diagram = new Diagram(db);
35
            DiagramDAO diagramDAO = new DiagramDAO();
38 36

  
39 37
            if (isLoggedIn(request)) {
40 38
                logger.debug("Logged user");
41 39
                int loggedUserId = getUserId(request);
42 40

  
43
                userDiagramList = diagram.getDiagramListByUserId(loggedUserId);
41
                userDiagramList = diagramDAO.getDiagramsByUserId(loggedUserId);
44 42
            }
45 43

  
46
            publicDiagramList = diagram.getDiagramPublicList();
44
            publicDiagramList = diagramDAO.getPublicDiagrams();
47 45

  
48 46
        } catch (DataAccessException e){
49 47
            logger.error("Data access exception");
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/api/GetDBDiagram.java
2 2

  
3 3
import com.google.gson.Gson;
4 4
import cz.zcu.kiv.offscreen.servlets.BaseServlet;
5
import cz.zcu.kiv.offscreen.user.DB;
6
import cz.zcu.kiv.offscreen.user.Diagram;
5
import cz.zcu.kiv.offscreen.user.dao.DiagramDAO;
7 6
import org.apache.commons.lang3.StringUtils;
8 7
import org.apache.logging.log4j.LogManager;
9 8
import org.apache.logging.log4j.Logger;
......
11 10
import javax.servlet.http.HttpServletRequest;
12 11
import javax.servlet.http.HttpServletResponse;
13 12
import java.io.IOException;
13
import java.util.Map;
14 14

  
15 15
/**
16 16
 * This class is used for loading diagrams from database.
......
30 30
            return;
31 31
        }
32 32

  
33
        DB db = new DB(getServletContext());
34
        Diagram diagram = new Diagram(db, Integer.parseInt(diagramId));
33
        DiagramDAO diagramDAO = new DiagramDAO();
34
        Map<String, Object> diagram = diagramDAO.getDiagram(Integer.parseInt(diagramId));
35 35

  
36
        if (!diagram.isPublic() && (!isLoggedIn(request) || (isLoggedIn(request) && diagram.getUserId() != getUserId(request)))) {
36
        if (!(boolean)diagram.get("public") && (!isLoggedIn(request) || (isLoggedIn(request) && (int)diagram.get("user_id") != getUserId(request)))) {
37 37
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
38 38
            logger.debug("User is unauthorized");
39 39
            return;
40 40
        }
41 41

  
42
        String json = new Gson().toJson(diagram.getDiagram());
42
        String json = new Gson().toJson(diagram);
43 43

  
44 44
        response.setContentType("application/json");
45 45
        response.setCharacterEncoding("UTF-8");
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/api/GetDBDiagramData.java
1 1
package cz.zcu.kiv.offscreen.servlets.api;
2 2

  
3 3
import cz.zcu.kiv.offscreen.servlets.BaseServlet;
4
import cz.zcu.kiv.offscreen.user.DB;
5
import cz.zcu.kiv.offscreen.user.Diagram;
4
import cz.zcu.kiv.offscreen.user.dao.DiagramDAO;
6 5
import org.apache.commons.lang3.StringUtils;
7 6
import org.apache.logging.log4j.LogManager;
8 7
import org.apache.logging.log4j.Logger;
......
10 9
import javax.servlet.http.HttpServletRequest;
11 10
import javax.servlet.http.HttpServletResponse;
12 11
import java.io.IOException;
12
import java.util.Map;
13 13

  
14 14
/**
15 15
 * This class is used for loading diagram's graph JSON from database.
......
29 29
            return;
30 30
        }
31 31

  
32
        DB db = new DB(getServletContext());
33
        Diagram diagram = new Diagram(db, Integer.parseInt(diagramId));
32
        DiagramDAO diagramDAO = new DiagramDAO();
33
        Map<String, Object> diagram = diagramDAO.getDiagram(Integer.parseInt(diagramId));
34 34

  
35
        if (!diagram.isPublic() && (!isLoggedIn(request) || (isLoggedIn(request) && diagram.getUserId() != getUserId(request)))) {
35
        if (!(boolean)diagram.get("public") && (!isLoggedIn(request) || (isLoggedIn(request) && (int)diagram.get("user_id") != getUserId(request)))) {
36 36
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
37 37
            logger.debug("User is unauthorized");
38 38
            return;
39 39
        }
40 40

  
41
        String json = diagram.getDiagram().get("graph_json");
41
        String json = (String)diagram.get("graph_json");
42 42

  
43 43
        response.setContentType("application/json");
44 44
        response.setCharacterEncoding("UTF-8");
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/api/GetPrivateDiagrams.java
3 3
import com.google.gson.JsonArray;
4 4
import com.google.gson.JsonObject;
5 5
import cz.zcu.kiv.offscreen.servlets.BaseServlet;
6
import cz.zcu.kiv.offscreen.user.DB;
7
import cz.zcu.kiv.offscreen.user.Diagram;
6
import cz.zcu.kiv.offscreen.user.dao.DiagramDAO;
8 7
import org.apache.logging.log4j.LogManager;
9 8
import org.apache.logging.log4j.Logger;
10 9

  
......
28 27
            return;
29 28
        }
30 29

  
31
        DB db = new DB(getServletContext());
32
        Diagram diagram = new Diagram(db);
30
        DiagramDAO diagramDAO = new DiagramDAO();
33 31

  
34 32
        int loggedUserId = getUserId(request);
35
        List<Map<String, String>> userDiagramList = diagram.getDiagramListByUserId(loggedUserId);
33
        List<Map<String, Object>> userDiagramList = diagramDAO.getDiagramsByUserId(loggedUserId);
36 34

  
37 35
        JsonArray jsonArray = new JsonArray();
38
        for (Map<String, String> userDiagram : userDiagramList) {
36
        for (Map<String, Object> userDiagram : userDiagramList) {
37

  
39 38
            JsonObject jsonObject = new JsonObject();
40
            jsonObject.addProperty("id", userDiagram.get("id"));
41
            jsonObject.addProperty("name", userDiagram.get("name"));
42
            jsonObject.addProperty("created", userDiagram.get("created"));
43
            jsonObject.addProperty("last_update", userDiagram.get("last_update"));
39
            jsonObject.addProperty("id", String.valueOf(userDiagram.get("id")));
40
            jsonObject.addProperty("name", String.valueOf(userDiagram.get("name")));
41
            jsonObject.addProperty("created", String.valueOf(userDiagram.get("created")));
42
            jsonObject.addProperty("last_update", String.valueOf(userDiagram.get("last_update")));
44 43
            jsonArray.add(jsonObject);
45 44
        }
46 45

  
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/api/Login.java
2 2

  
3 3
import com.google.gson.JsonObject;
4 4
import cz.zcu.kiv.offscreen.servlets.BaseServlet;
5
import cz.zcu.kiv.offscreen.user.DB;
6
import cz.zcu.kiv.offscreen.user.User;
5
import cz.zcu.kiv.offscreen.user.dao.UserDAO;
7 6
import cz.zcu.kiv.offscreen.vo.UserVO;
8 7
import org.apache.commons.lang3.StringUtils;
9 8
import org.apache.logging.log4j.LogManager;
......
12 11
import javax.servlet.http.HttpServletRequest;
13 12
import javax.servlet.http.HttpServletResponse;
14 13
import java.io.IOException;
14
import java.util.Map;
15 15

  
16 16
public class Login extends BaseServlet {
17 17
    private static final Logger logger = LogManager.getLogger();
......
35 35
        }
36 36

  
37 37
        if (errors.size() == 0) {
38
            DB db = new DB(getServletContext());
39
            User user = new User(db);
38
            UserDAO userDAO = new UserDAO();
39
            Map<String, Object> user = userDAO.login(username, password);
40 40

  
41
            if (user.login(username, password)) {
41
            if (user != null) {
42 42
                UserVO userVO = new UserVO();
43
                userVO.setId(user.getId());
44
                userVO.setUsername(user.getNick());
43
                userVO.setId((int)user.get("id"));
44
                userVO.setUsername((String)user.get("nick"));
45 45

  
46 46
                request.getSession().setAttribute("isLoggedIn", true);
47 47
                request.getSession().setAttribute("userId", userVO.getId());
48 48
                request.getSession().setAttribute("user", userVO);
49 49

  
50 50
                JsonObject json = new JsonObject();
51
                json.addProperty("id", user.getId());
52
                json.addProperty("username", user.getNick());
51
                json.addProperty("id",(int) user.get("id"));
52
                json.addProperty("username", (String) user.get("nick"));
53 53

  
54 54

  
55 55
                response.setContentType("application/json");
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/api/Register.java
2 2

  
3 3
import com.google.gson.JsonObject;
4 4
import cz.zcu.kiv.offscreen.servlets.BaseServlet;
5
import cz.zcu.kiv.offscreen.user.DB;
6
import cz.zcu.kiv.offscreen.user.User;
5
import cz.zcu.kiv.offscreen.user.dao.UserDAO;
7 6
import org.apache.commons.lang3.StringUtils;
8 7
import org.apache.commons.validator.routines.EmailValidator;
9 8
import org.apache.logging.log4j.LogManager;
......
12 11
import javax.servlet.http.HttpServletRequest;
13 12
import javax.servlet.http.HttpServletResponse;
14 13
import java.io.IOException;
15
import java.util.HashMap;
16
import java.util.Map;
17 14

  
18 15
public class Register extends BaseServlet {
19 16

  
......
29 26
		String password = request.getParameter("password");
30 27
		String passwordCheck = request.getParameter("passwordCheck");
31 28

  
32
		DB db = new DB(getServletContext());
33
		User user = new User(db);
29
		UserDAO userDAO = new UserDAO();
34 30

  
35 31
		JsonObject errors = new JsonObject();
36 32

  
......
47 43
			errors.addProperty("email", "Please enter valid e-mail address.");
48 44
			logger.debug("Invalid e-mail address");
49 45

  
50
		} else if (user.isEmailExists(email)) {
46
		} else if (userDAO.isEmailExists(email)) {
51 47
			errors.addProperty("email", "E-mail already exists.");
52 48
			logger.debug("E-mail exists");
53 49
		}
......
56 52
			errors.addProperty("username", "Please enter username.");
57 53
			logger.debug("Empty user name");
58 54

  
59
		} else if (user.isNickExists(username)) {
55
		} else if (userDAO.isNickExists(username)) {
60 56
			errors.addProperty("username", "Nickname already exists.");
61 57
			logger.debug("Username(nickname) exists");
62 58
		}
......
75 71
		}
76 72

  
77 73
    	if (errors.size() == 0) {
78
    		Map<String, String> userMap = new HashMap<>();
79
    		userMap.put("name", name);
80
    		userMap.put("email", email);
81
    		userMap.put("nick", username);
82
    		userMap.put("password", password);
83
    		userMap.put("session", request.getSession().getId());
84

  
85
    		user.register(userMap);
74
    		userDAO.register(username, name, password, request.getSession().getId(), email);
86 75

  
87 76
			response.setStatus(HttpServletResponse.SC_CREATED);
88 77
			logger.debug("User created");
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/api/RemoveDiagram.java
1 1
package cz.zcu.kiv.offscreen.servlets.api;
2 2

  
3 3
import cz.zcu.kiv.offscreen.servlets.BaseServlet;
4
import cz.zcu.kiv.offscreen.user.DB;
5
import cz.zcu.kiv.offscreen.user.Diagram;
4
import cz.zcu.kiv.offscreen.user.dao.DiagramDAO;
6 5
import org.apache.commons.lang3.StringUtils;
7 6
import org.apache.logging.log4j.LogManager;
8 7
import org.apache.logging.log4j.Logger;
......
33 32
            return;
34 33
        }
35 34

  
36
        DB db = new DB(getServletContext());
37
        Diagram diagram = new Diagram(db, Integer.parseInt(diagramId));
35
        DiagramDAO diagramDAO = new DiagramDAO();
38 36

  
39
        if (diagram.getUserId() != loggedUserId) {
37
        if (diagramDAO.getDiagramUserId(Integer.parseInt(diagramId)) != loggedUserId) {
40 38
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
41 39
            logger.debug("User is not owner of diagram");
42 40
            return;
43 41
        }
44 42

  
45
        diagram.delete();
43
        diagramDAO.deleteDiagram(Integer.parseInt(diagramId));
46 44
        logger.debug("Diagram removed");
47 45

  
48 46
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/servlets/api/SaveDiagram.java
2 2

  
3 3
import com.google.gson.Gson;
4 4
import cz.zcu.kiv.offscreen.servlets.BaseServlet;
5
import cz.zcu.kiv.offscreen.user.DB;
6
import cz.zcu.kiv.offscreen.user.Diagram;
5
import cz.zcu.kiv.offscreen.user.dao.DiagramDAO;
7 6
import org.apache.commons.lang3.StringUtils;
8 7
import org.apache.logging.log4j.LogManager;
9 8
import org.apache.logging.log4j.Logger;
......
11 10
import javax.servlet.http.HttpServletRequest;
12 11
import javax.servlet.http.HttpServletResponse;
13 12
import java.io.IOException;
14
import java.util.HashMap;
15
import java.util.Map;
16 13

  
17 14
public class SaveDiagram extends BaseServlet {
18 15
    private static final Logger logger = LogManager.getLogger();
......
43 40
            return;
44 41
        }
45 42

  
46
        DB db = new DB(getServletContext());
47
        Diagram diagram;
43
        DiagramDAO diagramDAO = new DiagramDAO();
44

  
45
        int intDiagramId;
48 46

  
49 47
        if (StringUtils.isBlank(diagramId)) {
50 48
            logger.debug("Creating new diagram");
51
            diagram = new Diagram(db);
49
            intDiagramId = diagramDAO.createDiagram(name, Integer.toString(loggedUserId), isPublic, graphJson);
50
            logger.debug("Diagram created or updated.");
52 51

  
53 52
        } else {
54 53
            logger.debug("Getting existing diagram from database");
55
            diagram = new Diagram(db, Integer.parseInt(diagramId));
54
            intDiagramId = Integer.parseInt(diagramId);
55
            int diagramUserId = diagramDAO.getDiagramUserId(intDiagramId);
56 56

  
57
            if (loggedUserId != diagram.getUserId()) {
57
            if (loggedUserId != diagramUserId) {
58 58
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
59 59
                logger.debug("User is not owner of diagram");
60 60
                return;
61 61
            }
62
        }
63 62

  
64
        Map<String, String> diagramParams = new HashMap<>();
65
        diagramParams.put("name", name);
66
        diagramParams.put("public", isPublic);
67
        diagramParams.put("graph_json", graphJson);
68
        diagramParams.put("user_id", Integer.toString(loggedUserId));
69

  
70
        diagram.update(diagramParams);
71
        logger.debug("Diagram created or updated.");
63
            diagramDAO.updateDiagram(intDiagramId, name, isPublic, graphJson);
64
            logger.debug("Diagram updated.");
65
        }
72 66

  
73 67
        // send response
74 68

  
75
        String json = new Gson().toJson(diagram.getDiagram());
69
        String json = new Gson().toJson(diagramDAO.getDiagram(intDiagramId));
76 70

  
77 71
        response.setContentType("application/json");
78 72
        response.setCharacterEncoding("UTF-8");
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/DB.java
1
package cz.zcu.kiv.offscreen.user;
2

  
3
import org.apache.logging.log4j.LogManager;
4
import org.apache.logging.log4j.Logger;
5

  
6
import javax.servlet.ServletContext;
7
import java.sql.*;
8

  
9
/**
10
 * Class Db is useful for communication with mysql database.
11
 * 
12
 * @author Daniel Bureš
13
 *
14
 */
15

  
16
public class DB {
17

  
18
	private static final Logger logger = LogManager.getLogger();
19
	private Connection connection;
20
	
21
	/**
22
	 * Constructor opens connection do database. Access credentials must be stored in ServletContext as InitParameter.
23
	 */
24
	public DB(ServletContext context) {
25
		String driverClassName = context.getInitParameter("jdbc.driverClassName");
26
		String url = context.getInitParameter("jdbc.url");
27
		String username = context.getInitParameter("jdbc.username");
28
		String password = context.getInitParameter("jdbc.password");
29

  
30
		try {
31
			logger.debug("Opening database connection");
32
			Class.forName(driverClassName);
33
			connection = DriverManager.getConnection(url, username, password);
34
			connection.setAutoCommit(true);
35
		} catch (ClassNotFoundException | SQLException e) {
36
			logger.error("Can not open database connection: ", e);
37
			throw new DataAccessException(e);
38
		}
39
	}
40

  
41
	/**
42
	 * Method return prepared statement for inserting of values
43

  
44
	 * @param query query with ? on values.
45
	 * @param returnGeneratedKeys true - RETURN_GENERATED_KEYS flag is set, false - no flag is set
46
	 */
47
	PreparedStatement getPreparedStatement(String query, boolean returnGeneratedKeys) {
48
		try {
49
			if (returnGeneratedKeys) {
50
				return connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
51
			} else {
52
				return connection.prepareStatement(query);
53
			}
54
		}catch (SQLException e){
55
			logger.error("Can not execute query: " + query);
56
			throw new DataAccessException(e);
57
		}
58
	}
59

  
60
	/**
61
	 * Method execute sql query like SELECT created with prepared statement and returns affected rows as resultSet or null.
62
	 *
63
	 * @param preparedStatement prepared statement with query and set all parameters.
64
	 * @return ResultSet - data from database.
65
	 */
66
	ResultSet executeQuery(PreparedStatement preparedStatement) {
67
		try {
68
			preparedStatement.execute();
69
			return preparedStatement.getResultSet();
70
		} catch (SQLException e) {
71
			logger.error("Can not execute database query: ", e);
72
			throw new DataAccessException(e);
73
		}
74
	}
75

  
76
	/**
77
	 * Method execute update or insert sql query created with prepared statement and return resultSet of generated keys or null.
78
	 * @param preparedStatement prepared statement with query and set all parameters.
79
	 * @return ResultSet - generated keys or null.
80
	 */
81
	ResultSet executeUpdate(PreparedStatement preparedStatement) {
82
		try {
83
			preparedStatement.executeUpdate();
84
			return preparedStatement.getGeneratedKeys();
85
		} catch (SQLException e) {
86
			logger.error("Can not execute database query: ", e);
87
			throw new DataAccessException(e);
88
		}
89
	}
90

  
91
	/**
92
	 * Method execute sql query like SELECT and returns affected rows as resultSet or null.
93
	 * @param sql - completed sql query
94
	 * @return ResultSet - data from database
95
	 */
96
	ResultSet executeQuery(String sql) {
97
		try {
98
			Statement stat = connection.createStatement();
99
			stat.execute(sql);
100
			return stat.getResultSet();
101

  
102
		} catch(SQLException | NullPointerException e) {
103
			logger.error("Can not execute database query: ", e);
104
			throw new DataAccessException(e);
105
		}
106
	}
107

  
108
	/**
109
	 * Method execute prepared sql query. Sql query can be INSERT, DELETE, UPDATE
110
	 *
111
	 * @return count of affected rows or -1 on SQLException and -2 on NullPointerException
112
	 * */
113
	int executeStatement(PreparedStatement preparedStatement) {
114
		try {
115
			return preparedStatement.executeUpdate();
116
		} catch(NullPointerException | SQLException e) {
117
			logger.error("Can not execute database query: ", e);
118
			throw new DataAccessException(e);
119
		}
120
	}
121

  
122
}
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/Diagram.java
1
package cz.zcu.kiv.offscreen.user;
2

  
3
import org.apache.logging.log4j.LogManager;
4
import org.apache.logging.log4j.Logger;
5

  
6
import java.sql.PreparedStatement;
7
import java.sql.ResultSet;
8
import java.sql.SQLException;
9
import java.util.ArrayList;
10
import java.util.Collections;
11
import java.util.HashMap;
12
import java.util.Map;
13

  
14
/**
15
 * Class is used for saving and loading diagram params from database.
16
 *
17
 * @author Daniel Bureš
18
 * @author Tomáš Šimandl
19
 */
20
public class Diagram {
21
    private static final Logger logger = LogManager.getLogger();
22

  
23
    private DB db = null;
24
    private int id = 0;
25

  
26

  
27
    public Diagram(DB db) {
28
        this(db, 0);
29
    }
30

  
31
    public Diagram(DB db, int id) {
32
        this.db = db;
33
        this.id = id;
34
    }
35

  
36
    /**
37
     * Method returns object id.
38
     *
39
     * @return id
40
     */
41
    public int getId() {
42
        return this.id;
43
    }
44

  
45
    /**
46
     * Return id of user which is owner of diagram.
47
     * @return user id
48
     */
49
    public int getUserId(){
50
        if(this.id == 0) return 0;
51

  
52
        String qy = "SELECT user_id FROM diagram WHERE id = '" + this.id + "'";
53
        ResultSet rs = db.executeQuery(qy);
54

  
55
        try{
56
            if (rs != null && rs.next()) {
57
                return rs.getInt("user_id");
58
            }
59
        }  catch (SQLException e){
60
            logger.error("Can not get owner id: ", e);
61
            throw new DataAccessException(e);
62
        }
63
        return -1;
64
    }
65

  
66
    /**
67
     * Returns if diagram is public or not
68
     * @return true - diagram is public, false - diagram is not public
69
     */
70
    public boolean isPublic(){
71
        if(this.id == 0) return false;
72

  
73
        String qy = "SELECT public FROM diagram WHERE id = '" + this.id + "'";
74
        ResultSet rs = db.executeQuery(qy);
75

  
76
        try{
77
            if (rs != null && rs.next()) {
78
                return rs.getString("public").equals("1");
79
            }
80
        }  catch (SQLException e){
81
            logger.error("Can not check if diagram is public: ", e);
82
            throw new DataAccessException(e);
83
        }
84
        return false;
85
    }
86

  
87
    /**
88
     * Returns json of diagram. Json can be send straight to frontend.
89
     */
90
    public String getJsonDiagram(){
91
        if(this.id == 0) return "";
92

  
93
        String qy = "SELECT graph_json FROM diagram WHERE id = '" + this.id + "'";
94
        ResultSet rs = db.executeQuery(qy);
95

  
96
        try{
97
            if (rs != null && rs.next()) {
98
                return rs.getString("graph_json");
99
            }
100
        }  catch (SQLException e){
101
            logger.error("Can not get json of diagram: ", e);
102
            throw new DataAccessException(e);
103
        }
104
        return "";
105
    }
106

  
107
    /**
108
     * Method return map of values of actual diagram or empty map if id of diagram is invalid.
109
     *
110
     * @return created map.
111
     */
112
    public Map<String, String> getDiagram() {
113
        if (this.id == 0) return Collections.emptyMap();
114

  
115
        String qy = "SELECT * FROM diagram WHERE id = '" + this.id + "'";
116

  
117
        try {
118

  
119
            ResultSet rs = db.executeQuery(qy);
120
            if (rs != null && rs.next()) {
121
                return createMap(rs);
122
            }
123

  
124
        } catch (SQLException e) {
125
            logger.error("Can not get diagram: ", e);
126
            throw new DataAccessException(e);
127
        }
128

  
129
        return Collections.emptyMap();
130
    }
131

  
132
    /**
133
     * Method saves new diagram into database or update existing diagram.
134
     *
135
     * @param param - diagram parameters
136
     */
137
    public void update(Map<String, String> param) {
138
        try {
139
            if (this.id == 0) {
140
                // crating new diagram
141

  
142
                String name = param.get("name");
143
                String userId = param.get("user_id");
144
                String isPublic = param.get("public");
145
                String graphJson = param.get("graph_json");
146

  
147

  
148
                String qy = "INSERT INTO diagram (name, created, last_update, user_id, public, graph_json ) " +
149
                        "VALUES (?, NOW(), NOW(), ?, ?, ?) ";
150

  
151
                PreparedStatement pst = db.getPreparedStatement(qy, true);
152
                pst.setString(1, name);
153
                pst.setString(2, userId);
154
                pst.setString(3, isPublic);
155
                pst.setString(4, graphJson);
156

  
157
                ResultSet rs = db.executeUpdate(pst);
158

  
159
                if (rs != null && rs.next()) {
160
                    this.id = rs.getInt(1);
161
                }
162
            } else {
163
                String name = param.get("name");
164
                String isPublic = param.get("public");
165
                String graphJson = param.get("graph_json");
166

  
167
                String qy = "UPDATE diagram SET name = ?, public = ?, graph_json = ?, last_update = NOW() WHERE id= ?";
168

  
169
                PreparedStatement pst = db.getPreparedStatement(qy, false);
170
                pst.setString(1, name);
171
                pst.setString(2, isPublic);
172
                pst.setString(3, graphJson);
173
                pst.setInt(4, this.id);
174

  
175
                db.executeStatement(pst);
176
            }
177
        } catch (SQLException e) {
178
            logger.error("Can not update diagram: ", e);
179
            throw new DataAccessException(e);
180
        }
181
    }
182

  
183
    /**
184
     * Method deletes diagram from database.
185
     */
186
    public void delete() {
187
        if (this.id == 0) return;
188

  
189
        String qy = "DELETE FROM diagram WHERE id = ? LIMIT 1";
190

  
191
        try {
192
            PreparedStatement pst = db.getPreparedStatement(qy, false);
193
            pst.setInt(1, this.id);
194
            db.executeStatement(pst);
195

  
196
        } catch (SQLException e) {
197
            logger.error("Can not delete diagram: ", e);
198
            throw new DataAccessException(e);
199
        }
200
    }
201

  
202
    /**
203
     * Method returns list of diagrams, which are uploaded by given user.
204
     *
205
     * @param user_id id of user
206
     * @return created list of diagram params.
207
     */
208
    public ArrayList<Map<String, String>> getDiagramListByUserId(int user_id) {
209
        String qy = "SELECT * FROM diagram WHERE user_id = '" + user_id + "' ORDER BY created DESC ";
210

  
211
        return createListOfMap(db.executeQuery(qy));
212
    }
213

  
214

  
215
    /**
216
     * Method returns list of all public diagrams.
217
     *
218
     * @return created list of diagram params
219
     */
220
    public ArrayList<Map<String, String>> getDiagramPublicList() {
221

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

  
224
        return createListOfMap(db.executeQuery(qy));
225
    }
226

  
227
    /**
228
     * Iterate over all items in input ResultSet and return list of all founded diagrams (map of diagram parameters).
229
     *
230
     * @param rs result set which contains diagram rows.
231
     * @return created list of diagrams.
232
     */
233
    private ArrayList<Map<String,String>> createListOfMap(ResultSet rs) {
234
        ArrayList<Map<String, String>> diagram_list = new ArrayList<>();
235

  
236
        try {
237
            while (rs != null && rs.next()) {
238
                diagram_list.add(createMap(rs));
239
            }
240
            return diagram_list;
241

  
242
        } catch (SQLException e){
243
            logger.error("Can not create map from input result set: ", e);
244
            throw new DataAccessException(e);
245
        }
246
    }
247

  
248
    /**
249
     * Method take from input ResultSet all parameters of diagram. Result set must point to some row and can not be null.
250
     *
251
     * @param rs not null result set
252
     * @return map of all parameters.
253
     */
254
    private Map<String,String> createMap(ResultSet rs) throws SQLException {
255
        HashMap<String, String> item_map = new HashMap<>();
256

  
257
        item_map.put("id", String.valueOf(rs.getInt("id")));
258
        item_map.put("name", rs.getString("name"));
259
        item_map.put("created", Util.formatDate(rs.getString("created")));
260
        item_map.put("last_update", Util.formatDate(rs.getString("last_update")));
261
        item_map.put("user_id", String.valueOf(rs.getInt("user_id")));
262
        item_map.put("public", String.valueOf(rs.getInt("public")));
263
        item_map.put("graph_json", String.valueOf(rs.getString("graph_json")));
264

  
265
        return item_map;
266
    }
267
}
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/MyBatisUtil.java
1
package cz.zcu.kiv.offscreen.user;
2

  
3
import org.apache.ibatis.io.Resources;
4
import org.apache.ibatis.session.SqlSessionFactory;
5
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
6

  
7
import java.io.InputStream;
8

  
9
public class MyBatisUtil {
10
    private static final String CONFIGURATION = "mybatis-config.xml";
11
    private static SqlSessionFactory sqlSessionFactory;
12

  
13
    public static SqlSessionFactory getSqlSessionFactory() {
14

  
15
        if (sqlSessionFactory == null) {
16
            try {
17
                InputStream inputStream = Resources.getResourceAsStream(CONFIGURATION);
18
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
19
            } catch (Exception e) {
20
                throw new DataAccessException(e);
21
            }
22
        }
23
        return sqlSessionFactory;
24
    }
25
}
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/User.java
1
package cz.zcu.kiv.offscreen.user;
2
import org.apache.logging.log4j.LogManager;
3
import org.apache.logging.log4j.Logger;
4
import org.springframework.security.crypto.bcrypt.BCrypt;
5

  
6
import java.sql.PreparedStatement;
7
import java.sql.ResultSet;
8
import java.sql.SQLException;
9
import java.util.Collections;
10
import java.util.HashMap;
11
import java.util.Map;
12

  
13
/**
14
 * Class User is used for creating, updating or loading user from database.
15
 *
16
 * @author Daniel Bureš
17
 *
18
 */
19
public class User {
20

  
21
	private static final Logger logger = LogManager.getLogger();
22

  
23
	private DB db = null;
24
	private int id = 0;
25

  
26
	/**
27
	 * Constructs object, where is saved db connection.
28
	 */
29
	public User(DB db) {
30
		this(db,0);
31
	}
32

  
33
	/**
34
	 * Constructs object, where is saved db connection and user id. User, who has this id is loaded from database.
35
	 */
36
	public User(DB db, int id){
37
		this.db = db;
38
		this.id = id;
39
	}
40

  
41
	/**
42
	 * Method try to login user by his nick name and password. If login is OK then returns true else  returns false;
43
	 *
44
	 * @param nick users login name
45
	 * @param psw users password
46
	 * @return true - login ok
47
	 * 		   false - login failed
48
	 */
49
	public boolean login(String nick, String psw){
50
		String qy = "SELECT * FROM user WHERE nick LIKE ? AND active = '1' LIMIT 1";
51

  
52
		try{
53
			PreparedStatement pst = db.getPreparedStatement(qy, false);
54
			pst.setString(1, nick);
55
			ResultSet rs = db.executeQuery(pst);
56

  
57
			if ( rs != null && rs.next() ) {
58
				if(rs.getInt("id") > 0 && BCrypt.checkpw(psw, rs.getString("psw"))){
59
					this.id = rs.getInt("id");
60
					return true;
61
				}
62
			}
63
		} catch (SQLException | IllegalArgumentException e) {
64
			logger.error("Can not login user: ", e);
65
			throw new DataAccessException(e);
66
		}
67

  
68
		return false;
69
	}
70

  
71
	/**
72
	 * Method register new user to database. Id of user (variable id) must not be set.
73
	 * When register is success variable id is set.
74
	 *
75
	 * @param param Parameters which describing user. Keys must be: nick, name, password, session, email.
76
	 */
77
	public void register(Map<String, String> param){
78
		try {
79
			if ( this.id  == 0 ) {
80

  
81
				String qy = "INSERT INTO user (id, created, active, nick, name, psw, session, email) " +
82
						"VALUES ( ?, NOW(), ?, ?, ?, ?, ?, ?)";
83

  
84
				PreparedStatement pst = db.getPreparedStatement(qy, true);
85
				pst.setInt(1, 0);
86
				pst.setInt(2, 1);
87
				pst.setString(3, param.get("nick"));
88
				pst.setString(4, param.get("name"));
89
				pst.setString(5, BCrypt.hashpw(param.get("password"), BCrypt.gensalt()));
90
				pst.setString(6, param.get("session"));
91
				pst.setString(7, param.get("email"));
92

  
93
				ResultSet rs = db.executeUpdate(pst);
94

  
95
				if(rs != null && rs.next()){
96
					this.id = rs.getInt(1);
97
				}
98
			}
99

  
100
		} catch (SQLException e) {
101
			logger.error("Can not register user: ", e);
102
			throw new DataAccessException(e);
103
		}
104
	}
105

  
106
	/**
107
	 * Return all information about user from database stored in map. Keys of map are: id, nick, name, psw, session,
108
	 * active, created, email.
109
	 *
110
	 * @return created map or empty map.
111
	 */
112
	public Map<String, String> getUser(){
113
		String qy = "SELECT * FROM user WHERE id = '" + this.id + "'";
114
		try {
115
			ResultSet rs = db.executeQuery(qy);
116

  
117
			if ( rs != null && rs.next() ) {
118
				Map<String, String> params = new HashMap<>(8);
119
				params.put("id", rs.getString("id"));
120
				params.put("nick", rs.getString("nick"));
121
				params.put("name", rs.getString("name"));
122
				params.put("psw", rs.getString("psw"));
123
				params.put("session", rs.getString("session"));
124
				params.put("active", rs.getString("active"));
125
				params.put("created", rs.getString("created"));
126
				params.put("email", rs.getString("email"));
127

  
128
				return params;
129

  
130
			} else {
131
				this.id = 0;
132
			}
133
		} catch (SQLException e) {
134
			logger.error("Can not get user: ", e);
135
			throw new DataAccessException(e);
136
		}
137

  
138
		return Collections.emptyMap();
139
	}
140

  
141
	/**
142
	 * Returns id of user. Value 0 indicates not existing user.
143
	 *
144
	 * @return int with user id or 0.
145
	 */
146
	public int getId(){
147
		return id;
148
	}
149

  
150
	/**
151
	 * Method sets session for current user and save session to database.
152
	 */
153
	public void setSession(String session){
154
		if(id > 0){
155
			String qy = "UPDATE user SET session= ? WHERE id='" + this.id + "'";
156

  
157
			try {
158

  
159
				PreparedStatement pst = db.getPreparedStatement(qy, false);
160
				pst.setString(1, session);
161
				db.executeStatement(pst);
162

  
163
			} catch (SQLException e) {
164
				logger.error("Can not get user session: ", e);
165
				throw new DataAccessException(e);
166
			}
167
		}
168
	}
169

  
170
	/**
171
	 * Method saves parameters into database. Method can change only email, nick and active parameters.
172
	 * @param param - parameters to save
173
	 */
174
	public void update(Map<String, String> param) {
175
		if ( this.id  != 0 ) {
176
			try {
177
				String qy = "UPDATE user SET  email = ?, nick = ?, active = ? WHERE id = ?";
178

  
179
				PreparedStatement pst = db.getPreparedStatement(qy, false);
180
				pst.setString(1, param.get("email"));
181
				pst.setString(2, param.get("nick"));
182
				pst.setString(3, param.get("active"));
183
				pst.setInt(4, this.id);
184

  
185
				db.executeStatement(pst);
186
			} catch (SQLException e) {
187
				logger.error("Can not update user: ", e);
188
				throw new DataAccessException(e);
189
			}
190
		}
191
	}
192

  
193
	/**
194
	 * Returns nick of user or empty string when no user is loaded.
195
	 */
196
	public String getNick(){
197
		if (this.id != 0) {
198
			String qy = "SELECT nick FROM user WHERE id = '" + this.id + "'";
199
			ResultSet rs = db.executeQuery(qy);
200

  
201
			try{
202
				if (rs != null && rs.next()) {
203
					return rs.getString("nick");
204
				}
205
			}  catch (SQLException e){
206
				logger.error("Can not get users nick name: ", e);
207
				throw new DataAccessException(e);
208
			}
209
		}
210

  
211
		return "";
212
	}
213

  
214
	/**
215
	 * Method checks if exists user with input nick.
216
	 *
217
	 * @return true - nick already exists, false - otherwise
218
	 */
219
	public boolean isNickExists(String testNick){
220
		return isExists("nick", testNick);
221
	}
222

  
223
	/**
224
	 * Method checks if exists user with input e-mail.
225
	 *
226
	 * @return true - e-mail already exists, false otherwise
227
	 */
228
	public boolean isEmailExists(String testEmail){
229
		return isExists("email", testEmail);
230
	}
231

  
232
	/**
233
	 * Method checks if exists user whose attribute given by name exists with given value
234
	 *
235
	 * @return true - minimal one user exists, false - otherwise
236
	 */
237
	private boolean isExists(String name, String value){
238
		String qy = "SELECT * FROM user WHERE LOWER(" + name + ") LIKE ? LIMIT 1";
239

  
240
		try {
241
			PreparedStatement pst = db.getPreparedStatement(qy, false);
242
			pst.setString(1, value.toLowerCase());
243
			ResultSet rs = db.executeQuery(pst);
244

  
245
			if ( rs != null && rs.next() && rs.getInt("id") > 0) {
246
				return true;
247
			}
248
		} catch (SQLException e) {
249
			logger.error("Can not check if user exits: ", e);
250
			throw new DataAccessException(e);
251
		}
252

  
253
		return false;
254
	}
255
}
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/Util.java
1
package cz.zcu.kiv.offscreen.user;
2

  
3
import java.util.regex.Matcher;
4
import java.util.regex.Pattern;
5

  
6
class Util {
7

  
8

  
9
	static String formatDate(String date){
10
		String pattern = "(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}).*";
11
		Pattern pat = Pattern.compile(pattern);
12
		Matcher matches = pat.matcher(date);
13
		String formatedDate = "";
14
		
15
		if(matches.find()){			
16
			formatedDate = matches.group(3) + "." + matches.group(2) + "." +  matches.group(1) + " " + matches.group(4) + ":" +  matches.group(5);			
17
		}
18
		
19
		return formatedDate;
20
	}
21
}
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/dao/DiagramDAO.java
1
package cz.zcu.kiv.offscreen.user.dao;
2

  
3
import cz.zcu.kiv.offscreen.user.DataAccessException;
4
import cz.zcu.kiv.offscreen.user.MyBatisUtil;
5
import cz.zcu.kiv.offscreen.user.mapper.IDiagramMapper;
6
import org.apache.ibatis.session.SqlSession;
7

  
8
import java.util.HashMap;
9
import java.util.List;
10
import java.util.Map;
11

  
12
public class DiagramDAO {
13

  
14
    public Map<String, Object> getDiagram(int userId){
15

  
16
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
17

  
18
            IDiagramMapper mapper = session.getMapper(IDiagramMapper.class);
19
            return mapper.getDiagram(userId);
20

  
21
        } catch (Exception e) {
22
            throw new DataAccessException(e);
23
        }
24
    }
25

  
26
    public List<Map<String, Object>> getDiagramsByUserId(int userId){
27
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
28
            IDiagramMapper mapper = session.getMapper(IDiagramMapper.class);
29

  
30
            return mapper.getDiagramsByUserId(userId);
31

  
32
        } catch (Exception e) {
33
            throw new DataAccessException(e);
34
        }
35
    }
36

  
37

  
38
    public List<Map<String, Object>> getPublicDiagrams(){
39
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
40
            IDiagramMapper mapper = session.getMapper(IDiagramMapper.class);
41

  
42
            return mapper.getPublicDiagrams();
43

  
44
        } catch (Exception e) {
45
            throw new DataAccessException(e);
46
        }
47
    }
48

  
49
    public void deleteDiagram(int diagramId){
50
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
51
            IDiagramMapper mapper = session.getMapper(IDiagramMapper.class);
52

  
53
            mapper.deleteDiagram(diagramId);
54
            session.commit();
55

  
56
        } catch (Exception e) {
57
            throw new DataAccessException(e);
58
        }
59
    }
60

  
61
    public int getDiagramUserId(int diagramId){
62
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
63
            IDiagramMapper mapper = session.getMapper(IDiagramMapper.class);
64

  
65
            return mapper.getDiagramUserId(diagramId);
66

  
67
        } catch (Exception e) {
68
            throw new DataAccessException(e);
69
        }
70
    }
71

  
72
    public int createDiagram(String name, String userId, String isPublic, String graphJson) {
73
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
74
            IDiagramMapper mapper = session.getMapper(IDiagramMapper.class);
75

  
76
            Map<String, Object> id = new HashMap<>();
77
            id.put("id", 0);
78

  
79
            mapper.createDiagram(id, name, userId, isPublic, graphJson);
80
            session.commit();
81

  
82
            return (int)id.get("id");
83

  
84
        } catch (Exception e) {
85
            throw new DataAccessException(e);
86
        }
87
    }
88

  
89
    public void updateDiagram(int diagramId, String name, String isPublic, String graphJson){
90
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
91
            IDiagramMapper mapper = session.getMapper(IDiagramMapper.class);
92

  
93
            mapper.updateDiagram(diagramId, name, isPublic, graphJson);
94
            session.commit();
95

  
96
        } catch (Exception e) {
97
            throw new DataAccessException(e);
98
        }
99
    }
100

  
101
}
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/dao/UserDAO.java
1
package cz.zcu.kiv.offscreen.user.dao;
2

  
3
import cz.zcu.kiv.offscreen.user.DataAccessException;
4
import cz.zcu.kiv.offscreen.user.MyBatisUtil;
5
import cz.zcu.kiv.offscreen.user.mapper.IUserMapper;
6
import org.apache.commons.lang3.StringUtils;
7
import org.apache.ibatis.session.SqlSession;
8
import org.springframework.security.crypto.bcrypt.BCrypt;
9

  
10
import java.util.Map;
11

  
12
public class UserDAO {
13

  
14
    public Map<String, Object> login(String nick, String psw){
15
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
16
            IUserMapper mapper = session.getMapper(IUserMapper.class);
17
            Map<String, Object> user = mapper.getUserByNick(nick);
18

  
19
            if(user != null &&
20
                    !user.isEmpty() &&
21
                    (Integer)user.get("id") > 0 &&
22
                    StringUtils.isNotBlank((String)user.get("psw")) &&
23
                    BCrypt.checkpw(psw, (String)user.get("psw"))) {
24
                return user;
25
            }
26

  
27
            return null;
28

  
29
        } catch (Exception e) {
30
            throw new DataAccessException(e);
31
        }
32
    }
33

  
34
    public void register(String nick, String name, String password, String session, String email){
35
        try (SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession()) {
36
            IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
37

  
38
            String hashPassword = BCrypt.hashpw(password, BCrypt.gensalt());
39
            mapper.createUser(nick, name, hashPassword, session, email);
40
            sqlSession.commit();
41

  
42
        } catch (Exception e) {
43
            throw new DataAccessException(e);
44
        }
45
    }
46

  
47
    public boolean isEmailExists(String email){
48
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
49
            IUserMapper mapper = session.getMapper(IUserMapper.class);
50
            Map<String, Object> user = mapper.getUserByEmail(email);
51

  
52
            return user != null && !user.isEmpty();
53

  
54
        } catch (Exception e) {
55
            throw new DataAccessException(e);
56
        }
57
    }
58

  
59
    public boolean isNickExists(String nick){
60
        try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
61
            IUserMapper mapper = session.getMapper(IUserMapper.class);
62
            Map<String, Object> user = mapper.getUserByNick(nick);
63

  
64
            return user != null && !user.isEmpty();
65

  
66
        } catch (Exception e) {
67
            throw new DataAccessException(e);
68
        }
69
    }
70
}
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/mapper/IDiagramMapper.java
1
package cz.zcu.kiv.offscreen.user.mapper;
2

  
3
import org.apache.ibatis.annotations.*;
4

  
5
import java.util.List;
6
import java.util.Map;
7

  
8
public interface IDiagramMapper {
9

  
10
    @Select("SELECT * FROM diagram WHERE id = #{id}")
11
    Map<String, Object> getDiagram(int id);
12

  
13
    @Select("SELECT id, name, created, last_update, user_id, public FROM diagram " +
14
            "WHERE user_id = #{userId} ORDER BY created DESC")
15
    List<Map<String, Object>> getDiagramsByUserId(int userId);
16

  
17
    @Select("SELECT id, name, created, last_update, user_id, public FROM diagram " +
18
            "WHERE public = 1 ORDER BY name ASC")
19
    List<Map<String, Object>> getPublicDiagrams();
20

  
21
    @Select("SELECT user_id FROM diagram WHERE id = #{id}")
22
    int getDiagramUserId(int id);
23

  
24
    @Delete("DELETE FROM diagram WHERE id = #{id}")
25
    void deleteDiagram(int id);
26

  
27
    @Insert("INSERT INTO diagram (name, created, last_update, user_id, public, graph_json) " +
28
            "VALUES (#{name}, NOW(), NOW(), #{userId}, #{isPublic}, #{graphJson}) ")
29
    @Options(useGeneratedKeys=true, keyColumn = "id", keyProperty="map.id")
30
    void createDiagram(
31
            @Param("map") Map<String, Object> map,
32
            @Param("name") String name,
33
            @Param("userId") String userId,
34
            @Param("isPublic") String isPublic,
35
            @Param("graphJson") String graphJson);
36

  
37
    @Update("UPDATE diagram SET name=#{name}, public=#{isPublic}, graph_json=#{graphJson}, last_update=NOW() " +
38
            "WHERE id=#{diagramId}")
39
    void updateDiagram(
40
            @Param("diagramId") int diagramId,
41
            @Param("name") String name,
42
            @Param("isPublic") String isPublic,
43
            @Param("graphJson") String graphJson);
44
}
sources/imiger-core/src/main/java/cz/zcu/kiv/offscreen/user/mapper/IUserMapper.java
1
package cz.zcu.kiv.offscreen.user.mapper;
2

  
3
import org.apache.ibatis.annotations.Insert;
4
import org.apache.ibatis.annotations.Param;
5
import org.apache.ibatis.annotations.Select;
6

  
7
import java.util.Map;
8

  
9
public interface IUserMapper {
10

  
11
    @Select("SELECT * FROM user WHERE nick LIKE #{nick} AND active = '1' LIMIT 1")
12
    Map<String, Object> getUserByNick(String nick);
13

  
14
    @Select("SELECT * FROM user WHERE email LIKE #{email} AND active = '1' LIMIT 1")
15
    Map<String, Object> getUserByEmail(String email);
16

  
17
    @Insert("INSERT INTO user (id, created, active, nick, name, psw, session, email) " +
18
            "VALUES ( 0, NOW(), 1, #{nick}, #{name}, #{password}, #{session}, #{email})")
19
    void createUser(
20
            @Param("nick") String nick,
21
            @Param("name") String name,
22
            @Param("password") String password,
23
            @Param("session") String session,
24
            @Param("email") String email);
25
}
sources/imiger-core/src/main/resources/mybatis-config.xml
1
<?xml version="1.0" encoding="UTF-8" ?>
2
<!DOCTYPE configuration
3
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
5

  
6
<configuration>
7
    <environments default="development">
8
        <environment id="development">
9
            <transactionManager type="JDBC"/>
10
            <dataSource type="POOLED">
11
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
12
                <property name="url" value="jdbc:mysql://localhost/visualization_tool?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
13
                <property name="username" value="admin"/>
14
                <property name="password" value="admin"/>
15
            </dataSource>
16
        </environment>
17
    </environments>
18
    <mappers>
19
        <mapper class="cz.zcu.kiv.offscreen.user.mapper.IUserMapper"/>
20
        <mapper class="cz.zcu.kiv.offscreen.user.mapper.IDiagramMapper"/>
21
    </mappers>
22
</configuration>

Také k dispozici: Unified diff