switched from pure sql to jpa and changed the type from string to enum

This commit is contained in:
frosch95
2013-09-27 20:30:35 +02:00
parent e06ed20165
commit 5e460fac7a
17 changed files with 208 additions and 376 deletions

View File

@@ -183,7 +183,7 @@ public class CacheDetailsController implements Initializable, SessionContextList
placedByTextfield.setText(currentCache.getPlacedBy());
ownerTextfield.setText(currentCache.getOwner().getName());
date.setValue(currentCache.getMainWayPoint().getTime().toLocalDate());
typeTextfield.setText(currentCache.getType());
typeTextfield.setText(currentCache.getType().toGroundspeakString());
containerTextfield.setText(currentCache.getContainer());
fillShortDescription(currentCache);
fillLongDescription(currentCache);

View File

@@ -26,6 +26,7 @@
package de.frosch95.geofrogger.fx.components;
import de.frosch95.geofrogger.model.Cache;
import de.frosch95.geofrogger.model.Type;
import javafx.scene.image.Image;
/**
@@ -41,39 +42,39 @@ public class GeocachingIcons {
String iconName = "/icons/iconmonstr-map-5-icon.png";
switch (cache.getType()) {
case "Multi-cache":
case MULTI_CACHE:
iconName = "/icons/iconmonstr-map-6-icon.png";
break;
case "Traditional Cache":
case TRADITIONAL_CACHE:
iconName = "/icons/iconmonstr-map-5-icon.png";
break;
case "Unknown Cache":
case UNKNOWN_CACHE:
iconName = "/icons/iconmonstr-help-3-icon.png";
break;
case "Earthcache":
case EARTH_CACHE:
iconName = "/icons/iconmonstr-globe-4-icon.png";
break;
case "Letterbox Hybrid":
case LETTERBOX:
iconName = "/icons/iconmonstr-email-4-icon.png";
break;
case "Event Cache":
case EVENT:
iconName = "/icons/iconmonstr-calendar-4-icon.png";
break;
case "Wherigo Cache":
case WHERIGO:
iconName = "/icons/iconmonstr-navigation-6-icon.png";
break;
case "Webcam Cache":
case WEBCAM_CACHE:
iconName = "/icons/iconmonstr-webcam-3-icon.png";
break;
case "Virtual Cache":
case VIRTUAL_CACHE:
iconName = "/icons/iconmonstr-network-2-icon.png";
break;

View File

@@ -1,9 +1,6 @@
/*
* Empty Stylesheet file.
*/
.mainFxmlClass {
.root{
-fx-font-size: 10pt;
-fx-font-family: "Fira Sans";
}
.menu-bar {
@@ -35,7 +32,7 @@
}
.cache-list-name {
-fx-font-size: 1.2em;
-fx-font-weight: bold;
}
.cache-list-icon {
@@ -49,7 +46,6 @@
.cache-list-action-icons {
-fx-padding: 4;
-fx-margin: 0 8;
-fx-text-fill: #ffffff;
}

View File

@@ -25,20 +25,27 @@
*/
package de.frosch95.geofrogger.model;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Andreas Billmann
*/
@Entity
public class Attribute {
private Integer id;
@Id
private Long id;
private boolean inc;
private String text;
public Integer getId() {
public Long getId() {
return id;
}
public void setId(Integer id) {
public void setId(Long id) {
this.id = id;
}

View File

@@ -25,20 +25,23 @@
*/
package de.frosch95.geofrogger.model;
import javax.persistence.*;
import java.util.List;
/**
* @author Andreas Billmann
*/
@Entity
public class Cache {
@Id
private Long id;
private boolean available;
private boolean archived;
private String name;
private String placedBy;
private User owner;
private String type;
private Type type;
private String container;
private List<Attribute> attributes;
private String difficulty;
@@ -54,6 +57,7 @@ public class Cache {
private List<TravelBug> travelBugs;
private Waypoint mainWayPoint;
@OneToOne(fetch=FetchType.LAZY)
public Waypoint getMainWayPoint() {
return mainWayPoint;
}
@@ -102,6 +106,7 @@ public class Cache {
this.placedBy = placedBy;
}
@OneToOne(fetch=FetchType.LAZY)
public User getOwner() {
return owner;
}
@@ -110,11 +115,12 @@ public class Cache {
this.owner = owner;
}
public String getType() {
@Enumerated(EnumType.STRING)
public Type getType() {
return type;
}
public void setType(String type) {
public void setType(Type type) {
this.type = type;
}
@@ -126,6 +132,7 @@ public class Cache {
this.container = container;
}
@ManyToMany(fetch=FetchType.LAZY)
public List<Attribute> getAttributes() {
return attributes;
}
@@ -206,6 +213,7 @@ public class Cache {
this.encodedHints = encodedHints;
}
@OneToMany(fetch=FetchType.LAZY)
public List<Log> getLogs() {
return logs;
}
@@ -214,6 +222,7 @@ public class Cache {
this.logs = logs;
}
@OneToMany(fetch=FetchType.LAZY)
public List<TravelBug> getTravelBugs() {
return travelBugs;
}

View File

@@ -25,13 +25,16 @@
*/
package de.frosch95.geofrogger.model;
import javax.persistence.*;
import java.time.LocalDateTime;
/**
* @author Andreas Billmann
*/
@Entity
public class Log {
@Id
private Long id;
private LocalDateTime date;
private String type;
@@ -63,6 +66,7 @@ public class Log {
this.type = type;
}
@OneToOne(cascade = CascadeType.PERSIST)
public User getFinder() {
return finder;
}

View File

@@ -0,0 +1,26 @@
package de.frosch95.geofrogger.model;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* This class represents the application settings, like current user, etc.
*
* @author abi
*/
@Entity
public class Settings {
@Id
private Long id;
private Long currentUserID = new Long(3906456);
public Long getCurrentUserID() {
return currentUserID;
}
public void setCurrentUserID(final Long currentUserID) {
this.currentUserID = currentUserID;
}
}

View File

@@ -25,11 +25,17 @@
*/
package de.frosch95.geofrogger.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Andreas Billmann
*/
@Entity
public class TravelBug {
@Id
private Long id;
private String ref;
private String name;

View File

@@ -0,0 +1,39 @@
package de.frosch95.geofrogger.model;
/**
* This enum represents the different cache types
*
* @author abi
*/
public enum Type {
TRADITIONAL_CACHE("Traditional Cache"),
MULTI_CACHE("Multi-cache"),
UNKNOWN_CACHE("Unknown Cache"),
EARTH_CACHE("Earthcache"),
LETTERBOX("Letterbox Hybrid"),
EVENT("Event Cache"),
WHERIGO("Wherigo Cache"),
WEBCAM_CACHE("Webcam Cache"),
VIRTUAL_CACHE("Virtual Cache");
private String groundspeakString;
private Type(String groundspeakString) {
this.groundspeakString = groundspeakString;
}
public String toGroundspeakString() {
return groundspeakString;
}
public static Type groundspeakStringToType(String groundspeakString) {
for (Type t: Type.values()) {
if (t.toGroundspeakString().equals(groundspeakString)) {
return t;
}
}
throw new IllegalArgumentException("unknown type:"+groundspeakString);
}
}

View File

@@ -25,11 +25,18 @@
*/
package de.frosch95.geofrogger.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Andreas Billmann
*/
@Entity
public class User {
@Id
private Long id;
private String name;

View File

@@ -25,14 +25,20 @@
*/
package de.frosch95.geofrogger.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.net.URL;
import java.time.LocalDateTime;
/**
* @author Andreas Billmann
*/
@Entity
public class Waypoint {
@Id
private Long id;
private double latitude;
private double longitude;

View File

@@ -8,93 +8,21 @@ package de.frosch95.geofrogger.service;
import de.frosch95.geofrogger.application.ProgressEvent;
import de.frosch95.geofrogger.application.ProgressListener;
import de.frosch95.geofrogger.application.ServiceManager;
import de.frosch95.geofrogger.model.Attribute;
import de.frosch95.geofrogger.model.Cache;
import de.frosch95.geofrogger.model.User;
import de.frosch95.geofrogger.model.Waypoint;
import de.frosch95.geofrogger.model.Log;
import de.frosch95.geofrogger.model.TravelBug;
import de.frosch95.geofrogger.sql.DatabaseService;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Andreas
*/
public class CacheServiceImpl implements CacheService {
private static final String SAVE_CACHE = "INSERT INTO geocache("
+ "id,"
+ "available,"
+ "archived,"
+ "name,"
+ "placedBy,"
+ "ownerId,"
+ "type,"
+ "container,"
+ "difficulty,"
+ "terrain,"
+ "country,"
+ "state,"
+ "shortDescription,"
+ "shortDescriptionHtml,"
+ "longDescription,"
+ "longDescriptionHtml,"
+ "encodedHints,"
+ "mainWaypointId"
+ ") values ("
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?"
+ ")";
private static final String SAVE_WAYPOINT = "INSERT INTO waypoint("
+ "id,"
+ "latitude,"
+ "longitude,"
+ "name,"
+ "time,"
+ "description,"
+ "url,"
+ "urlName,"
+ "symbol,"
+ "type"
+ ") values ("
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?,"
+ "?"
+ ")";
private static final String COUNT_ALL_CACHES = "SELECT count(*) FROM geocache";
private static final String LOAD_ALL_CACHES = "SELECT * FROM geocache ORDER BY ID";
private static final String LOAD_CACHE_BY_ID = "SELECT * FROM geocache WHERE ID = ?";
private static final String LOAD_ALL_WAYPOINTS = "SELECT * FROM waypoint ORDER BY ID";
private final DatabaseService dbService = ServiceManager.getInstance().getDatabaseService();
private final List<ProgressListener> listeners = new ArrayList<>();
@@ -108,218 +36,60 @@ public class CacheServiceImpl implements CacheService {
@Override
public void storeCaches(List<Cache> caches) {
Connection connection = null;
try {
connection = dbService.getConnection();
try (PreparedStatement cacheStatement = connection.prepareStatement(SAVE_CACHE)) {
try (PreparedStatement waypointStatement = connection.prepareStatement(SAVE_WAYPOINT)) {
int currentCacheNumber = 0;
int numberOfCaches = caches.size();
for (Cache cache : caches) {
EntityManager em = dbService.getEntityManager();
int currentCacheNumber = 0;
int numberOfCaches = caches.size();
for (Cache cache : caches) {
currentCacheNumber++;
fireEvent(new ProgressEvent("Database",
ProgressEvent.State.RUNNING,
"Save caches to Database " + currentCacheNumber + " / " + numberOfCaches,
(double) currentCacheNumber / (double) numberOfCaches));
fireEvent(new ProgressEvent("Database",
ProgressEvent.State.RUNNING,
"Save caches to Database " + currentCacheNumber + " / " + numberOfCaches,
(double) currentCacheNumber / (double) numberOfCaches));
if (!doesCacheExist(cache.getId())) {
saveCacheObject(cacheStatement, cache);
saveWaypointObject(waypointStatement, cache);
}
}
}
}
connection.commit();
} catch (SQLException ex) {
Logger.getLogger(CacheServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex1) {
Logger.getLogger(CacheServiceImpl.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
}
em.getTransaction().begin();
em.merge(cache.getOwner());
em.merge(cache.getMainWayPoint());
private boolean doesCacheExist(Long id) {
boolean exists = false;
try {
try (PreparedStatement cacheStatement = dbService.getConnection().prepareStatement(LOAD_CACHE_BY_ID)) {
cacheStatement.setLong(1, id);
try (ResultSet cacheResultSet = cacheStatement.executeQuery()) {
exists = cacheResultSet.next();
for (Log log: cache.getLogs()) {
em.merge(log);
em.merge(log.getFinder());
}
for (Attribute attribute: cache.getAttributes()) {
em.merge(attribute);
}
for (TravelBug bug: cache.getTravelBugs()) {
em.merge(bug);
}
em.merge(cache);
em.getTransaction().commit();
}
} catch (SQLException ex) {
Logger.getLogger(CacheServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return exists;
fireEvent(new ProgressEvent("Database",
ProgressEvent.State.FINISHED,
"Caches are saved to Database"));
}
@Override
public List<Cache> getAllCaches() {
EntityManager em = dbService.getEntityManager();
List<Cache> caches = new ArrayList<>();
Connection connection;
try {
connection = dbService.getConnection();
try (PreparedStatement cacheStatement = connection.prepareStatement(LOAD_ALL_CACHES)) {
caches = resultSetToCacheList(cacheStatement, connection);
}
connection.commit();
} catch (SQLException ex) {
Logger.getLogger(CacheServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return caches;
}
private void saveCacheObject(PreparedStatement cacheStatement, Cache cache) throws SQLException {
cacheStatement.setLong(1, cache.getId());
cacheStatement.setBoolean(2, cache.isAvailable());
cacheStatement.setBoolean(3, cache.isArchived());
cacheStatement.setString(4, cache.getName());
cacheStatement.setString(5, cache.getPlacedBy());
cacheStatement.setLong(6, cache.getOwner().getId()); // ownerid
cacheStatement.setString(7, cache.getType()); // type
cacheStatement.setString(8, cache.getContainer()); //container
cacheStatement.setString(9, cache.getDifficulty()); //difficulty
cacheStatement.setString(10, cache.getTerrain()); //terrain
cacheStatement.setString(11, cache.getCountry()); //country
cacheStatement.setString(12, cache.getState()); //state
cacheStatement.setString(13, cache.getShortDescription()); //shortDescription
cacheStatement.setBoolean(14, cache.isShortDescriptionHtml()); //shortDescriptionHtml
cacheStatement.setString(15, cache.getLongDescription()); //longDescription
cacheStatement.setBoolean(16, cache.isLongDescriptionHtml()); //longDescriptionHtml
cacheStatement.setString(17, cache.getEncodedHints()); //encodedHints
cacheStatement.setLong(18, cache.getId()); //mainWaypointId
cacheStatement.execute();
}
private void saveWaypointObject(PreparedStatement waypointStatement, Cache cache) throws SQLException {
waypointStatement.setLong(1, cache.getId());
waypointStatement.setDouble(2, cache.getMainWayPoint().getLatitude()); // latitude
waypointStatement.setDouble(3, cache.getMainWayPoint().getLongitude()); //longitude,"
waypointStatement.setString(4, cache.getMainWayPoint().getName()); //name,"
waypointStatement.setTimestamp(5, Timestamp.valueOf(cache.getMainWayPoint().getTime())); //time,"
waypointStatement.setString(6, cache.getMainWayPoint().getDescription()); //description,"
waypointStatement.setString(7, cache.getMainWayPoint().getUrl().toExternalForm()); //url,"
waypointStatement.setString(8, cache.getMainWayPoint().getUrlName()); //urlName,"
waypointStatement.setString(9, cache.getMainWayPoint().getSymbol()); //symbol,"
waypointStatement.setString(10, cache.getMainWayPoint().getType()); //type"
waypointStatement.execute();
}
private List<Cache> resultSetToCacheList(final PreparedStatement cacheStatement, Connection connection) throws SQLException {
final List<Cache> caches = new ArrayList<>();
int numberOfCaches = 0;
try (PreparedStatement countStatement = connection.prepareStatement(COUNT_ALL_CACHES)) {
try (ResultSet countResultSet = countStatement.executeQuery()) {
if (countResultSet.next()) {
numberOfCaches = countResultSet.getInt(1);
}
}
List<Cache> result = em.createQuery("select c from Cache c").getResultList();
if (result != null) {
caches = result;
}
try (ResultSet cacheResultSet = cacheStatement.executeQuery()) {
int currentCacheNumber = 0;
while (cacheResultSet.next()) {
currentCacheNumber++;
fireEvent(new ProgressEvent("Database",
ProgressEvent.State.RUNNING,
"Load caches from Database " + currentCacheNumber + " / " + numberOfCaches,
(double) currentCacheNumber / (double) numberOfCaches));
createCacheObject(cacheResultSet, caches);
}
}
final List<Waypoint> waypoints = new ArrayList<>();
try (PreparedStatement waypointStatement = connection.prepareStatement(LOAD_ALL_WAYPOINTS)) {
try (ResultSet waypointResultSet = waypointStatement.executeQuery()) {
int currentWaypointNumber = 0;
while (waypointResultSet.next()) {
currentWaypointNumber++;
fireEvent(new ProgressEvent("Database",
ProgressEvent.State.RUNNING,
"Load waypoints from Database " + currentWaypointNumber + " / " + numberOfCaches,
(double) currentWaypointNumber / (double) numberOfCaches));
createWaypointObject(waypointResultSet, waypoints);
}
}
}
int cacheSize = caches.size();
int waypointSize = waypoints.size();
assert cacheSize == waypointSize : "size of waypoints and size of caches have to be the same!!";
for (int i = 0; i < cacheSize; i++) {
final Cache cache = caches.get(i);
final Waypoint waypoint = waypoints.get(i);
assert cache.getId().equals(waypoint.getId());
fireEvent(new ProgressEvent("Database",
ProgressEvent.State.RUNNING,
"Add waypoints to caches " + i + " / " + cacheSize,
(double) i / (double) cacheSize));
cache.setMainWayPoint(waypoint);
}
return caches;
}
private void fireEvent(ProgressEvent event) {
listeners.stream().forEach((l) -> {
l.progress(event);
});
listeners.stream().forEach((l) -> l.progress(event));
}
private void createCacheObject(final ResultSet cacheResultSet, final List<Cache> caches) throws SQLException {
Cache cache = new Cache();
cache.setId(cacheResultSet.getLong("id"));
cache.setAvailable(cacheResultSet.getBoolean("available"));
cache.setAvailable(cacheResultSet.getBoolean("archived"));
cache.setName(cacheResultSet.getString("name"));
cache.setPlacedBy(cacheResultSet.getString("placedBy"));
cache.setType(cacheResultSet.getString("type"));
cache.setContainer(cacheResultSet.getString("container"));
cache.setDifficulty(cacheResultSet.getString("difficulty"));
cache.setTerrain(cacheResultSet.getString("terrain"));
cache.setCountry(cacheResultSet.getString("country"));
cache.setState(cacheResultSet.getString("state"));
cache.setShortDescription(cacheResultSet.getString("shortDescription"));
cache.setShortDescriptionHtml(cacheResultSet.getBoolean("shortDescriptionHtml"));
cache.setLongDescription(cacheResultSet.getString("longDescription"));
cache.setLongDescriptionHtml(cacheResultSet.getBoolean("longDescriptionHtml"));
cache.setEncodedHints(cacheResultSet.getString("encodedHints"));
User user = new User();
user.setName("aus der DB");
user.setId(cacheResultSet.getLong("ownerId"));
cache.setOwner(user);
caches.add(cache);
}
private void createWaypointObject(final ResultSet waypointResultSet, final List<Waypoint> waypoints) throws SQLException {
Waypoint waypoint = new Waypoint();
//cache.setMainWayPoint(waypoint);
waypoint.setId(waypointResultSet.getLong("id"));
waypoint.setLatitude(waypointResultSet.getDouble("latitude"));
waypoint.setLongitude(waypointResultSet.getDouble("longitude"));
waypoint.setName(waypointResultSet.getString("name"));
waypoint.setTime(waypointResultSet.getTimestamp("time").toLocalDateTime());
waypoint.setDescription(waypointResultSet.getString("description"));
try {
waypoint.setUrl(new URL(waypointResultSet.getString("url")));
} catch (MalformedURLException ex) {
Logger.getLogger(CacheServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
}
waypoint.setUrlName(waypointResultSet.getString("urlName"));
waypoint.setSymbol(waypointResultSet.getString("symbol"));
waypoint.setType(waypointResultSet.getString("type"));
waypoints.add(waypoint);
}
}

View File

@@ -25,12 +25,11 @@
*/
package de.frosch95.geofrogger.sql;
import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;
/**
* @author Andreas
*/
public interface DatabaseService {
Connection getConnection() throws SQLException;
EntityManager getEntityManager();
}

View File

@@ -25,94 +25,30 @@
*/
package de.frosch95.geofrogger.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
* @author Andreas
*/
public class DatabaseServiceImpl implements DatabaseService {
private static final String CREATE_GEOCACHE_TABLE =
"CREATE TABLE geocache ("
+ "id BIGINT,"
+ "available BOOLEAN,"
+ "archived BOOLEAN,"
+ "name VARCHAR(255),"
+ "placedBy VARCHAR(255),"
+ "ownerId BIGINT,"
+ "type VARCHAR(255),"
+ "container VARCHAR(255),"
+ "difficulty VARCHAR(10),"
+ "terrain VARCHAR(10),"
+ "country VARCHAR(255),"
+ "state VARCHAR(255),"
+ "shortDescription CLOB,"
+ "shortDescriptionHtml BOOLEAN,"
+ "longDescription CLOB,"
+ "longDescriptionHtml BOOLEAN,"
+ "encodedHints CLOB,"
+ "mainWaypointId BIGINT"
+ ");";
private static final String WAYPOINT_TABLE =
"CREATE TABLE waypoint ("
+ "id BIGINT,"
+ "latitude DECIMAL(9,6),"
+ "longitude DECIMAL(9,6),"
+ "name VARCHAR(255),"
+ "time TIMESTAMP,"
+ "description CLOB,"
+ "url VARCHAR(255),"
+ "urlName VARCHAR(255),"
+ "symbol VARCHAR(255),"
+ "type VARCHAR(255)"
+ ");";
private Connection con;
private static final String PERSISTENCE_UNIT_NAME = "geocaches";
private EntityManagerFactory factory;
private EntityManager em;
public DatabaseServiceImpl() {
try {
con = DriverManager.getConnection("jdbc:h2:./geofroggerfxdb;IFEXISTS=TRUE", "sa", "sa");
con.setAutoCommit(false);
} catch (SQLException ex) {
setupDatabase();
}
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = factory.createEntityManager();
}
@Override
public Connection getConnection() throws SQLException {
if (con == null) {
throw new SQLException("no connection available");
}
return con;
public EntityManager getEntityManager() {
assert (em != null) : "no entity manager available";
return em;
}
private void setupDatabase() {
Statement statement = null;
try {
Class.forName("org.h2.Driver");
con = DriverManager.getConnection("jdbc:h2:./geofroggerfxdb", "sa", "sa");
con.setAutoCommit(false);
statement = con.createStatement();
statement.execute(CREATE_GEOCACHE_TABLE);
statement.execute(WAYPOINT_TABLE);
con.commit();
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(DatabaseServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (statement != null) try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(DatabaseServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}