diff --git a/Wetterstation/wetterstation.ino b/Wetterstation/wetterstation.ino new file mode 100644 index 00000000..05a9067a --- /dev/null +++ b/Wetterstation/wetterstation.ino @@ -0,0 +1,343 @@ +#include +#include +#include +#include +#include +#include + +// Set these to your desired credentials. +const char *ssid = "MOWESTA Wetterstation"; +const char *password = "mowesta19"; +const char setup_off = '0'; +const char setup_on = '1'; +const String ssidStart = "/SSID"; +const String pwStart = "/PW"; + +String user_ssid = ""; +String user_pw = ""; + +/* Const to calculate height*/ +#define SEALEVELPRESSURE_HPA (1013.25) +/* Time in which the esp is put to sleep between each measurement */ +#define uS_TO_S_FACTOR 1000000 +#define SLEEP_TIME 10 + +/* Sensor Objects */ +Adafruit_BME280 bme1; // I2C +Adafruit_BME280 bme2; // I2C +WiFiServer server(80); + + +void setup() { + pinMode(LED_BUILTIN, OUTPUT); + + /* Set baudrate and wait for it to be initialised */ + Serial.begin(115200); + while(!Serial); + + /* "Allocate" compleate EEPROM storage | 512 Byte */ + EEPROM.begin(512); + + /* Check if weatherstation is already configured */ + if(setup_is_on()) { + Serial.println(); + Serial.println("Configuring access point..."); + + WiFi.softAP(ssid, password); + IPAddress myIP = WiFi.softAPIP(); + Serial.print("AP IP address: "); + Serial.println(myIP); + server.begin(); + + Serial.println("Server started"); + } else { // no further configuration needed + // read WiFi SSID and PW from memory + user_ssid = read_String(1); + user_pw = read_String(user_ssid.length()+2); + Serial.print("Connecting to Network "); + Serial.print(user_ssid); + connect_to_wifi(user_ssid, user_pw); + + /* Start Sensors and check if sensor is connected */ + checkStatus(); + + /* Search for connected I2C devices and print their address */ + printAddress(); + + /* Print reasen why device was restarted */ + print_wakeup_reason(); + + /* Setup sleeptimer */ + setupSleepTimer(); + + } + + +} + +void loop() { + if(setup_is_on()) { + WiFiClient client = server.available(); // listen for incoming clients + if (client) { // if you get a client + handle_client_connection(client); + } + } else { + delay(1000); + Serial.print("Try to connect"); + if(WiFi.status() != WL_CONNECTED){ + connect_to_wifi(user_ssid, user_pw); + } + Serial.print("Connected"); + /* Measure data */ + measureData(); + /* go to sleep */ + esp_deep_sleep_start(); + + } + delay(100); +} + +void write_String(char add, String data) +{ + int _size = data.length(); + int i; + for(i=0;i<_size;i++) + { + EEPROM.write(add+i,data[i]); + } + EEPROM.write(add+_size,'\0'); //Add termination null character for String Data + EEPROM.commit(); +} + +String read_String(char add) +{ + int i; + char data[100]; //Max 100 Bytes + int len=0; + unsigned char k; + k=EEPROM.read(add); + while(k != '\0' && len<500) //Read until null character + { + k=EEPROM.read(add+len); + data[len]=k; + len++; + } + data[len]='\0'; + return String(data); +} + +void handle_client_connection(WiFiClient client) { + Serial.println("New Client connected."); // print a message out the serial port + String currentLine = ""; // make a String to hold incoming data from the client + while (client.connected()) { // loop while the client's connected + if (client.available()) { // if there's bytes to read from the client, + char c = client.read(); // read a byte, then + //Serial.write(c); // print it out the serial monitor + + if (c != '\r') { // if you got anything else but a carriage return character, + currentLine += c; // add it to the end of the currentLine + } + + // Check to see if the client request was a valid SSID and PW + if (currentLine.endsWith(ssidStart)) { + user_ssid = currentLine.substring(0, currentLine.length() - ssidStart.length()); //extract SSID from input + Serial.println(new_ssid.c_str()); + write_String(1, user_ssid); //write SSID into memory + Serial.println(read_String(1)); + currentLine = ""; + } + else if (currentLine.endsWith(pwStart)) { + String user_pw = currentLine.substring(0, currentLine.length() - pwStart.length()); //extract PW from input + Serial.println(new_pw.c_str()); + if(user_ssid.length() > 0) { //if we got a valid SSID + write_String(new_ssid.length()+2, new_pw); //write PW behind the SSID string into memory + Serial.println(read_String(new_ssid.length()+2)); + + // read WiFi SSID and PW from memory + user_ssid = read_String(1); + user_pw = read_String(user_ssid.length()+2); + + WiFi.softAPdisconnect(true); //shut down AP + connect_to_wifi(new_ssid, new_pw); //connect to WiFi using the newly entered credentials + } + currentLine = ""; + } + + if(c == '\n') { + currentLine = ""; + } + Serial.flush(); + } + } + // close the connection: + client.stop(); + Serial.println("Client Disconnected."); +} + +void connect_to_wifi(String ssid, String pw) { + WiFi.begin(ssid.c_str(), pw.c_str()); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + if(setup_is_on()) { + turn_off_setup(); //write SETUP_OFF bit into memory + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); +} + +void turn_off_setup() { + EEPROM.write(0, (int)setup_off); + EEPROM.commit(); +} + +void turn_on_setup() { + EEPROM.write(0, (int)setup_on); + EEPROM.commit(); +} + +bool setup_is_on() { + return EEPROM.read(0) == (int)setup_on; +} + +bool setup_is_off() { + return EEPROM.read(0) != (int)setup_on; +} + +void setupSleepTimer(){ + esp_sleep_enable_timer_wakeup(SLEEP_TIME * uS_TO_S_FACTOR); + Serial.println("Setup ESP32 to sleep for every " + String(SLEEP_TIME) + " Seconds"); +} + +void measureData() { + Serial.println(bme1.readAltitude(SEALEVELPRESSURE_HPA)); + Serial.println(bme2.readAltitude(SEALEVELPRESSURE_HPA)); + /* 0-2 Device with L2C address 0x76 {tmp, hum, pres, altitude} */ + /* 3-5 Device with L2C address 0x77 {tmp, hum, pres, altitude} */ + double measurements [8] = {0}; + for(int i = 0; i < 5; ++i){ + measurements[0] += bme1.readTemperature(); + measurements[1] += bme1.readHumidity(); + measurements[2] += bme1.readPressure(); + measurements[3] += bme1.readAltitude(SEALEVELPRESSURE_HPA); + measurements[4] += bme2.readTemperature(); + measurements[5] += bme2.readHumidity(); + measurements[6] += bme2.readPressure(); + measurements[7] += bme2.readAltitude(SEALEVELPRESSURE_HPA); + } + + Serial.println("SENSOR - 1"); + Serial.print("Temperature = "); + Serial.print(measurements[0]/5); + Serial.println(" *C"); + + Serial.print("Humidity = "); + Serial.print(measurements[1]/5); + Serial.println(" %"); + + Serial.print("Pressure = "); + Serial.print(measurements[2]/5/100.0F); + Serial.println(" hPa"); + + Serial.print("Altitude = "); + Serial.print(measurements[3]/5); + Serial.println(" m"); + + Serial.println("SENSOR - 2"); + Serial.print("Temperature = "); + Serial.print(measurements[4]/5); + Serial.println(" *C"); + + Serial.print("Humidity = "); + Serial.print(measurements[5]/5); + Serial.println(" %"); + + Serial.print("Pressure = "); + Serial.print(measurements[6]/5/100.0F); + Serial.println(" hPa"); + + Serial.print("Altitude = "); + Serial.print(measurements[7]/5); + Serial.println(" m"); + + Serial.println(); +} + +void printAddress(){ + byte error, address; + int nDevices; + + Serial.println("Scanning..."); + + nDevices = 0; + for(address = 1; address < 127; address++ ) + { + // The i2c_scanner uses the return value of + // the Write.endTransmisstion to see if + // a device did acknowledge to the address. + Wire.beginTransmission(address); + error = Wire.endTransmission(); + + if (error == 0) + { + Serial.print("I2C device found at address 0x"); + if (address<16) + Serial.print("0"); + Serial.print(address,HEX); + Serial.println(" !"); + + nDevices++; + } + else if (error==4) + { + Serial.print("Unknown error at address 0x"); + if (address<16) + Serial.print("0"); + Serial.println(address,HEX); + } + } + if (nDevices == 0) + Serial.println("No I2C devices found\n"); + else + Serial.println("done\n"); + + delay(500); // wait 5 seconds for next scan +} + +void checkStatus() { + unsigned status1; + unsigned status2; + status1 = bme1.begin(0x76); + status2 = bme2.begin(0x77); + if (!status1 || !status2) { + Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!"); + Serial.print("SensorID was: 0x"); Serial.println(bme1.sensorID(),16); + //Serial.print("SensorID was: 0x"); Serial.println(bme2.sensorID(),16); + Serial.print("ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n"); + Serial.print("ID of 0x56-0x58 represents a BMP 280,\n"); + Serial.print("ID of 0x60 represents a BME 280.\n"); + Serial.print("ID of 0x61 represents a BME 680.\n"); + while (1); + } + Serial.print("Status checked"); +} + +void print_wakeup_reason(){ + esp_sleep_wakeup_cause_t wakeup_reason; + wakeup_reason = esp_sleep_get_wakeup_cause(); + switch(wakeup_reason) + { + case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; + case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; + case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; + case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; + case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; + default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; + } +} diff --git a/ios-app/app/ContentView.swift b/ios-app/app/ContentView.swift index 302ab8a2..ec277092 100644 --- a/ios-app/app/ContentView.swift +++ b/ios-app/app/ContentView.swift @@ -10,9 +10,11 @@ import SwiftUI import Alamofire import MowestaApi +typealias UIState = SwiftUI.State + class BuildData: ObservableObject { @Published var loading = true; - @Published var version = BuildVersion(build: "", creator: "", time: 0, version: "") + @Published var version = BuildVersion(time: 0, build: "", creator: "", version: "") } struct ContentView: View { @@ -36,7 +38,7 @@ struct ContentView: View { } struct ActivityIndicator: View { - @State var spinCircle = false + @UIState var spinCircle = false var body: some View { ZStack { @@ -55,8 +57,8 @@ struct ActivityIndicator: View { } struct LabelText: View { - @State var label: String - @State var text: String + @UIState var label: String + @UIState var text: String var body: some View { HStack { Text(label).font(.caption).bold() diff --git a/service-data/src/main/java/com/mowesta/data/nominatim/NominatimCity.java b/service-data/src/main/java/com/mowesta/data/nominatim/NominatimCity.java index 068bc466..c3059472 100644 --- a/service-data/src/main/java/com/mowesta/data/nominatim/NominatimCity.java +++ b/service-data/src/main/java/com/mowesta/data/nominatim/NominatimCity.java @@ -3,149 +3,102 @@ package com.mowesta.data.nominatim; import com.mowesta.api.location.CityType; /** - * Represents a city or town (e.g. Essen, Troisdorf, etc.). + * Represents a city or town (e.g. Essen, Troisdorf, etc.). * * @author Marcus */ public class NominatimCity extends NominatimObject { - - /** - * A flag to indicate whether this is the capital of the country. - */ - private boolean capital; - - /** - * The optional population of the city. - */ - private Integer population; - - /** - * The type of the city. - */ - private CityType type; - /** - * The optional state that contains this city. - */ - private Long state; - - /** - * The country that contains this city. - */ - private long country; - - /** - * The id of the timezone as defined by java.time.TimeId. - */ - private String timezone; - - /** - * Returns the capital. - * - * @return The capital. - */ - public boolean isCapital() { - return capital; - } + /** + * A flag to indicate whether this is the capital of the country. + */ + private boolean capital; - /** - * Sets the capital. - * - * @param capital The capital to set. - */ - public void setCapital(boolean capital) { - this.capital = capital; - } + /** + * The type of the city. + */ + private CityType type; - /** - * Returns the population. - * - * @return The population. - */ - public Integer getPopulation() { - return population; - } + /** + * The optional state that contains this city. + */ + private Long state; - /** - * Sets the population. - * - * @param population The population to set. - */ - public void setPopulation(Integer population) { - this.population = population; - } + /** + * The country that contains this city. + */ + private long country; - /** - * Returns the type. - * - * @return The type. - */ - public CityType getType() { - return type; - } + /** + * Returns the capital. + * + * @return The capital. + */ + public boolean isCapital() { + return capital; + } - /** - * Sets the type. - * - * @param type The type to set. - */ - public void setType(CityType type) { - this.type = type; - } + /** + * Sets the capital. + * + * @param capital The capital to set. + */ + public void setCapital(boolean capital) { + this.capital = capital; + } - /** - * Returns the state. - * - * @return The state. - */ - public Long getState() { - return state; - } + /** + * Returns the type. + * + * @return The type. + */ + public CityType getType() { + return type; + } - /** - * Sets the state. - * - * @param state The state to set. - */ - public void setState(Long state) { - this.state = state; - } + /** + * Sets the type. + * + * @param type The type to set. + */ + public void setType(CityType type) { + this.type = type; + } - /** - * Returns the country. - * - * @return The country. - */ - public long getCountry() { - return country; - } + /** + * Returns the state. + * + * @return The state. + */ + public Long getState() { + return state; + } - /** - * Sets the country. - * - * @param country The country to set. - */ - public void setCountry(long country) { - this.country = country; - } + /** + * Sets the state. + * + * @param state The state to set. + */ + public void setState(Long state) { + this.state = state; + } - /** - * Returns the timezone. - * - * @return The timezone. - */ - public String getTimezone() { - return timezone; - } + /** + * Returns the country. + * + * @return The country. + */ + public long getCountry() { + return country; + } + + /** + * Sets the country. + * + * @param country The country to set. + */ + public void setCountry(long country) { + this.country = country; + } - /** - * Sets the timezone. - * - * @param timezone The timezone to set. - */ - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - } diff --git a/service-data/src/main/java/com/mowesta/data/nominatim/NominatimObject.java b/service-data/src/main/java/com/mowesta/data/nominatim/NominatimObject.java index e220a9fa..c13897cb 100644 --- a/service-data/src/main/java/com/mowesta/data/nominatim/NominatimObject.java +++ b/service-data/src/main/java/com/mowesta/data/nominatim/NominatimObject.java @@ -7,198 +7,242 @@ import org.geojson.Geometry; import org.geojson.Point; /** - * A base class for the format of data exported from - * the nominatim tool. + * A base class for the format of data exported from the nominatim tool. * * @author Marcus * */ public class NominatimObject { - /** - * The id of the object. Other objects may - * refer to this. - */ - private long id; - - /** - * The names of the object. - */ - private Map names = new HashMap<>(); + /** + * The id of the object. Other objects may refer to this. + */ + private long id; - /** - * The longitude and latitude of the centroid of the object. - */ - private Point centroid; - - /** - * The optional boundary of the object which should be a polygon - * or multipolygon. - */ - private Geometry boundary; + /** + * The names of the object. + */ + private Map names = new HashMap<>(); - /** - * An optional importance value for search ranking. - */ - private Double importance; - - /** - * The nominatim search rank. - */ - private Short searchRank; - - /** - * The nominatim address rank. - */ - private Short addressRank; - - /** - * The optional wikipedia entry. - */ - private String wikipedia; - - /** - * Returns the id. - * - * @return The id. - */ - public long getId() { - return id; - } + /** + * The longitude and latitude of the centroid of the object. + */ + private Point centroid; - /** - * Sets the id. - * - * @param id The id to set. - */ - public void setId(long id) { - this.id = id; - } + /** + * The optional boundary of the object which should be a polygon or + * multipolygon. + */ + private Geometry boundary; - /** - * Returns the names. - * - * @return The names. - */ - public Map getNames() { - return names; - } + /** + * An optional importance value for search ranking. + */ + private Double importance; - /** - * Sets the names. - * - * @param names The names to set. - */ - public void setNames(Map names) { - this.names = names; - } + /** + * The nominatim search rank. + */ + private Short searchRank; - /** - * Returns the centroid. - * - * @return The centroid. - */ - public Point getCentroid() { - return centroid; - } + /** + * The nominatim address rank. + */ + private Short addressRank; - /** - * Sets the centroid. - * - * @param centroid The centroid to set. - */ - public void setCentroid(Point centroid) { - this.centroid = centroid; - } + /** + * The optional population. + */ + private Integer population; - /** - * Returns the boundary. - * - * @return The boundary. - */ - public Geometry getBoundary() { - return boundary; - } + /** + * The id of the timezone as defined by java.time.TimeId. + */ + private String timezone; - /** - * Sets the boundary. - * - * @param boundary The boundary to set. - */ - public void setBoundary(Geometry boundary) { - this.boundary = boundary; - } + /** + * The optional wikipedia entry. + */ + private String wikipedia; - /** - * Returns the importance. - * - * @return The importance. - */ - public Double getImportance() { - return importance; - } + /** + * Returns the id. + * + * @return The id. + */ + public long getId() { + return id; + } - /** - * Sets the importance. - * - * @param importance The importance to set. - */ - public void setImportance(Double importance) { - this.importance = importance; - } + /** + * Sets the id. + * + * @param id The id to set. + */ + public void setId(long id) { + this.id = id; + } - /** - * Returns the searchRank. - * - * @return The searchRank. - */ - public Short getSearchRank() { - return searchRank; - } + /** + * Returns the names. + * + * @return The names. + */ + public Map getNames() { + return names; + } - /** - * Sets the searchRank. - * - * @param searchRank The searchRank to set. - */ - public void setSearchRank(Short searchRank) { - this.searchRank = searchRank; - } + /** + * Sets the names. + * + * @param names The names to set. + */ + public void setNames(Map names) { + this.names = names; + } - /** - * Returns the addressRank. - * - * @return The addressRank. - */ - public Short getAddressRank() { - return addressRank; - } + /** + * Returns the centroid. + * + * @return The centroid. + */ + public Point getCentroid() { + return centroid; + } - /** - * Sets the addressRank. - * - * @param addressRank The addressRank to set. - */ - public void setAddressRank(Short addressRank) { - this.addressRank = addressRank; - } + /** + * Sets the centroid. + * + * @param centroid The centroid to set. + */ + public void setCentroid(Point centroid) { + this.centroid = centroid; + } - /** - * Returns the wikipedia. - * - * @return The wikipedia. - */ - public String getWikipedia() { - return wikipedia; - } + /** + * Returns the boundary. + * + * @return The boundary. + */ + public Geometry getBoundary() { + return boundary; + } + + /** + * Sets the boundary. + * + * @param boundary The boundary to set. + */ + public void setBoundary(Geometry boundary) { + this.boundary = boundary; + } + + /** + * Returns the importance. + * + * @return The importance. + */ + public Double getImportance() { + return importance; + } + + /** + * Sets the importance. + * + * @param importance The importance to set. + */ + public void setImportance(Double importance) { + this.importance = importance; + } + + /** + * Returns the searchRank. + * + * @return The searchRank. + */ + public Short getSearchRank() { + return searchRank; + } + + /** + * Sets the searchRank. + * + * @param searchRank The searchRank to set. + */ + public void setSearchRank(Short searchRank) { + this.searchRank = searchRank; + } + + /** + * Returns the addressRank. + * + * @return The addressRank. + */ + public Short getAddressRank() { + return addressRank; + } + + /** + * Sets the addressRank. + * + * @param addressRank The addressRank to set. + */ + public void setAddressRank(Short addressRank) { + this.addressRank = addressRank; + } + + /** + * Returns the population. + * + * @return The population. + */ + public Integer getPopulation() { + return population; + } + + /** + * Sets the population. + * + * @param population The population to set. + */ + public void setPopulation(Integer population) { + this.population = population; + } + + /** + * Returns the timezone. + * + * @return The timezone. + */ + public String getTimezone() { + return timezone; + } + + /** + * Sets the timezone. + * + * @param timezone The timezone to set. + */ + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + /** + * Returns the wikipedia. + * + * @return The wikipedia. + */ + public String getWikipedia() { + return wikipedia; + } + + /** + * Sets the wikipedia. + * + * @param wikipedia The wikipedia to set. + */ + public void setWikipedia(String wikipedia) { + this.wikipedia = wikipedia; + } - /** - * Sets the wikipedia. - * - * @param wikipedia The wikipedia to set. - */ - public void setWikipedia(String wikipedia) { - this.wikipedia = wikipedia; - } - } diff --git a/service-ejb/src/main/java/com/mowesta/service/conversion/AbstractLocationConverter.java b/service-ejb/src/main/java/com/mowesta/service/conversion/AbstractLocationConverter.java index 59cc6219..e15bd061 100644 --- a/service-ejb/src/main/java/com/mowesta/service/conversion/AbstractLocationConverter.java +++ b/service-ejb/src/main/java/com/mowesta/service/conversion/AbstractLocationConverter.java @@ -32,7 +32,7 @@ public abstract class AbstractLocationConverter { +public abstract class CountryLocationConverter extends AbstractLocationConverter { } diff --git a/service-ejb/src/main/java/com/mowesta/service/conversion/StateConverter.java b/service-ejb/src/main/java/com/mowesta/service/conversion/StateConverter.java index a8af660b..aabe3d07 100644 --- a/service-ejb/src/main/java/com/mowesta/service/conversion/StateConverter.java +++ b/service-ejb/src/main/java/com/mowesta/service/conversion/StateConverter.java @@ -2,15 +2,14 @@ package com.mowesta.service.conversion; import org.mapstruct.Mapper; -import com.mowesta.api.location.Location; +import com.mowesta.api.location.State; import com.mowesta.service.entity.StateEntity; /** - * A converter for emails. + * A converter for states. * - * @author Marcus + * @author Sebastian */ @Mapper(config = AbstractConverter.class) -public abstract class StateConverter extends AbstractLocationConverter { - +public abstract class StateConverter extends AbstractLocationConverter { } diff --git a/service-ejb/src/main/java/com/mowesta/service/conversion/StateDigestConverter.java b/service-ejb/src/main/java/com/mowesta/service/conversion/StateDigestConverter.java new file mode 100644 index 00000000..4734004f --- /dev/null +++ b/service-ejb/src/main/java/com/mowesta/service/conversion/StateDigestConverter.java @@ -0,0 +1,16 @@ +package com.mowesta.service.conversion; + +import org.mapstruct.Mapper; + +import com.mowesta.api.location.StateDigest; +import com.mowesta.service.entity.StateEntity; + +/** + * A converter for state digests. + * + * @author Sebastian + */ +@Mapper(config = AbstractConverter.class) +public abstract class StateDigestConverter extends AbstractLocationConverter { + +} diff --git a/service-ejb/src/main/java/com/mowesta/service/conversion/StateLocationConverter.java b/service-ejb/src/main/java/com/mowesta/service/conversion/StateLocationConverter.java new file mode 100644 index 00000000..415db243 --- /dev/null +++ b/service-ejb/src/main/java/com/mowesta/service/conversion/StateLocationConverter.java @@ -0,0 +1,16 @@ +package com.mowesta.service.conversion; + +import org.mapstruct.Mapper; + +import com.mowesta.api.location.Location; +import com.mowesta.service.entity.StateEntity; + +/** + * A converter for state to location. + * + * @author Marcus + */ +@Mapper(config = AbstractConverter.class) +public abstract class StateLocationConverter extends AbstractLocationConverter { + +} diff --git a/service-ejb/src/main/java/com/mowesta/service/entity/CityEntity.java b/service-ejb/src/main/java/com/mowesta/service/entity/CityEntity.java index 300750d5..59351017 100644 --- a/service-ejb/src/main/java/com/mowesta/service/entity/CityEntity.java +++ b/service-ejb/src/main/java/com/mowesta/service/entity/CityEntity.java @@ -33,231 +33,225 @@ import com.mowesta.api.location.CityType; * @author Marcus */ @Entity -@Table(name = "city", indexes = { @Index(columnList = "externalId", unique = true), @Index(columnList="deleted,modificationTime", unique = false) }) +@Table(name = "city", indexes = { @Index(columnList = "externalId", unique = true), + @Index(columnList = "deleted,modificationTime", unique = false) }) @Indexed public class CityEntity extends AbstractLocationEntity { - /** - * The serialization id. - */ - private static final long serialVersionUID = -6621003401388720889L; + /** + * The serialization id. + */ + private static final long serialVersionUID = -6621003401388720889L; - /** - * The type of the city. - */ - @Enumerated(EnumType.ORDINAL) - @Field - private CityType type; + /** + * The type of the city. + */ + @Enumerated(EnumType.ORDINAL) + @Field + private CityType type; - /** - * The timezone of the city. - */ - @NotNull - @Column(length = 32) - private String timezone; + /** + * The timezone of the city. + */ + @NotNull + @Column(length = 32) + private String timezone; - /** - * A flag to indicate whether the city is a capital. - */ - private boolean capital; + /** + * A flag to indicate whether the city is a capital. + */ + private boolean capital; - /** - * The optional population of the city. - */ - private Integer population; + /** + * The optional population of the city. + */ + private Integer population; - /** - * The country of the city. - */ - @NotNull - @JoinColumn(name = "country_id") - @ManyToOne(fetch = FetchType.LAZY) - @IndexedEmbedded - private CountryEntity country; + /** + * The country of the city. + */ + @NotNull + @JoinColumn(name = "country_id") + @ManyToOne(fetch = FetchType.LAZY) + @IndexedEmbedded + private CountryEntity country; - /** - * The state of the city. - */ - @JoinColumn(name = "state_id") - @ManyToOne(fetch = FetchType.LAZY) - @IndexedEmbedded - private StateEntity state; - - /** - * Returns the type. - * - * @return The type. - */ - public CityType getType() { - return type; - } + /** + * The state of the city. + */ + @JoinColumn(name = "state_id") + @ManyToOne(fetch = FetchType.LAZY) + @IndexedEmbedded + private StateEntity state; - /** - * Sets the type. - * - * @param type The type to set. - */ - public void setType(CityType type) { - this.type = type; - } + /** + * Returns the type. + * + * @return The type. + */ + public CityType getType() { + return type; + } - /** - * Returns the timezone. - * - * @return The timezone. - */ - public String getTimezone() { - return timezone; - } + /** + * Sets the type. + * + * @param type The type to set. + */ + public void setType(CityType type) { + this.type = type; + } - /** - * Sets the timezone. - * - * @param timezone - * The timezone to set. - */ - public void setTimezone(String timezone) { - this.timezone = timezone; - } + /** + * Returns the timezone. + * + * @return The timezone. + */ + public String getTimezone() { + return timezone; + } - /** - * Returns the capital. - * - * @return The capital. - */ - public boolean isCapital() { - return capital; - } + /** + * Sets the timezone. + * + * @param timezone The timezone to set. + */ + public void setTimezone(String timezone) { + this.timezone = timezone; + } - /** - * Sets the capital. - * - * @param capital - * The capital to set. - */ - public void setCapital(boolean capital) { - this.capital = capital; - } + /** + * Returns the capital. + * + * @return The capital. + */ + public boolean isCapital() { + return capital; + } - /** - * Returns the population. - * - * @return The population. - */ - public Integer getPopulation() { - return population; - } + /** + * Sets the capital. + * + * @param capital The capital to set. + */ + public void setCapital(boolean capital) { + this.capital = capital; + } - /** - * Sets the population. - * - * @param population - * The population to set. - */ - public void setPopulation(Integer population) { - this.population = population; - } + /** + * Returns the population. + * + * @return The population. + */ + public Integer getPopulation() { + return population; + } - /** - * Returns the country. - * - * @return The country. - */ - public CountryEntity getCountry() { - return country; - } + /** + * Sets the population. + * + * @param population The population to set. + */ + public void setPopulation(Integer population) { + this.population = population; + } - /** - * Sets the country. - * - * @param country - * The country to set. - */ - public void setCountry(CountryEntity country) { - this.country = country; - } + /** + * Returns the country. + * + * @return The country. + */ + public CountryEntity getCountry() { + return country; + } - /** - * Returns the state. - * - * @return The state. - */ - public StateEntity getState() { - return state; - } + /** + * Sets the country. + * + * @param country The country to set. + */ + public void setCountry(CountryEntity country) { + this.country = country; + } - /** - * Sets the state. - * - * @param state - * The state to set. - */ - public void setState(StateEntity state) { - this.state = state; - } - - /** - * Returns an approximate number of results for a query for the term. - * - * @param em The entity manager. - * @param language The user interface language. - * @param term The search term. - * @return The count. - */ - public static int countAllByTerm(EntityManager em, Language language, String term) { - FullTextQuery query = createQueryByTerm(em, language, term); - return query.getResultSize(); - } + /** + * Returns the state. + * + * @return The state. + */ + public StateEntity getState() { + return state; + } - /** - * Returns the list of cities whose names matches the query for the specified page config. - * - * @param em The entity manager. - * @param config The page config to limit the result. - * @param language The user interface language. - * @param term The search term. - * @return The result list. - */ - @SuppressWarnings("unchecked") - public static List findAllByTerm(EntityManager em, PageConfig config, Language language, String term) { - FullTextQuery query = createQueryByTerm(em, language, term); - query.setFirstResult(config.getOffset()); - query.setMaxResults(config.getSize()); - return (List)query.getResultList(); - } + /** + * Sets the state. + * + * @param state The state to set. + */ + public void setState(StateEntity state) { + this.state = state; + } + + /** + * Returns an approximate number of results for a query for the term. + * + * @param em The entity manager. + * @param language The user interface language. + * @param term The search term. + * @return The count. + */ + public static int countAllByTerm(EntityManager em, Language language, String term) { + FullTextQuery query = createQueryByTerm(em, language, term); + return query.getResultSize(); + } + + /** + * Returns the list of cities whose names matches the query for the specified + * page config. + * + * @param em The entity manager. + * @param config The page config to limit the result. + * @param language The user interface language. + * @param term The search term. + * @return The result list. + */ + @SuppressWarnings("unchecked") + public static List findAllByTerm(EntityManager em, PageConfig config, Language language, String term) { + FullTextQuery query = createQueryByTerm(em, language, term); + query.setFirstResult(config.getOffset()); + query.setMaxResults(config.getSize()); + return (List) query.getResultList(); + } + + /** + * Creates a full-text query over the cities that searches in the city, country + * and state names. + * + * @param em The entity manager. + * @param language The ui language. + * @param term The term to search. + * @return The query. + */ + private static FullTextQuery createQueryByTerm(EntityManager em, Language language, String term) { + FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em); + QueryBuilder builder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(CityEntity.class) + .get(); + String[] base = new String[] { "names", "state.names", "country.names" }; + String[] names = new String[] { "local", null }; + switch (language) { + case ENGLISH: + names[1] = "english"; + case GERMAN: + names[1] = "german"; + } + String[] fields = new String[names.length * base.length]; + for (int i = 0; i < base.length; i++) { + for (int j = 0; j < names.length; j++) { + fields[j + i * names.length] = base[i] + "." + names[j]; + } + } + Query query = builder.keyword().onFields(fields).matching(term).createQuery(); + return fullTextEntityManager.createFullTextQuery(query, CityEntity.class); + } - /** - * Creates a full-text query over the cities that searches in the city, country and state names. - * - * @param em The entity manager. - * @param language The ui language. - * @param term The term to search. - * @return The query. - */ - private static FullTextQuery createQueryByTerm(EntityManager em, Language language, String term) { - FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em); - QueryBuilder builder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(CityEntity.class).get(); - String[] base = new String[] { "names", "state.names", "country.names" }; - String[] names = new String[] { "local", null }; - switch (language) { - case ENGLISH: - names[1] = "english"; - case GERMAN: - names[1] = "german"; - } - String[] fields = new String[names.length * base.length]; - for (int i = 0; i < base.length; i++) { - for (int j = 0; j < names.length; j++) { - fields[j + i * names.length] = base[i] + "." + names[j]; - } - } - Query query = builder - .keyword() - .onFields(fields) - .matching(term) - .createQuery(); - return fullTextEntityManager.createFullTextQuery(query, CityEntity.class); - } - - } diff --git a/service-ejb/src/main/java/com/mowesta/service/entity/StateEntity.java b/service-ejb/src/main/java/com/mowesta/service/entity/StateEntity.java index a4631843..ce302e11 100644 --- a/service-ejb/src/main/java/com/mowesta/service/entity/StateEntity.java +++ b/service-ejb/src/main/java/com/mowesta/service/entity/StateEntity.java @@ -1,79 +1,200 @@ package com.mowesta.service.entity; +import java.util.List; +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EntityManager; +import javax.persistence.FetchType; +import javax.persistence.Index; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +import org.apache.lucene.search.Query; import org.hibernate.search.annotations.ContainedIn; import org.hibernate.search.annotations.Indexed; +import org.hibernate.search.annotations.IndexedEmbedded; +import org.hibernate.search.jpa.FullTextEntityManager; +import org.hibernate.search.jpa.FullTextQuery; +import org.hibernate.search.jpa.Search; +import org.hibernate.search.query.dsl.QueryBuilder; -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import java.util.Set; +import com.mowesta.api.Language; +import com.mowesta.api.PageConfig; /** * Represents a state. * - * @author Marcus + * @author Marcus, Sebastian */ @Entity -@Table(name = "state", indexes = { @Index(columnList = "externalId", unique = true), @Index(columnList="deleted,modificationTime", unique = false) }) +@Table(name = "state", indexes = { @Index(columnList = "externalId", unique = true), + @Index(columnList = "deleted,modificationTime", unique = false) }) @Indexed public class StateEntity extends AbstractLocationEntity { - + /** * The serialization id. */ private static final long serialVersionUID = 3335679745383089451L; - + + /** + * The timezone of the state. + */ + //@NotNull + @Column(length = 32) + private String timezone; + + /** + * The optional population of the city. + */ + private Integer population; + /** * The states of the state. */ - @NotNull - @JoinColumn(name="country_id") + @NotNull + @JoinColumn(name = "country_id") @ManyToOne(fetch = FetchType.LAZY) + @IndexedEmbedded private CountryEntity country; - /** - * A reference to the states used to tell hibernate - * search that the cities must be updated if the state's - * fields change. - */ - @ContainedIn - @OneToMany(fetch = FetchType.LAZY, mappedBy = "state") - private Set cities; + /** + * A reference to the states used to tell hibernate search that the cities must + * be updated if the state's fields change. + */ + @ContainedIn + @OneToMany(fetch = FetchType.LAZY, mappedBy = "state") + private Set cities; - - /** - * Returns the country. - * - * @return The country. - */ - public CountryEntity getCountry() { - return country; - } + /** + * Returns the country. + * + * @return The country. + */ + public CountryEntity getCountry() { + return country; + } - /** - * Sets the country. - * - * @param country The country to set. - */ - public void setCountry(CountryEntity country) { - this.country = country; - } + /** + * Sets the country. + * + * @param country The country to set. + */ + public void setCountry(CountryEntity country) { + this.country = country; + } - /** - * Returns the cities. - * - * @return The cities. - */ - public Set getCities() { - return cities; - } + /** + * Returns the cities. + * + * @return The cities. + */ + public Set getCities() { + return cities; + } + + /** + * Sets the cities. + * + * @param cities The cities to set. + */ + public void setCities(Set cities) { + this.cities = cities; + } + + /** + * @return the timezone + */ + public String getTimezone() { + return timezone; + } + + /** + * @param timezone the timezone to set + */ + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + /** + * @return the population + */ + public Integer getPopulation() { + return population; + } + + /** + * @param population the population to set + */ + public void setPopulation(Integer population) { + this.population = population; + } + + /** + * Returns an approximate number of results for a query for the term. + * + * @param em The entity manager. + * @param language The user interface language. + * @param term The search term. + * @return The count. + */ + public static int countAllByTerm(EntityManager em, Language language, String term) { + FullTextQuery query = createQueryByTerm(em, language, term); + return query.getResultSize(); + } + + /** + * Returns the list of states whose names matches the query for the specified + * page config. + * + * @param em The entity manager. + * @param config The page config to limit the result. + * @param language The user interface language. + * @param term The search term. + * @return The result list. + */ + @SuppressWarnings("unchecked") + public static List findAllByTerm(EntityManager em, PageConfig config, Language language, String term) { + FullTextQuery query = createQueryByTerm(em, language, term); + query.setFirstResult(config.getOffset()); + query.setMaxResults(config.getSize()); + return (List) query.getResultList(); + } + + /** + * Creates a full-text query over the states that searches in the country and + * state names. + * + * @param em The entity manager. + * @param language The ui language. + * @param term The term to search. + * @return The query. + */ + private static FullTextQuery createQueryByTerm(EntityManager em, Language language, String term) { + FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em); + QueryBuilder builder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(StateEntity.class) + .get(); + String[] base = new String[] { "names", "country.names" }; + String[] names = new String[] { "local", null }; + switch (language) { + case ENGLISH: + names[1] = "english"; + case GERMAN: + names[1] = "german"; + } + String[] fields = new String[names.length * base.length]; + for (int i = 0; i < base.length; i++) { + for (int j = 0; j < names.length; j++) { + fields[j + i * names.length] = base[i] + "." + names[j]; + } + } + Query query = builder.keyword().onFields(fields).matching(term).createQuery(); + return fullTextEntityManager.createFullTextQuery(query, StateEntity.class); + } - /** - * Sets the cities. - * - * @param cities The cities to set. - */ - public void setCities(Set cities) { - this.cities = cities; - } - } diff --git a/service-ejb/src/main/java/com/mowesta/service/session/LocationSessionBean.java b/service-ejb/src/main/java/com/mowesta/service/session/LocationSessionBean.java index 19fab0fd..9f099391 100644 --- a/service-ejb/src/main/java/com/mowesta/service/session/LocationSessionBean.java +++ b/service-ejb/src/main/java/com/mowesta/service/session/LocationSessionBean.java @@ -9,9 +9,14 @@ import com.mowesta.api.location.City; import com.mowesta.api.location.CityDigestPage; import com.mowesta.api.location.CityPage; import com.mowesta.api.location.SearchContext; +import com.mowesta.api.location.State; +import com.mowesta.api.location.StateDigestPage; +import com.mowesta.api.location.StatePage; import com.mowesta.service.conversion.CityConverter; import com.mowesta.service.conversion.CityDigestConverter; import com.mowesta.service.conversion.Convert; +import com.mowesta.service.conversion.StateConverter; +import com.mowesta.service.conversion.StateDigestConverter; import com.mowesta.service.entity.AbstractEntity; import com.mowesta.service.entity.CityEntity; import com.mowesta.service.entity.CountryEntity; @@ -28,105 +33,194 @@ import com.mowesta.service.entity.StateEntity; @RequestScoped public class LocationSessionBean extends AbstractSessionBean { - /** - * Finds the cities by a search term. - * - * @param config The page configuration. - * @param context The search context. - * @param term The search term. - * @return The page with the results. - */ - @PermitAll - public CityDigestPage findCities(PageConfig config, SearchContext context, String term) { - CityDigestPage page = new CityDigestPage(); - page.setOffset(config.getOffset()); - page.setSize(config.getSize()); - page.setTotal(CityEntity.countAllByTerm(em, context.getLanguage(), term)); - page.setElements(Convert.with(CityDigestConverter.class).apply(CityEntity.findAllByTerm(em, config, context.getLanguage(), term), false)); - if (page.getTotal() < page.getOffset() + page.getElements().size()) { - page.setTotal(page.getOffset() + page.getElements().size()); - } - return page; - } - - - /** - * Returns the city with the specified id. - * - * @param id The id fo the city. - * @param filtered True to filter deleted. - * @return The city with the id. - * @throws EntityNotFoundException Thrown if the city does not exist. - */ - @PermitAll - public City getCity(long id, boolean filtered) throws EntityNotFoundException { - CityEntity city = em.find(CityEntity.class, new Long(id)); - if (city == null || (filtered && city.isDeleted())) throw new EntityNotFoundException(CityEntity.class, id, "City not found."); - return Convert.with(CityConverter.class).apply(city, filtered); - } - - /** - * Returns the modification date of the city, thereby - * considering the country and state as well. - * - * @param id The id of the city. - * @return The maximum time stamp of the city, state and - * country referenced by the city or 0, if the city does - * not exist. - */ - @PermitAll - public long getLastModifiedCity(long id) { - long result = 0; - CityEntity city = em.find(CityEntity.class, new Long(id)); - if (city == null) return result; - if (city.getState() != null) result = city.getState().getModificationTime(); - result = Math.max(result, city.getCountry().getModificationTime()); - result = Math.max(result, city.getModificationTime()); - return result; - } - - /** - * Returns the maximum last modification time stamp - * over all location tables. - * - * @return The maximum modification. - */ - @PermitAll - public long getLastModifiedLocation() { - long result = 0; - @SuppressWarnings("unchecked") - Class[] types = new Class[] { CityEntity.class, CountryEntity.class, StateEntity.class }; - for (Class type: types) { - result = Math.max(result, AbstractEntity.getLastModified(em, type)); - } - return result; - } - - /** - * Returns the boundary of the city with the specified id or null, - * if the city does not have a boundary. - * - * @param id The id. - * @return The city boundary as a geojson string. - * @throws EntityNotFoundException Thrown if the city cannot be found. - */ - @PermitAll - public String getCityBoundary(long id) throws EntityNotFoundException { - CityEntity city = em.find(CityEntity.class, new Long(id)); - if (city == null) throw new EntityNotFoundException(CityEntity.class, id, "City not found."); - return city.getBoundary(); - } - - /** - * Returns all cities via pagination. - * - * @param config The page config. - * @param filtered True to filter deleted, false otherwise. - * @return The page according to the config. - */ - @PermitAll - public CityPage getAllCities(PageConfig config, boolean filtered) { - return getAll(CityEntity.class, config, new OrderCriterion("id"), filtered, new CityPage(), CityConverter.class); - } - + /** + * Finds the cities by a search term. + * + * @param config The page configuration. + * @param context The search context. + * @param term The search term. + * @return The page with the results. + */ + @PermitAll + public CityDigestPage findCities(PageConfig config, SearchContext context, String term) { + CityDigestPage page = new CityDigestPage(); + page.setOffset(config.getOffset()); + page.setSize(config.getSize()); + page.setTotal(CityEntity.countAllByTerm(em, context.getLanguage(), term)); + page.setElements(Convert.with(CityDigestConverter.class) + .apply(CityEntity.findAllByTerm(em, config, context.getLanguage(), term), false)); + if (page.getTotal() < page.getOffset() + page.getElements().size()) { + page.setTotal(page.getOffset() + page.getElements().size()); + } + return page; + } + + /** + * Finds the states by a search term. + * + * @param config The page configuration. + * @param context The search context. + * @param term The search term. + * @return The page with the results. + */ + @PermitAll + public StateDigestPage findStates(PageConfig config, SearchContext context, String term) { + StateDigestPage page = new StateDigestPage(); + page.setOffset(config.getOffset()); + page.setSize(config.getSize()); + page.setTotal(StateEntity.countAllByTerm(em, context.getLanguage(), term)); + page.setElements(Convert.with(StateDigestConverter.class) + .apply(StateEntity.findAllByTerm(em, config, context.getLanguage(), term), false)); + if (page.getTotal() < page.getOffset() + page.getElements().size()) { + page.setTotal(page.getOffset() + page.getElements().size()); + } + return page; + } + + /** + * Returns the city with the specified id. + * + * @param id The id of the city. + * @param filtered True to filter deleted. + * @return The city with the id. + * @throws EntityNotFoundException Thrown if the city does not exist. + */ + @PermitAll + public City getCity(long id, boolean filtered) throws EntityNotFoundException { + CityEntity city = em.find(CityEntity.class, new Long(id)); + if (city == null || (filtered && city.isDeleted())) + throw new EntityNotFoundException(CityEntity.class, id, "City not found."); + return Convert.with(CityConverter.class).apply(city, filtered); + } + + /** + * Returns the state with the specified id. + * + * @param id The id of the state. + * @param filtered True to filter deleted. + * @return The state with the id. + * @throws EntityNotFoundException Thrown if the state does not exist. + */ + @PermitAll + public State getState(long id, boolean filtered) throws EntityNotFoundException { + StateEntity state = em.find(StateEntity.class, new Long(id)); + if (state == null || (filtered && state.isDeleted())) + throw new EntityNotFoundException(StateEntity.class, id, "State not found."); + return Convert.with(StateConverter.class).apply(state, filtered); + } + + /** + * Returns the modification date of the city, thereby considering the country + * and state as well. + * + * @param id The id of the city. + * @return The maximum time stamp of the city, state and country referenced by + * the city or 0, if the city does not exist. + */ + @PermitAll + public long getLastModifiedCity(long id) { + long result = 0; + CityEntity city = em.find(CityEntity.class, new Long(id)); + if (city == null) + return result; + if (city.getState() != null) + result = city.getState().getModificationTime(); + result = Math.max(result, city.getCountry().getModificationTime()); + result = Math.max(result, city.getModificationTime()); + return result; + } + + /** + * Returns the modification date of the state, thereby considering the country + * as well. + * + * @param id The id of the state. + * @return The maximum time stamp of the state and country referenced by the + * state or 0, if the state does not exist. + */ + @PermitAll + public long getLastModifiedState(long id) { + long result = 0; + StateEntity state = em.find(StateEntity.class, new Long(id)); + if (state == null) + return result; + if (state.getCountry() != null) + result = state.getCountry().getModificationTime(); + result = Math.max(result, state.getModificationTime()); + return result; + } + + /** + * Returns the maximum last modification time stamp over all location tables. + * + * @return The maximum modification. + */ + @PermitAll + public long getLastModifiedLocation() { + long result = 0; + @SuppressWarnings("unchecked") + Class[] types = new Class[] { CityEntity.class, CountryEntity.class, StateEntity.class }; + for (Class type : types) { + result = Math.max(result, AbstractEntity.getLastModified(em, type)); + } + return result; + } + + /** + * Returns the boundary of the city with the specified id or null, if the city + * does not have a boundary. + * + * @param id The id. + * @return The city boundary as a geojson string. + * @throws EntityNotFoundException Thrown if the city cannot be found. + */ + @PermitAll + public String getCityBoundary(long id) throws EntityNotFoundException { + CityEntity city = em.find(CityEntity.class, new Long(id)); + if (city == null) + throw new EntityNotFoundException(CityEntity.class, id, "City not found."); + return city.getBoundary(); + } + + /** + * Returns the boundary of the state with the specified id or null, if the state + * does not have a boundary. + * + * @param id The id. + * @return The state boundary as a geojson string. + * @throws EntityNotFoundException Thrown if the state cannot be found. + */ + @PermitAll + public String getStateBoundary(long id) throws EntityNotFoundException { + StateEntity state = em.find(StateEntity.class, new Long(id)); + if (state == null) + throw new EntityNotFoundException(StateEntity.class, id, "State not found."); + return state.getBoundary(); + } + + /** + * Returns all cities via pagination. + * + * @param config The page config. + * @param filtered True to filter deleted, false otherwise. + * @return The page according to the config. + */ + @PermitAll + public CityPage getAllCities(PageConfig config, boolean filtered) { + return getAll(CityEntity.class, config, new OrderCriterion("id"), filtered, new CityPage(), + CityConverter.class); + } + + /** + * Returns all states via pagination. + * + * @param config The page config. + * @param filtered True to filter deleted, false otherwise. + * @return The page according to the config. + */ + @PermitAll + public StatePage getAllStates(PageConfig config, boolean filtered) { + return getAll(StateEntity.class, config, new OrderCriterion("id"), filtered, new StatePage(), + StateConverter.class); + } } diff --git a/service-ejb/src/main/java/com/mowesta/service/session/SyncSessionBean.java b/service-ejb/src/main/java/com/mowesta/service/session/SyncSessionBean.java index 0ef70dfe..e74b1aab 100644 --- a/service-ejb/src/main/java/com/mowesta/service/session/SyncSessionBean.java +++ b/service-ejb/src/main/java/com/mowesta/service/session/SyncSessionBean.java @@ -66,11 +66,15 @@ public class SyncSessionBean extends AbstractSessionBean { e = new StateEntity(); updateLocation(state, e); e.setCountry(country); + e.setPopulation(state.getPopulation()); + e.setTimezone(state.getTimezone()); em.persist(e); } else { log.log(Level.INFO, "State " + getName(state) + " exist, updating."); updateLocation(state, e); e.setCountry(country); + e.setPopulation(state.getPopulation()); + e.setTimezone(state.getTimezone()); } } } diff --git a/service-ejb/src/test/java/com/mowesta/service/test/session/LocationSessionTest.java b/service-ejb/src/test/java/com/mowesta/service/test/session/LocationSessionTest.java index cc0ef834..57b6a0f4 100644 --- a/service-ejb/src/test/java/com/mowesta/service/test/session/LocationSessionTest.java +++ b/service-ejb/src/test/java/com/mowesta/service/test/session/LocationSessionTest.java @@ -4,6 +4,7 @@ import javax.ejb.EJB; import javax.inject.Inject; import javax.persistence.EntityManager; +import com.mowesta.api.location.StateDigestPage; import org.hibernate.search.jpa.Search; import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; @@ -20,93 +21,145 @@ import com.mowesta.service.session.LocationSessionBean; /** * Tests running against the location session. * - * @author Marcus + * @author Marcus, Sebastian */ @RunWith(Arquillian.class) public class LocationSessionTest extends AbstractSessionTest { - /** - * The location session to perform tests. - */ - @EJB - LocationSessionBean locationSession; - - /** - * The entity manager to reindex the data. - */ - @Inject - EntityManager em; - - /** - * A flag to avoid reindexing for all test cases. - */ - boolean indexed; - - /** - * Forces a complete rebuild of the search index unless - * the search index has been reindexed already. - * - * @throws Exception Thrown if a failure occurs. - */ - @Before - public void rebuildIndex() throws Exception { - if (!indexed) { - Search.getFullTextEntityManager(em).createIndexer().startAndWait(); - indexed = true; - } - } - - /** - * Checks that the search for the term has results. - * - * @param results The number of results expected. - * @param language The language. - * @param term The term. - * @return The result page. - */ - private CityDigestPage assertSearch(int results, Language language, String term) { - CityDigestPage page = locationSession.findCities(new PageConfig(0, 20), new SearchContext(language), term); - Assert.assertEquals("Should have matchin number of results." , results, page.getTotal()); - return page; - } + /** + * The location session to perform tests. + */ + @EJB + LocationSessionBean locationSession; - /** - * Test that we can find the cities by name. - */ - @Test - public void testSearchByName() { - assertSearch(2, Language.GERMAN, "Stuttgart"); - assertSearch(2, Language.ENGLISH, "Essen"); - assertSearch(1, Language.GERMAN, "Troisdorf"); - assertSearch(1, Language.GERMAN, "Bonn"); - } - - /** - * Tests that we can find prefixes. - */ - @Test - public void testSearchByPrefix() { - assertSearch(2, Language.GERMAN, "Stutt"); - assertSearch(2, Language.ENGLISH, "Esse"); - } + /** + * The entity manager to reindex the data. + */ + @Inject + EntityManager em; + + /** + * A flag to avoid reindexing for all test cases. + */ + boolean indexed; + + /** + * Forces a complete rebuild of the search index unless the search index has + * been reindexed already. + * + * @throws Exception Thrown if a failure occurs. + */ + @Before + public void rebuildIndex() throws Exception { + if (!indexed) { + Search.getFullTextEntityManager(em).createIndexer().startAndWait(); + indexed = true; + } + } + + /** + * Test that we can find the cities by name. + */ + @Test + public void testSearchCitiesByName() { + assertCitySearch(2, Language.GERMAN, "Stuttgart"); + assertCitySearch(2, Language.ENGLISH, "Essen"); + assertCitySearch(1, Language.GERMAN, "Troisdorf"); + assertCitySearch(1, Language.GERMAN, "Bonn"); + } + + /** + * Tests that we can find prefixes. + */ + @Test + public void testSearchCitiesByPrefix() { + assertCitySearch(2, Language.GERMAN, "Stutt"); + assertCitySearch(2, Language.ENGLISH, "Esse"); + } + + /** + * Tests that we can find different cases. + */ + @Test + public void testSearchCitiesByWrongCase() { + assertCitySearch(2, Language.GERMAN, "sTuTTgar"); + } + + /** + * Tests that we can find different German spellings. + */ + @Test + public void testSearchCitiesByVariants() { + assertCitySearch(1, Language.GERMAN, "Nürtingen"); + assertCitySearch(1, Language.GERMAN, "Nurtingen"); + assertCitySearch(1, Language.GERMAN, "Nuertingen"); + } + + /** + * Test that we can find the states by name. + */ + @Test + public void testSearchStatesByName() { + assertStateSearch(1, Language.GERMAN, "Nordrhein-Westfalen"); + assertStateSearch(1, Language.ENGLISH, "North Rhine-Westphalia"); + assertStateSearch(0, Language.GERMAN, "Troisdorf"); + assertStateSearch(1, Language.GERMAN, "Berlin"); + assertStateSearch(1, Language.GERMAN, "Baden-Württemberg"); + } + + /** + * Tests that we can find prefixes. + */ + @Test + public void testSearchStatesByPrefix() { + assertStateSearch(1, Language.GERMAN, "Berl"); + assertStateSearch(1, Language.ENGLISH, "Baden"); + } + + /** + * Tests that we can find different cases. + */ + @Test + public void testSearchStatesByWrongCase() { + assertStateSearch(1, Language.GERMAN, "bADen-W"); + } + + /** + * Tests that we can find different German spellings. + */ + @Test + public void testSearchStatesByVariants() { + assertStateSearch(1, Language.GERMAN, "Baden-Württemberg"); + assertStateSearch(1, Language.GERMAN, "Baden-Wurttemberg"); + assertStateSearch(1, Language.GERMAN, "Baden-Wuerttemberg"); + } + + /** + * Checks that the search for the term has results. + * + * @param results The number of results expected. + * @param language The language. + * @param term The term. + * @return The result page. + */ + private CityDigestPage assertCitySearch(int results, Language language, String term) { + CityDigestPage page = locationSession.findCities(new PageConfig(0, 20), new SearchContext(language), term); + Assert.assertEquals("Should have matching number of results.", results, page.getTotal()); + return page; + } + + /** + * Checks that the search for the term has results. + * + * @param results The number of results expected. + * @param language The language. + * @param term The term. + * @return The result page. + */ + private StateDigestPage assertStateSearch(int results, Language language, String term) { + StateDigestPage page = locationSession.findStates(new PageConfig(0, 20), new SearchContext(language), term); + Assert.assertEquals("Should have matching number of results.", results, page.getTotal()); + return page; + } - /** - * Tests that we can find different cases. - */ - @Test - public void testSearchByWrongCase() { - assertSearch(2, Language.GERMAN, "sTuTTgar"); - } - - /** - * Tests that we can find different German spellings. - */ - @Test - public void testSearchByVariants() { - assertSearch(1, Language.GERMAN, "Nürtingen"); - assertSearch(1, Language.GERMAN, "Nurtingen"); - assertSearch(1, Language.GERMAN, "Nuertingen"); - } - - } diff --git a/service-ejb/src/test/resources/META-INF/persistence.xml b/service-ejb/src/test/resources/META-INF/persistence.xml index 8f66b681..ed5854c8 100644 --- a/service-ejb/src/test/resources/META-INF/persistence.xml +++ b/service-ejb/src/test/resources/META-INF/persistence.xml @@ -8,6 +8,8 @@ + + \ No newline at end of file diff --git a/service-ejb/src/test/resources/arquillian.xml b/service-ejb/src/test/resources/arquillian.xml index 40bdc127..9be84a5a 100644 --- a/service-ejb/src/test/resources/arquillian.xml +++ b/service-ejb/src/test/resources/arquillian.xml @@ -15,6 +15,7 @@ 10990 + -Djboss.socket.binding.port-offset=1000 diff --git a/service-ejb/src/test/resources/nominatim/cities.json.bz2 b/service-ejb/src/test/resources/nominatim/cities.json.bz2 index 17256fc2..f5d45656 100644 Binary files a/service-ejb/src/test/resources/nominatim/cities.json.bz2 and b/service-ejb/src/test/resources/nominatim/cities.json.bz2 differ diff --git a/service-ejb/src/test/resources/nominatim/countries.json.bz2 b/service-ejb/src/test/resources/nominatim/countries.json.bz2 index 96f70dbb..4e6ac920 100644 Binary files a/service-ejb/src/test/resources/nominatim/countries.json.bz2 and b/service-ejb/src/test/resources/nominatim/countries.json.bz2 differ diff --git a/service-ejb/src/test/resources/nominatim/states.json.bz2 b/service-ejb/src/test/resources/nominatim/states.json.bz2 index d7dfa79e..86e44a78 100644 Binary files a/service-ejb/src/test/resources/nominatim/states.json.bz2 and b/service-ejb/src/test/resources/nominatim/states.json.bz2 differ diff --git a/service-tool/src/main/java/com/mowesta/tool/nominatim/NominatimExporter.java b/service-tool/src/main/java/com/mowesta/tool/nominatim/NominatimExporter.java index 49e7ae9d..87059161 100644 --- a/service-tool/src/main/java/com/mowesta/tool/nominatim/NominatimExporter.java +++ b/service-tool/src/main/java/com/mowesta/tool/nominatim/NominatimExporter.java @@ -93,6 +93,11 @@ public class NominatimExporter { */ public static final String FILE_CITIES = "cities.json"; + /** + * Timezone Engine for determine timezone at specific coordinate + */ + private static final TimeZoneEngine timezoneEngine = TimeZoneEngine.initialize(); + /** * These are the name tags that we extract, we throw away the * others to reduce the file size. @@ -103,7 +108,9 @@ public class NominatimExporter { "name:en", // English translation "name:es", // Spanish translation "name:fr", // French translation - "name:it" // Italian translation + "name:it", // Italian translation + "short_name", // ShortName + "ref" }; @@ -159,7 +166,6 @@ public class NominatimExporter { private static int loadCities(EntityManager em, Map countries, Map states, File file) throws Exception { int counter = 0; Map entityCache = new HashMap<>(); - TimeZoneEngine timezoneEngine = TimeZoneEngine.initialize(); ObjectMapper objectMapper = new ObjectMapper(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); // create a scrollable query (not supported by JPA's api, so let's use hibernate's internals) @@ -221,18 +227,14 @@ public class NominatimExporter { } } } - // determine the timezone - LngLatAlt centroid = city.getCentroid().getCoordinates(); - List zones = timezoneEngine.queryAll(centroid.getLatitude(), centroid.getLongitude()); - if (zones.size() == 0) { - logger.log(Level.SEVERE, "Unable to find timezone for city: " + centroid + ". Skipping."); + + String timezone = getTimezoneByCoordinate(city.getCentroid()); + if (timezone == null) { + logger.log(Level.SEVERE, "Unable to find timezone for city: " + city.getCentroid() + ". Skipping."); continue; - } else { - if (zones.size() > 1) { - logger.log(Level.WARNING, "Multiple timezones for city: " + centroid + ". Using first."); - } - city.setTimezone(zones.get(0).getId()); - } + } + city.setTimezone(timezone); + writer.write(objectMapper.writeValueAsString(city)); writer.write("\n"); counter += 1; @@ -336,6 +338,20 @@ public class NominatimExporter { return null; } + + private static String getTimezoneByCoordinate(Point coordinate) { + LngLatAlt centroid = coordinate.getCoordinates(); + List zones = timezoneEngine.queryAll(centroid.getLatitude(), centroid.getLongitude()); + if (zones.size() == 0) { + return null; + } else { + if (zones.size() > 1) { + logger.log(Level.WARNING, "Multiple timezones for city: " + centroid + ". Using first."); + } + return zones.get(0).getId(); + } + } + /** * Determines whether the object represents an administrative boundary that * could be the city boundary. @@ -409,12 +425,24 @@ public class NominatimExporter { state.setImportance(place.getImportance()); state.setAddressRank(place.getAddressRank()); state.setSearchRank(place.getSearchRank()); + state.setPopulation(getPopulation(place)); state.setWikipedia(place.getWikipedia()); + + state.setBoundary(toGeometry(place.getGeometry())); if (place.getCentroid() != null) state.setCentroid(toPoint(place.getCentroid())); else state.setCentroid(toPoint(place.getGeometry())); + + String timezone = getTimezoneByCoordinate(state.getCentroid()); + if (timezone == null) { + logger.log(Level.SEVERE, "Unable to find timezone for state: " + state.getCentroid() + ". Skipping."); + continue; + } + state.setTimezone(timezone); + + state.setId(place.getPlaceId()); state.setCountry(country.getId()); state.setNames(getFilteredNames(place.getNames())); diff --git a/service-war/src/main/java/com/mowesta/service/rest/LocationResource.java b/service-war/src/main/java/com/mowesta/service/rest/LocationResource.java index b97d9425..57e5f1fe 100644 --- a/service-war/src/main/java/com/mowesta/service/rest/LocationResource.java +++ b/service-war/src/main/java/com/mowesta/service/rest/LocationResource.java @@ -107,26 +107,55 @@ public class LocationResource implements ILocationService { @Override public Response searchStates(PageConfig pageConfig, SearchContext context, String term) { - // TODO Implement me! - return Response.status(Status.NOT_IMPLEMENTED).build(); + EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedLocation())); + // TODO: think about caching when index is created asynchronously + ResponseBuilder b = request.evaluatePreconditions(tag); + if (b == null) { + b = Response.ok(locationSession.findStates(pageConfig, context, term)); + } + return b.tag(tag).build(); } @Override public Response getStates(PageConfig pageConfig) { - // TODO Implement me! - return Response.status(Status.NOT_IMPLEMENTED).build(); + EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedLocation())); + ResponseBuilder b = request.evaluatePreconditions(tag); + if (b == null) { + b = Response.ok(locationSession.getAllStates(pageConfig, true)); + } + return b.tag(tag).build(); } @Override public Response getState(long id) { - // TODO Implement me! - return Response.status(Status.NOT_IMPLEMENTED).build(); + EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedState(id))); + ResponseBuilder b = request.evaluatePreconditions(tag); + if (b == null) { + try { + b = Response.ok(locationSession.getState(id, false)); + } catch (EntityNotFoundException e) { + b = Response.status(Status.NOT_FOUND); + } + } + return b.tag(tag).build(); } @Override public Response getStateBoundary(long id) { - // TODO Implement me! - return Response.status(Status.NOT_IMPLEMENTED).build(); + EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedState(id))); + ResponseBuilder b = request.evaluatePreconditions(tag); + if (b == null) { + try { + String boundary = locationSession.getStateBoundary(id); + if (boundary == null) + b = Response.noContent(); + else + b = Response.ok(boundary); + } catch (EntityNotFoundException e) { + b = Response.status(Status.NOT_FOUND); + } + } + return b.tag(tag).build(); } diff --git a/service-war/src/main/java/com/mowesta/service/rest/ServerDebugFilter.java b/service-war/src/main/java/com/mowesta/service/rest/ServerDebugFilter.java index 6d100346..037598b5 100644 --- a/service-war/src/main/java/com/mowesta/service/rest/ServerDebugFilter.java +++ b/service-war/src/main/java/com/mowesta/service/rest/ServerDebugFilter.java @@ -5,7 +5,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.logging.Level; diff --git a/service-war/src/test/java/com/mowesta/service/test/rest/LocationResourceTest.java b/service-war/src/test/java/com/mowesta/service/test/rest/LocationResourceTest.java index 5c4c97ad..fe3c5871 100644 --- a/service-war/src/test/java/com/mowesta/service/test/rest/LocationResourceTest.java +++ b/service-war/src/test/java/com/mowesta/service/test/rest/LocationResourceTest.java @@ -21,6 +21,10 @@ import com.mowesta.api.location.CityDigestPage; import com.mowesta.api.location.CityPage; import com.mowesta.api.location.ILocationService; import com.mowesta.api.location.SearchContext; +import com.mowesta.api.location.State; +import com.mowesta.api.location.StateDigest; +import com.mowesta.api.location.StateDigestPage; +import com.mowesta.api.location.StatePage; /** * Tests against the location resource. @@ -59,6 +63,18 @@ public class LocationResourceTest extends AbstractResourceTest { checkGetCityAndBoundary(digest.getId()); } } + + @Test + public void testStateSearch() throws Exception { + Response r = locationService.searchStates(new PageConfig(0, 10), new SearchContext(Language.GERMAN), "Nordrhein-Westfalen"); + AssertResponse.isStatus(r, Status.OK); + StateDigestPage page = AssertResponse.hasBody(r, StateDigestPage.class); + Assert.assertTrue("Search for Nordrhein-Westfalen should have results.", page.getTotal() > 0 && page.getElements().size() > 0); + for (int i = 0; i < page.getElements().size(); i++) { + StateDigest digest = page.getElements().get(i); + checkGetStateAndBoundary(digest.getId()); + } + } /** * Test case that retrieves a page and checks the result. @@ -76,6 +92,22 @@ public class LocationResourceTest extends AbstractResourceTest { } } + /** + * Test case that retrieves a page and checks the result. + * + * @throws Exception Thrown if something fails. + */ + @Test + public void testStatePaging() throws Exception { + Response r = locationService.getStates(new PageConfig(0, 5)); + AssertResponse.isStatus(r, Status.OK); + StatePage page = AssertResponse.hasBody(r, StatePage.class); + Assert.assertTrue("Page should be full.", page.getElements().size() == page.getSize()); + for (State s: page.getElements()) { + checkGetStateAndBoundary(s.getId()); + } + } + /** * Checks that the city and its bounds can be fetched. @@ -98,5 +130,26 @@ public class LocationResourceTest extends AbstractResourceTest { } } + /** + * Checks that the state and its bounds can be fetched. + * + * @param id The id of the state. + * @throws Exception Thrown if something fails. + */ + public void checkGetStateAndBoundary(long id) throws Exception { + Response c = locationService.getState(id); + AssertResponse.isStatus(c, Status.OK); + AssertResponse.hasBody(c, State.class); + Response b = locationService.getStateBoundary(id); + if (b.getStatusInfo() == Status.OK) { + String body = b.readEntity(String.class); + ObjectMapper mapper = new ObjectMapper();; + Geometry geometry = mapper.readValue(body, Geometry.class); + Assert.assertTrue("Geometry must be polygon or multipolygon.", (geometry instanceof Polygon) || (geometry instanceof MultiPolygon)); + } else { + Assert.assertTrue("REsult must be no-content.", b.getStatusInfo() == Status.NO_CONTENT); + } + } + } diff --git a/service-war/src/test/resources/META-INF/persistence.xml b/service-war/src/test/resources/META-INF/persistence.xml index 8f66b681..ed5854c8 100644 --- a/service-war/src/test/resources/META-INF/persistence.xml +++ b/service-war/src/test/resources/META-INF/persistence.xml @@ -8,6 +8,8 @@ + + \ No newline at end of file diff --git a/service-war/src/test/resources/arquillian.xml b/service-war/src/test/resources/arquillian.xml index fc40014c..cdeef657 100644 --- a/service-war/src/test/resources/arquillian.xml +++ b/service-war/src/test/resources/arquillian.xml @@ -15,6 +15,7 @@ 10990 + -Djboss.socket.binding.port-offset=1000 ../service-wildfly/wildfly-17.0.1.Final