UserUtil.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. package cz.hsrs.db.util;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import cz.hsrs.db.model.NoItemFoundException;
  8. import cz.hsrs.db.model.Unit;
  9. import cz.hsrs.db.model.UnitPosition;
  10. import cz.hsrs.db.model.composite.LastPosition;
  11. import cz.hsrs.db.pool.SQLExecutor;
  12. import net.sf.json.JSONArray;
  13. import net.sf.json.JSONObject;
  14. /**
  15. * @author jezekjan
  16. */
  17. public class UserUtil extends GroupUtil {
  18. private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
  19. public UserUtil() {}
  20. public String getUserLanguage(String user_name) throws SQLException, NoItemFoundException {
  21. String select = "SELECT lang FROM system_users WHERE user_name = '"+user_name+"'";
  22. ResultSet res = stmt.executeQuery(select);
  23. if (res.next()) {
  24. return res.getString(1);
  25. } else
  26. throw new NoItemFoundException("getUserLanguage " + user_name + " not found.");
  27. }
  28. public int getUserId(String userName) throws NoItemFoundException, SQLException{
  29. String query = "SELECT user_id FROM system_users WHERE user_name = '"+userName+"';";
  30. ResultSet res = SQLExecutor.getInstance().executeQuery(query);
  31. if(res.next()){
  32. return res.getInt(1);
  33. } else{
  34. throw new NoItemFoundException("User with given " + userName + " was not found.");
  35. }
  36. }
  37. public int setUserLanguage(String user_name, String newLang) throws SQLException{
  38. String query = "UPDATE system_users SET lang = '"+newLang+"' WHERE user_name = '"+user_name+"';";
  39. return SQLExecutor.executeUpdate(query);
  40. }
  41. public boolean getAudio(String user_name) throws SQLException, NoItemFoundException {
  42. String select = "SELECT audio FROM system_users WHERE user_name = '"+user_name+"'";
  43. ResultSet res = stmt.executeQuery(select);
  44. if (res.next()) {
  45. return res.getBoolean(1);
  46. } else
  47. throw new NoItemFoundException("getAudio " + user_name + " not found.");
  48. }
  49. @SuppressWarnings("unchecked")
  50. public List<UnitPosition> getLastPositionsByUserName(String user_name) throws SQLException {
  51. return (List<UnitPosition>) generateObjectList(new UnitPosition(), getLastPositionsByUserNameRes(user_name));
  52. }
  53. @Deprecated
  54. public String getRole(String user_name) throws SQLException, NoItemFoundException{
  55. String query = "SELECT user_role FROM rights, system_users WHERE " +
  56. "system_users.user_name = '"+user_name + "' AND "+
  57. "system_users.rights_id = rights.rights_id";
  58. ResultSet res = stmt.executeQuery(query);
  59. if (res.next()) {
  60. return res.getString(1);
  61. } else {
  62. throw new NoItemFoundException("getUserPassword " + user_name + " not found.");
  63. }
  64. }
  65. /**
  66. * Methods provides rightID of the given user
  67. * @param userName is the unique user name
  68. * @return integer represents rightID
  69. * @throws SQLException
  70. * @throws NoItemFoundException
  71. */
  72. public int getRightsId(String userName) throws SQLException, NoItemFoundException {
  73. String query = "SELECT rights_id FROM system_users WHERE user_name='"+userName+"';";
  74. ResultSet res = SQLExecutor.getInstance().executeQuery(query);
  75. if(res.next()) {
  76. return res.getInt(1);
  77. } else {
  78. throw new NoItemFoundException("Rights for " + userName + " not found!");
  79. }
  80. }
  81. /**
  82. * Method select groupId of given user
  83. * @return groupId as int or null if there is not any user with given userName
  84. */
  85. public static Integer getUserGroupId(String userName) throws SQLException{
  86. String query = "SELECT group_id FROM system_users WHERE user_name ='"+userName+"';";
  87. ResultSet res = SQLExecutor.getInstance().executeQuery(query);
  88. return res.next() ? res.getInt(1) : null;
  89. }
  90. @SuppressWarnings("unchecked")
  91. public List<LastPosition> getLastPositionWithStatus(String user_name) throws SQLException {
  92. List<LastPosition> lastPositions = new ArrayList<>();
  93. List<UnitPosition> positions = (List<UnitPosition>) generateObjectList(
  94. new UnitPosition(), getLastPositionsByUserNameRes(user_name));
  95. for (UnitPosition pos : positions) {
  96. lastPositions.add((new UnitUtil()).getLastPositionWithStatus(pos));
  97. }
  98. return lastPositions;
  99. }
  100. /**
  101. * Methods selects last positions of units for given user
  102. * @param user_name - name of user
  103. * @return ResultSet containing lastUnitPositions
  104. * @throws SQLException
  105. */
  106. public ResultSet getLastPositionsByUserNameRes(String user_name) throws SQLException {
  107. /**
  108. * SELECT last_units_positions.gid, st_astext(the_geom), last_units_positions.unit_id, last_units_positions.time_stamp
  109. * FROM last_units_positions, units_to_groups, system_users
  110. * WHERE system_users.user_name = 'pepa'
  111. * AND system_users.group_id=units_to_groups.group_id
  112. * AND units_to_groups.unit_id =last_units_positions.unit_id ;
  113. */
  114. String last_pos_table = SQLExecutor.getUnitsLastPositions_table();
  115. /*
  116. String queryObservations = "SELECT gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
  117. + last_pos_table + ".unit_id, time_stamp, units_to_groups.group_id "
  118. + "FROM "
  119. + last_pos_table
  120. + ", "
  121. + "units_to_groups "
  122. + " WHERE ("
  123. + this.getWhereStatemant(user_name, "units_to_groups.group_id")
  124. + ") AND units_to_groups.unit_id = "
  125. + last_pos_table
  126. + ".unit_id; ";
  127. */
  128. String queryObservations = "SELECT units_to_groups.group_id, units_to_groups.unit_id,"
  129. + " lpt.gid, lpt.time_stamp, st_x(lpt.the_geom), st_y(lpt.the_geom), st_srid(lpt.the_geom), lpt.speed"
  130. + " FROM units_to_groups"
  131. + " LEFT JOIN "+last_pos_table+" lpt ON units_to_groups.unit_id = lpt.unit_id"
  132. + " WHERE ("+ this.getWhereStatemant(user_name, "units_to_groups.group_id") + ");";
  133. return stmt.executeQuery(queryObservations);
  134. }
  135. /**
  136. * Methods selects last positions of given unit for given user
  137. * @param user_name - name of user
  138. * @param unit_id - ID of unit
  139. * @return ResultSet containing lastUnitPosition
  140. * @throws SQLException
  141. */
  142. public ResultSet getLastPositionsByUserNameRes(String user_name, Long unit_id) throws SQLException {
  143. if (unit_id == null) {
  144. return getLastPositionsByUserNameRes(user_name);
  145. } else {
  146. String last_pos_table = SQLExecutor.getUnitsLastPositions_table();
  147. String queryObservations = "SELECT gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
  148. + last_pos_table
  149. + ".unit_id, time_stamp, units_to_groups.group_id "
  150. + "FROM "
  151. + last_pos_table
  152. + ", "
  153. + "units_to_groups "
  154. + " WHERE ("
  155. + this.getWhereStatemant(user_name,
  156. "units_to_groups.group_id")
  157. + ") AND units_to_groups.unit_id = "
  158. + last_pos_table
  159. + ".unit_id AND "
  160. + last_pos_table
  161. + ".unit_id = "
  162. + unit_id;
  163. return stmt.executeQuery(queryObservations);
  164. }
  165. }
  166. /**
  167. * Method gets UnitsPositions by user name
  168. * @param user_name - name of user
  169. * @param limit - limit of positions
  170. * @return
  171. * @throws SQLException
  172. */
  173. public ResultSet getPositionsByUserName(String user_name, Integer limit) throws SQLException {
  174. String sqlLimit = "";
  175. if (limit != null) {
  176. if (limit == 1) {
  177. return getLastPositionsByUserNameRes(user_name);
  178. }
  179. sqlLimit = "LIMIT " + limit;
  180. }
  181. String pos_table = SQLExecutor.getUnitsPositions_table();
  182. String queryObservations = "select gid, st_x(the_geom), st_y(the_geom), st_srid(the_geom), speed, "
  183. + pos_table
  184. + ".unit_id, time_stamp, units_to_groups.group_id " + "from "
  185. + pos_table + ", units_to_groups " + "WHERE ("
  186. + this.getWhereStatemant(user_name, "units_to_groups.group_id")
  187. + ") AND units_to_groups.unit_id = " + pos_table + ".unit_id "
  188. + " ORDER BY time_stamp DESC " + sqlLimit + " ;";
  189. return stmt.executeQuery(queryObservations);
  190. }
  191. public ResultSet getTracksByUserName(String user_name, int limit) throws SQLException {
  192. /**
  193. * select gid, st_astext(the_geom) from units_tracks, units_to_groups,
  194. * system_users WHERE system_users.user_name = 'pepa' AND
  195. * system_users.group_id= units_to_groups.group_id AND
  196. * units_to_groups.unit_id = units_tracks.unit_id ;
  197. */
  198. String tracks_table = SQLExecutor.getUnitsTracks_table();
  199. String queryObservations = "select gid, st_astext(the_geom), "
  200. + tracks_table
  201. + ".unit_id, track_start, track_end, units_to_groups.group_id "
  202. + "from " + tracks_table + "," + " units_to_groups"
  203. + " WHERE ("
  204. + this.getWhereStatemant(user_name, "units_to_groups.group_id")
  205. + ") AND units_to_groups.unit_id = " + tracks_table
  206. + ".unit_id order by track_end desc limit " + limit + "; ";
  207. return stmt.executeQuery(queryObservations);
  208. }
  209. public String getUserPassword(String user_name) throws SQLException, NoItemFoundException {
  210. String queryObservations = "select user_password from system_users WHERE user_name='" + user_name + "';";
  211. ResultSet res = stmt.executeQuery(queryObservations);
  212. if (res.next()) {
  213. return res.getString(1);
  214. } else
  215. throw new NoItemFoundException("getUserPassword " + user_name + " not found.");
  216. }
  217. public int insertUser(String user_name, String pass) throws SQLException {
  218. String insert = "insert into system_users(user_name, user_password) Values('" + user_name + "','" + pass + "');";
  219. return SQLExecutor.executeUpdate(insert);
  220. }
  221. /**
  222. *
  223. * @param user_name
  224. * @param pass
  225. * @param realName
  226. * @param groupId
  227. * @param rightsId
  228. * @return
  229. * @throws SQLException
  230. */
  231. public static int insertUser(String user_name, String pass, String realName, int groupId, int rightsId) throws SQLException {
  232. String insert = "INSERT INTO system_users(user_name, user_password, user_real_name, group_id, rights_id) "
  233. + "VALUES('" + user_name + "','" + pass + "','"+realName+"',"+groupId+","+rightsId+");";
  234. return SQLExecutor.executeUpdate(insert);
  235. }
  236. public int deleteUser(String user_name) throws SQLException {
  237. String del = "DELETE FROM system_users WHERE user_name='" + user_name + "';";
  238. return SQLExecutor.executeUpdate(del);
  239. }
  240. public int setUserSession(String user_name, String session_id, String IP) throws SQLException {
  241. /* try to delete session if exists */
  242. delUserSession(session_id);
  243. String getUsID = "SELECT user_id FROM system_users WHERE user_name = '" + user_name + "'";
  244. ResultSet res = stmt.executeQuery(getUsID);
  245. res.next();
  246. int user_id = res.getInt(1);
  247. String insert = "INSERT INTO sessions(session_id, system_user_id, ip) VALUES ("
  248. + "'" + session_id + "'," + user_id + ",'" + IP + "')";
  249. return SQLExecutor.executeUpdate(insert);
  250. }
  251. public int delUserSession(String session_id) throws SQLException {
  252. String insert = "DELETE FROM sessions WHERE session_id ='" + session_id + "'";
  253. return SQLExecutor.executeUpdate(insert);
  254. }
  255. @SuppressWarnings("unchecked")
  256. public List<Unit> getUnitsByUser(String user_name) throws SQLException{
  257. String query = "SELECT u.unit_id, u.holder_id, u.description " +
  258. "FROM units u, units_to_groups utg, system_users su " +
  259. "WHERE su.user_name = '"+user_name+"' " +
  260. "AND su.group_id = utg.group_id " +
  261. "AND utg.unit_id = u.unit_id;";
  262. ResultSet res = stmt.executeQuery(query);
  263. return (List<Unit>)generateObjectList(new Unit(), res);
  264. }
  265. public SimpleDateFormat getDateFormater() {
  266. return FORMATTER;
  267. }
  268. /**
  269. * Method returns positions of units in all groups for defined user collected in day defined by timeStamp parameter
  270. * @param user_name is String username of logged user
  271. * @param timeStamp is day for which positions should be found
  272. * @return ResultSet object with positions during one defined day
  273. * @throws SQLException
  274. */
  275. public ResultSet getPositionsByUserNameInDay2(String user_name, String timeStamp) throws SQLException {
  276. if(timeStamp !=null){
  277. String pos_table = SQLExecutor.getUnitsPositions_table();
  278. String query = "SELECT gid, "+pos_table+".unit_id, units_to_groups.group_id, "
  279. + "time_stamp, speed, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
  280. + "FROM "+pos_table+", units_to_groups "
  281. + "WHERE ("+this.getWhereStatemant(user_name, "units_to_groups.group_id")+") "
  282. + "AND units_to_groups.unit_id = "+pos_table+".unit_id "
  283. + "AND time_stamp > '"+timeStamp+"' AND time_stamp < timestamp '"+timeStamp+"' + INTERVAL '1 day' "
  284. + "ORDER BY time_stamp DESC;";
  285. return stmt.executeQuery(query);
  286. } else{
  287. throw new SQLException("Parameter timestamp was not defined!");
  288. }
  289. }
  290. /**
  291. * Method returns positions of units in all groups for defined user collected from defined timestamp parameter
  292. * @param user_name is String username of logged user
  293. * @param fromTime is timestamp of the beginning
  294. * @param unitId is identifier of unit
  295. * @param ordering is order direction for results, can be ASC or DESC only
  296. * @return ResultSet object with positions from defined timestamp, number is limited by range of 1 day!!!
  297. * @throws SQLException
  298. */
  299. public ResultSet getPositionsByUserNameInDay(String user_name, String fromTime, long unitId, String ordering) throws SQLException {
  300. if(fromTime != null){
  301. String pos_table = SQLExecutor.getUnitsPositions_table();
  302. String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
  303. + "FROM "+pos_table+" "
  304. + "WHERE "+pos_table+".unit_id = " + unitId + " "
  305. + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+fromTime+"'::timestamp + '1 day'::interval "
  306. + "ORDER BY time_stamp "+ordering+";";
  307. return stmt.executeQuery(query);
  308. } else{
  309. throw new SQLException("Parameter fromTime was not defined!");
  310. }
  311. }
  312. /**
  313. * Method returns positions of units in all groups for defined user collected to defined timestamp parameter
  314. * @param user_name is String username of logged user
  315. * @param toTime is timestamp of the end of range
  316. * @param unitId is identifier of unit
  317. * @param ordering is order direction for results, can be ASC or DESC only
  318. * @return ResultSet object with positions to defined timestamp, number is limited by range of 1 day ago!!!
  319. * @throws SQLException
  320. */
  321. public ResultSet getPositionsByUserNameDayBefore(String user_name, String toTime, long unitId, String ordering) throws SQLException {
  322. if(toTime !=null){
  323. String pos_table = SQLExecutor.getUnitsPositions_table();
  324. String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
  325. + "FROM "+pos_table+" "
  326. + "WHERE "+pos_table+".unit_id = " + unitId + " "
  327. + "AND time_stamp >= '"+toTime+"'::timestamp - '1 day'::interval AND time_stamp < '"+toTime+"' "
  328. + "ORDER BY time_stamp "+ordering+";";
  329. return stmt.executeQuery(query);
  330. } else{
  331. throw new SQLException("Parameter toTime was not defined!");
  332. }
  333. }
  334. /**
  335. * Method returns positions of units in all groups for defined user collected during defined timeStamp parameters
  336. * @param user_name is String username of logged user
  337. * @param fromTime is timestamp of the beginning
  338. * @param toTime is timestamp of the end of range
  339. * @param unitId is identifier of unit
  340. * @param ordering is order direction for results, can be ASC or DESC only
  341. * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows!!!
  342. * @throws SQLException
  343. */
  344. public ResultSet getPositionsByUserNameDuringRange(String user_name, String fromTime, String toTime, long unitId, String ordering) throws SQLException {
  345. if(fromTime !=null && toTime !=null){
  346. String pos_table = SQLExecutor.getUnitsPositions_table();
  347. String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
  348. + "FROM "+pos_table+" "
  349. + "WHERE "+pos_table+".unit_id = " + unitId + " "
  350. + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+toTime+"' "
  351. + "ORDER BY time_stamp "+ordering+" LIMIT 50000;";
  352. return stmt.executeQuery(query);
  353. } else{
  354. throw new SQLException("Parameters fromTime and toTime were not defined!");
  355. }
  356. }
  357. /**
  358. * Method returns positions of given unit for defined user collected during defined timestamp parameter,
  359. * modified for case of identical fromTime and toTime value
  360. * @param user_name is String username of logged user
  361. * @param fromTime is timestamp of the beginning of range
  362. * @param toTime is timestamp of the end of range
  363. * @param unitId is identifier of unit
  364. * @param ordering is order direction for results, can be ASC or DESC only
  365. * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows!!!
  366. * @throws SQLException
  367. */
  368. public ResultSet getPositionsByUserNameDuringDay(String user_name, String fromTime, String toTime, long unitId, String ordering) throws SQLException {
  369. if(fromTime !=null && toTime !=null){
  370. if(fromTime.equalsIgnoreCase(toTime)){
  371. String pos_table = SQLExecutor.getUnitsPositions_table();
  372. String query = "SELECT time_stamp, st_x(the_geom), st_y(the_geom), st_srid(the_geom) "
  373. + "FROM "+pos_table+" "
  374. + "WHERE "+pos_table+".unit_id = " + unitId + " "
  375. + "AND time_stamp >= '"+fromTime+"' AND time_stamp < '"+toTime+"'::timestamp + '1 day'::interval "
  376. + "ORDER BY time_stamp "+ordering+" LIMIT 50000;";
  377. return stmt.executeQuery(query);
  378. } else{
  379. throw new SQLException("Parameters was not correctly defined!");
  380. }
  381. } else{
  382. throw new SQLException("Parameter toTime was not defined!");
  383. }
  384. }
  385. /**
  386. * Method returns positions of units in all groups for defined user collected during defined timeStamp parameters
  387. * @param user_name user_name is String username of logged user
  388. * @param fromTime is timestamp of the beginning
  389. * @param toTime is timestamp of the end of range
  390. * @param unitId is identifier of unit
  391. * @param ordering is order direction for results, can be ASC or DESC only
  392. * @return ResultSet object with positions between defined timestamps, number is limited by 50 000 rows or to 1 day of collecting!!!
  393. * @throws SQLException
  394. */
  395. public ResultSet getPositionsTimeRangeByUserName(String user_name, String fromTime, String toTime, Long unitId, String ordering) throws SQLException{
  396. ResultSet res;
  397. if(fromTime != null && toTime == null && unitId != null){
  398. if(!fromTime.isEmpty()){
  399. res = getPositionsByUserNameInDay(user_name, fromTime, unitId, ordering);
  400. } else{
  401. throw new SQLException("Wrong content of parameter from!");
  402. }
  403. } else if(fromTime == null && toTime != null && unitId != null){
  404. if(!toTime.isEmpty()){
  405. res = getPositionsByUserNameDayBefore(user_name, toTime, unitId, ordering);
  406. } else{
  407. throw new SQLException("Wrong content of parameter to!");
  408. }
  409. } else if(fromTime != null && toTime != null && unitId != null){
  410. if(!fromTime.isEmpty() && !toTime.isEmpty()){
  411. if(fromTime.equalsIgnoreCase(toTime)){
  412. res = getPositionsByUserNameDuringDay(user_name, fromTime, toTime, unitId, ordering);
  413. } else{
  414. res = getPositionsByUserNameDuringRange(user_name, fromTime, toTime, unitId, ordering);
  415. }
  416. } else{
  417. throw new SQLException("Wrong content of parameters from and to!");
  418. }
  419. } else{
  420. throw new SQLException("Wrong combination of parameters from and to!");
  421. }
  422. return res;
  423. }
  424. /**
  425. * Function provides list of Units in the group of given user in GeoJSON FeatureCollection
  426. * @param userName - name of user to select the unit group
  427. * @return GeoJSON file as String
  428. * @throws SQLException
  429. */
  430. public static String getUnitsGeoJson(String userName) throws SQLException {
  431. String query = "SELECT unit_id, description, type_name, altitude, time_stamp, st_asgeojson(the_geom) AS geom"
  432. + " FROM public.unit_groups_description_position"
  433. + " WHERE id = (SELECT group_id FROM system_users WHERE user_name = '"+userName+"')"
  434. + " AND the_geom IS NOT NULL AND (st_x(the_geom) != 0 OR st_y(the_geom) != 0)"
  435. + " ORDER BY unit_id;";
  436. ResultSet res = SQLExecutor.getInstance().executeQuery(query);
  437. JSONObject geojson = new JSONObject();
  438. if(res != null) {
  439. geojson.element("type", "FeatureCollection");
  440. JSONArray features = new JSONArray();
  441. while (res.next()) {
  442. JSONObject feature = new JSONObject();
  443. feature.element("type", "Feature");
  444. JSONObject properties = new JSONObject();
  445. properties.element("unit_id", res.getString("unit_id"));
  446. properties.element("description", res.getString("description"));
  447. properties.element("type_name", res.getString("type_name"));
  448. properties.element("altitude", res.getDouble("altitude"));
  449. properties.element("time_stamp", res.getString("time_stamp")+"00");
  450. feature.element("properties", properties);
  451. String geometry = res.getString("geom");
  452. feature.element("geometry", geometry);
  453. features.add(feature);
  454. }
  455. geojson.element("features", features);
  456. }
  457. return geojson.toString();
  458. }
  459. }