12 Commits
Author SHA1 Message Date
handte 36b5fc7957 Release 1.0.14.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 23:37:49 +01:00
handte 8aa383a002 Prevent ejb and war tests to run in parallel.
LocationBasedServices/mowesta/pipeline/head This commit looks good
Add locking to ensure that ejb and war tests are serialized.
Revert changes to arquillian ports since they are useless.
2021-02-14 23:24:56 +01:00
handte 1d3c8335c7 Reduce build duration by running tasks in parallel.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
Allow gradle to execute build tasks in parallel.
Change ejb test ports to enable simultaneous execution with war tests.
2021-02-14 21:59:16 +01:00
handte aeee482128 Fix angular elements component styles.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 21:18:26 +01:00
handte 6bf3663c81 Add missing cors rules for resources.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 20:52:03 +01:00
handte 48519aefa5 Properly handle bitmaps during import.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 20:24:47 +01:00
handte 0d05a03f6e Update to 1.0.14-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 18:53:33 +01:00
handte 4bff009cfc Release 1.0.13.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 18:50:58 +01:00
handte ba1b5ab29a Fix path names in route servlet.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 18:07:36 +01:00
handte 8bfce31f2e Properly compute regular grid coordinates.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 17:48:10 +01:00
handte bca818e734 Replace COSMO D2 nwp with ICON D2 nwp.
LocationBasedServices/mowesta/pipeline/head This commit looks good
Remove cosmo d2 since it is no longer computed by DWD.
Add new icon d2 as drop-in replacement for cosmo.
Extend grip decoder to properly handle bitmap section.
Switch icon eu to use icosahedral coordinate system.
Rename inconsistent state boundary endpoint.
2021-02-14 17:23:32 +01:00
handte c95015c234 Update to 1.0.13-SNAPSHOT.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 00:14:25 +01:00
17 changed files with 791 additions and 423 deletions
+1 -1
View File
@@ -89,7 +89,7 @@ android {
applicationId "com.mowesta.android.app"
minSdkVersion 19
targetSdkVersion 29
versionCode 12
versionCode 14
versionName "${version}"
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+35 -1
View File
@@ -1,3 +1,6 @@
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
apply plugin: 'maven-publish'
buildscript {
@@ -21,7 +24,7 @@ allprojects {
// set version for our project
group = 'com.mowesta'
version = '1.0.12'
version = '1.0.14'
// set versions for our libraries
ext {
@@ -145,3 +148,34 @@ subprojects {
tasks.register("generatePomFileForMavenPublication") { }
tasks.register("build") { }
// aquire locks to ensure that service-ejb and service-war are not running tests in parallel
def lock = new ReentrantLock()
def available = lock.newCondition()
def busy = new AtomicBoolean()
def serializedTasks = []
def sequentialProjects = [ 'service-ejb', 'service-war' ]
gradle.taskGraph.beforeTask {
if (it.name == 'test' && it.project.name in sequentialProjects) {
serializedTasks << it
it.doFirst {
lock.lock()
while (busy.get()) {
available.await()
}
busy.set(true)
lock.unlock()
}
}
}
gradle.taskGraph.afterTask {
if (it in serializedTasks) {
lock.lock()
busy.set(false)
available.signal()
lock.unlock()
}
}
@@ -29,7 +29,7 @@ import io.swagger.annotations.ApiResponses;
/**
* The api to query and fetch locations.
*
*
* @author Marcus
*/
@Api
@@ -40,7 +40,7 @@ public interface ILocationService {
/**
* Returns a page of locations that match the query.
*
*
* @param pageConfig The page configuration.
* @param context The search context.
* @param term The search term.
@@ -53,16 +53,16 @@ public interface ILocationService {
@ApiResponses({
@ApiResponse(code=HttpServletResponse.SC_OK, message="Location hierarchy page retrieved successfully.", response=LocationHierarchyPage.class),
@ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.")
})
})
@PermitAll
Response searchLocations(@BeanParam @Valid PageConfig pageConfig, @BeanParam @Valid SearchContext context,
@ApiParam(value="The search term.", required=true) @QueryParam("term") @NotNull @Valid String term);
/**
* Returns a page of cities that are inside a particular area defined by two coordinates.
*
*
* @param pageConfig The page configuration.
* @param longitude1 The longitude of the first coordinate.
* @param latitude1 The latitude of the first coordinate.
@@ -76,18 +76,18 @@ public interface ILocationService {
@ApiResponses({
@ApiResponse(code=HttpServletResponse.SC_OK, message="The pages.", response=CityPage.class),
@ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.")
})
})
@PermitAll
Response searchCities(@BeanParam @Valid PageConfig pageConfig,
@ApiParam(value = "The longitude of the first coordinate.", required = true) @QueryParam("longitude1") double longitude1,
Response searchCities(@BeanParam @Valid PageConfig pageConfig,
@ApiParam(value = "The longitude of the first coordinate.", required = true) @QueryParam("longitude1") double longitude1,
@ApiParam(value = "The latitude of the first coordinate.", required = true) @QueryParam("latitude1") double latitude1,
@ApiParam(value = "The longitude of the second coordinate.", required = true) @QueryParam("longitude2") double longitude2,
@ApiParam(value = "The longitude of the second coordinate.", required = true) @QueryParam("longitude2") double longitude2,
@ApiParam(value = "The latitude of the second coordinate.", required = true) @QueryParam("latitude2") double latitude2);
/**
* Returns a page of cities.
*
*
* @param pageConfig The page configuration.
* @return A page of cities.
*/
@@ -97,10 +97,10 @@ public interface ILocationService {
@ApiResponses({
@ApiResponse(code=HttpServletResponse.SC_OK, message="City page retrieved successfully.", response=CityPage.class),
@ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.")
})
})
@PermitAll
Response getCities(@BeanParam @Valid PageConfig pageConfig);
/**
* Returns a particular city.
*
@@ -119,8 +119,8 @@ public interface ILocationService {
/**
* Returns a geojson representation of the city boundaries.
*
* @param id The id of the city.
*
* @param id The id of the city.
* @return The boundaries of geojson or an error code.
*/
@GET
@@ -134,8 +134,8 @@ public interface ILocationService {
@PermitAll
@Produces({MediaType.APPLICATION_JSON})
Response getCityBoundary(@ApiParam(value = "The city id.", required = true) @PathParam("id") @Valid @Min(0) long id);
/**
* Returns a page of states.
*
@@ -151,7 +151,7 @@ public interface ILocationService {
})
@PermitAll
Response getStates(@BeanParam @Valid PageConfig pageConfig);
/**
* Returns a particular state.
*
@@ -167,15 +167,15 @@ public interface ILocationService {
})
@PermitAll
Response getState(@ApiParam(value = "The state id.", required = true) @PathParam("id") @Valid @Min(0) long id);
/**
* Returns a geojson representation of the state boundaries.
*
* @param id The id of the state.
* @return The boundaries of geojson or an error code.
* @return The boundaries as geojson or an error code.
*/
@GET
@Path("state/{id: [0-9]+}/boundary")
@Path("states/{id: [0-9]+}/boundary")
@ApiOperation(value = "Gets the state boundary for a state with a particular id.", tags = {Tags.DEFAULT, Tags.LOCATION})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "State boundary retrieved successfully.", response=Geometry.class),
@@ -185,7 +185,28 @@ public interface ILocationService {
@PermitAll
@Produces({MediaType.APPLICATION_JSON})
Response getStateBoundary(@ApiParam(value = "The state id.", required = true) @PathParam("id") @Valid @Min(0) long id);
/**
* The deprecated version of the method that has a typo in the path name (state instead of states).
* To be removed, if Android Apps < V14 are no longer present.
*
* @param id The id of the state.
* @return The boundaries as geojson or an error code.
*/
@GET
@Path("state/{id: [0-9]+}/boundary")
@ApiOperation(value = "Deprecated: Gets the state boundary for a state with a particular id.", tags = {Tags.DEFAULT, Tags.LOCATION})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "State boundary retrieved successfully.", response=Geometry.class),
@ApiResponse(code = HttpServletResponse.SC_NO_CONTENT, message = "The state boundary are not available."),
@ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The state does not exist."),
})
@PermitAll
@Produces({MediaType.APPLICATION_JSON})
@Deprecated
Response getStateBoundaryDeprecated(@ApiParam(value = "The state id.", required = true) @PathParam("id") @Valid @Min(0) long id);
/**
* Returns a page of cities for a state ordered by importance.
*
@@ -202,10 +223,10 @@ public interface ILocationService {
})
@PermitAll
Response getStateCities(@ApiParam(value = "The state id.", required = true) @PathParam("id") @Valid @Min(0) long id, @BeanParam @Valid PageConfig pageConfig);
/**
* Returns a page of countries.
*
*
* @param pageConfig The page configuration.
* @return A page of countries.
*/
@@ -215,10 +236,10 @@ public interface ILocationService {
@ApiResponses({
@ApiResponse(code=HttpServletResponse.SC_OK, message="Country page retrieved successfully.", response=CountryPage.class),
@ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.")
})
})
@PermitAll
Response getCountries(@BeanParam @Valid PageConfig pageConfig);
/**
* Returns a particular country.
*
@@ -237,8 +258,8 @@ public interface ILocationService {
/**
* Returns a geojson representation of the country boundaries.
*
* @param id The id of the country.
*
* @param id The id of the country.
* @return The boundaries of geojson or an error code.
*/
@GET
@@ -252,7 +273,7 @@ public interface ILocationService {
@PermitAll
@Produces({MediaType.APPLICATION_JSON})
Response getCountryBoundary(@ApiParam(value = "The country id.", required = true) @PathParam("id") @Valid @Min(0) long id);
/**
* Returns a page of cities for a country ordered by importance.
*
@@ -270,5 +291,5 @@ public interface ILocationService {
@PermitAll
Response getCountryCities(@ApiParam(value = "The country id.", required = true) @PathParam("id") @Valid @Min(0) long id, @BeanParam @Valid PageConfig pageConfig);
}
+2 -1
View File
@@ -1,3 +1,4 @@
android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx4g
org.gradle.jvmargs=-Xmx4g
org.gradle.parallel=true
@@ -20,6 +20,7 @@ import com.mowesta.data.ftp.FileStatusListener;
import com.mowesta.data.ftp.FtpFolderSync;
import com.mowesta.data.grib2.Grib2Data;
import com.mowesta.data.grib2.Grib2File;
import com.mowesta.data.grib2.decoder.BitmapInterpreter;
import com.mowesta.data.grib2.decoder.RegularGridDecoder;
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
@@ -31,16 +32,15 @@ import com.mowesta.data.process.util.FileNameComparator;
* Represents a numeric weather prediction from DWD.
*/
public class NumericPrediction {
/**
* The extension of the data files.
*/
private static final String GRIB_EXTENSION = "grib2.bz2";
/**
* A enum to describe the coordinate system used
* to represent locations.
*
* A enum to describe the coordinate system used to represent locations.
*
* @author Marcus
*
*/
@@ -57,55 +57,54 @@ public class NumericPrediction {
* A icosahedral system.
*/
ICOSAHEDRAL("icosahedral", false);
/**
* The string to filter files.
*/
private final String filter;
/**
* A flag to indicate whether the values
* are computed from a grid definition.
* A flag to indicate whether the values are computed from a grid definition.
*/
private final boolean computed;
/**
* Creates a new coordinate system.
*
* @param filter The keyword to filter.
* @param computed A boolean to indicate whether the
* values are computed.
*
* @param filter
* The keyword to filter.
* @param computed
* A boolean to indicate whether the values are computed.
*/
private CoordinateSystem(String filter, boolean computed) {
this.filter = filter;
this.computed = computed;
}
/**
* Returns the keyword to filter files.
*
*
* @return The filter.
*/
public String getFilter() {
return filter;
}
/**
* Returns true if the values of the positions are
* computed from a grid definition. False if they shall
* be read from a file.
*
* Returns true if the values of the positions are computed from a grid
* definition. False if they shall be read from a file.
*
* @return True if the coordinates are computed, false otherwise.
*/
public boolean isComputed() {
return computed;
}
}
/**
* The predictions that we use to download data.
*
*
* @author Marcus
*/
public enum PredictionType {
@@ -116,12 +115,13 @@ public class NumericPrediction {
/**
* The european icon prediction.
*/
ICON_EUROPE("opendata.dwd.de", "weather/nwp/icon-eu/grib/00/", 0, CoordinateSystem.REGULAR, 93),
ICON_EUROPE("opendata.dwd.de", "weather/nwp/icon-eu/grib/00/", 0, CoordinateSystem.REGULAR, 93),
/**
* The cosmo d2 prediction (the 3 o'clock prediction has more data, but sizes vary across variables).
* The cosmo d2 prediction (the 3 o'clock prediction has more data, but sizes
* vary across variables).
*/
COSMO_EUROPE("opendata.dwd.de", "weather/nwp/cosmo-d2/grib/03/", 3, CoordinateSystem.ROTATED, 46);
COSMO_EUROPE("opendata.dwd.de", "weather/nwp/icon-d2/grib/03/", 3, CoordinateSystem.ICOSAHEDRAL, 46);
/**
* The number of files expected in variant data folders.
*/
@@ -138,19 +138,23 @@ public class NumericPrediction {
* The server name.
*/
private String server;
/**
* The hour when the prediction is generated.
*/
private int hour;
/**
* Creates a new prediction.
*
* @param server The server name.
* @param folder The remote folder.
* @param system The coordinate system used by the simulation.
* @param files The number of files in for time variant variables.
*
* @param server
* The server name.
* @param folder
* The remote folder.
* @param system
* The coordinate system used by the simulation.
* @param files
* The number of files in for time variant variables.
*/
private PredictionType(String server, String folder, int hour, CoordinateSystem system, int files) {
this.server = server;
@@ -159,58 +163,57 @@ public class NumericPrediction {
this.system = system;
this.files = files;
}
/**
* Returns the hour when the prediction is made.
*
*
* @return The hour.
*/
public int getHour() {
return hour;
}
/**
* The number of files for time variant variables.
*
*
* @return The number of files for time variant variables.
*/
public int getFiles() {
return files;
}
/**
* The folder on the server.
*
*
* @return The folder on the server.
*/
public String getFolder() {
return folder;
}
/**
* The name of the ftp server.
*
*
* @return The name of the ftp server.
*/
public String getServer() {
return server;
}
/**
* Returns the coordinate system used by the simulation.
*
*
* @return The coordinate system.
*/
public CoordinateSystem getSystem() {
return system;
}
}
/**
* An enumeration with the variables.
*
*
* @author Marcus
*/
public enum Variable {
@@ -274,65 +277,67 @@ public class NumericPrediction {
* The total precipitation (accumulated (!)).
*/
PREC("tot_prec", false),
/**
* The zonal wind. at 10m height.
*/
U10M("u_10m", false),
/**
* The meridional wind at 10m height.
*/
V10M("v_10m", false),
/**
* The weather interpretation type.
*/
WW("ww", false);
/**
* The name of the folder.
*/
private final String folder;
/**
* Determines whether the variable is time invariant.
*/
private final boolean invariant;
/**
* Creates a new variable.
*
* @param folder The folder name.
* @param invariant True if time invariant.
*
* @param folder
* The folder name.
* @param invariant
* True if time invariant.
*/
private Variable(String folder, boolean invariant) {
this.folder = folder;
this.invariant = invariant;
}
/**
* Returns the folder name.
*
*
* @return The folder name.
*/
public String getFolder() {
return folder;
}
/**
* Returns true if the variable is time invariant.
*
*
* @return True if time invariant, false otherwise.
*/
public boolean isInvariant() {
return invariant;
}
};
/**
* Utility class used to represent time stamps.
*
* Utility class used to represent time stamps.
*
* @author Marcus
*/
public static class Time implements Comparable<Time> {
@@ -348,28 +353,33 @@ public class NumericPrediction {
* The day of the month (1-31).
*/
public final int day;
/**
* Creates a new time instance with the specified
* year, month and day.
*
* @param year The year.
* @param month The month.
* @param day The day.
* Creates a new time instance with the specified year, month and day.
*
* @param year
* The year.
* @param month
* The month.
* @param day
* The day.
*/
public Time(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
/**
* Returns the value of the string.
*
* @param s The string.
*
* @param s
* The string.
* @return The time or null, if the string does not represent time.
*/
public static Time valueOf(String s) {
if (s == null || s.length() != 8) return null;
if (s == null || s.length() != 8)
return null;
try {
int year = Integer.parseInt(s.substring(0, 4));
int month = Integer.parseInt(s.substring(4, 6));
@@ -379,11 +389,12 @@ public class NumericPrediction {
return null;
}
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) return false;
Time o = (Time)obj;
if (obj == null || obj.getClass() != getClass())
return false;
Time o = (Time) obj;
return o.year == year && o.month == month && o.day == day;
}
@@ -391,7 +402,7 @@ public class NumericPrediction {
public int hashCode() {
return year << 16 | month << 8 | day;
}
@Override
public int compareTo(Time o) {
int c = Integer.compare(o.year, year);
@@ -403,24 +414,24 @@ public class NumericPrediction {
}
return c;
}
@Override
public String toString() {
return String.format("%04d%02d%02d", year, month, day);
}
}
/**
* The logger to generate debug output.
*/
protected Logger log = Logger.getLogger(getClass().getName());
/**
* The local folder that contains the data.
*/
protected File localFolder;
/**
* The variables that are synchronized.
*/
@@ -429,120 +440,147 @@ public class NumericPrediction {
* The prediction.
*/
protected PredictionType type;
/**
* Creates a numerical prediction from the specified prediction model.
*
* @param type The prediction model.
* @param localFolder The local folder.
*
* @param type
* The prediction model.
* @param localFolder
* The local folder.
*/
public NumericPrediction(PredictionType type, File localFolder) {
this.type = type;
this.localFolder = localFolder;
variables = new Variable[] {
type.getSystem().isComputed()?Variable.RLAT:Variable.CLAT,
type.getSystem().isComputed()?Variable.RLON:Variable.CLON,
Variable.HSURF, Variable.PLCOV, Variable.SOILTYP, Variable.PREC, Variable.T2M, Variable.CLCT, Variable.CLDEPTH,
Variable.PMSL, Variable.WW, Variable.U10M, Variable.V10M, Variable.RELHUM2M, Variable.HSNOW, Variable.PS
};
variables = new Variable[] { Variable.HSURF, Variable.PLCOV, Variable.SOILTYP, Variable.PREC, Variable.T2M,
Variable.CLCT, Variable.CLDEPTH, Variable.PMSL, Variable.WW, Variable.U10M, Variable.V10M,
Variable.RELHUM2M, Variable.HSNOW, Variable.PS,
type.getSystem().isComputed() ? Variable.RLAT : Variable.CLAT,
type.getSystem().isComputed() ? Variable.RLON : Variable.CLON };
}
/**
* Returns the prediction.
*
*
* @return The prediction.
*/
public PredictionType getType() {
return type;
}
/**
* Returns the local folder.
*
*
* @return The local folder.
*/
public File getLocalFolder() {
return localFolder;
}
/**
* Returns the variables.
*
*
* @return The variables.
*/
public Variable[] getVariables() {
return variables;
}
}
/**
* Returns the longitudes.
*
* @param time The time.
*
* @param time
* The time.
* @return The double array with the longitudes.
* @throws IOException Thrown if something fails.
* @throws IOException
* Thrown if something fails.
*/
public DoubleArray getLongitues(Time time) throws IOException {
if (type.getSystem().isComputed()) {
Grib2File file = new Grib2File(createStream(getFile(Variable.RLON, time)));
try {
switch (type.getSystem()) {
case REGULAR:
RegularGridDecoder regular = new RegularGridDecoder(file.nextData().getGridSection());
return regular.getLongitudes();
case ROTATED:
RotatedGridDecoder rotated = new RotatedGridDecoder(file.nextData().getGridSection());
return rotated.getLongitudes();
default:
throw new IOException("Failed to decode unknown computed coordinate system.");
}
} catch (Exception e) {
throw new IOException("Failed to read data.", e);
} finally {
file.close();
Grib2File filterFile = new Grib2File(createStream(getFile(Variable.HSURF, time)));
try {
Grib2Data data = filterFile.nextData();
BitmapInterpreter interpreter = new BitmapInterpreter(data.getBitmapSection(),
data.getGridSection().getPointCount());
DoubleArray result = null;
if (type.getSystem().isComputed()) {
Grib2File gridFile = new Grib2File(createStream(getFile(Variable.RLON, time)));
try {
switch (type.getSystem()) {
case REGULAR:
RegularGridDecoder regular = new RegularGridDecoder(gridFile.nextData().getGridSection());
result = regular.getLongitudes();
break;
case ROTATED:
RotatedGridDecoder rotated = new RotatedGridDecoder(gridFile.nextData().getGridSection());
result = rotated.getLongitudes();
break;
default:
throw new IOException("Failed to decode unknown computed coordinate system.");
}
} finally {
gridFile.close();
}
} else {
result = getValues(getFile(Variable.CLON, time));
}
} else {
return getValues(getFile(Variable.CLON, time));
return interpreter.filter(result);
} catch (Exception e) {
throw new IOException("Failed to read data.", e);
} finally {
filterFile.close();
}
}
/**
* Returns the latitudes.
*
* @param time The time.
*
* @param time
* The time.
* @return The double array with the latitudes.
* @throws IOException Thrown if something fails.
* @throws IOException
* Thrown if something fails.
*/
public DoubleArray getLatitudes(Time time) throws IOException {
if (type.getSystem().isComputed()) {
Grib2File file = new Grib2File(createStream(getFile(Variable.RLAT, time)));
try {
switch (type.getSystem()) {
case REGULAR:
RegularGridDecoder regular = new RegularGridDecoder(file.nextData().getGridSection());
return regular.getLatitudes();
case ROTATED:
RotatedGridDecoder rotated = new RotatedGridDecoder(file.nextData().getGridSection());
return rotated.getLatitudes();
default:
throw new IOException("Failed to decode unknown computed coordinate system.");
Grib2File filterFile = new Grib2File(createStream(getFile(Variable.HSURF, time)));
try {
Grib2Data data = filterFile.nextData();
BitmapInterpreter interpreter = new BitmapInterpreter(data.getBitmapSection(),
data.getGridSection().getPointCount());
DoubleArray result = null;
if (type.getSystem().isComputed()) {
Grib2File gridFile = new Grib2File(createStream(getFile(Variable.RLAT, time)));
try {
switch (type.getSystem()) {
case REGULAR:
RegularGridDecoder regular = new RegularGridDecoder(gridFile.nextData().getGridSection());
result = regular.getLatitudes();
break;
case ROTATED:
RotatedGridDecoder rotated = new RotatedGridDecoder(gridFile.nextData().getGridSection());
result = rotated.getLatitudes();
break;
default:
throw new IOException("Failed to decode unknown computed coordinate system.");
}
} finally {
gridFile.close();
}
} catch (Exception e) {
throw new IOException("Failed to read data.", e);
} finally {
file.close();
} else {
result = getValues(getFile(Variable.CLAT, time));
}
} else {
return getValues(getFile(Variable.CLAT, time));
return interpreter.filter(result);
} catch (Exception e) {
throw new IOException("Failed to read data.", e);
} finally {
filterFile.close();
}
}
/**
* Returns a list of files that is available locally for a particular
* variable.
*
* @param variable The variable.
* Returns a list of files that is available locally for a particular variable.
*
* @param variable
* The variable.
* @return The list of files.
*/
public List<File> getFiles(Variable variable) {
@@ -550,7 +588,7 @@ public class NumericPrediction {
File[] files = folder.listFiles();
List<File> result = new ArrayList<File>();
if (files != null) {
for (File f: files) {
for (File f : files) {
if (f.isFile() && f.getName().endsWith(GRIB_EXTENSION)) {
result.add(f);
}
@@ -559,71 +597,80 @@ public class NumericPrediction {
result.sort(new FileNameComparator());
return result;
}
/**
* Returns the files that are available for a particular variable
* at a particular time.
*
* @param variable The variable.
* @param time The time.
* Returns the files that are available for a particular variable at a
* particular time.
*
* @param variable
* The variable.
* @param time
* The time.
* @return The list of files.
*/
public List<File> getFiles(Variable variable, Time time) {
List<File> data = getFiles(variable);
List<File> result = new ArrayList<>();
for (File f: data) {
for (File f : data) {
if (f.getName().contains("_" + time)) {
result.add(f);
}
}
return result;
}
/**
* Returns the first file for the variable and time
* or null, if the file is not available.
*
* @param variable The variable.
* @param time The time
* Returns the first file for the variable and time or null, if the file is not
* available.
*
* @param variable
* The variable.
* @param time
* The time
* @return The first file or null, if there is no such file.
*/
public File getFile(Variable variable, Time time) {
List<File> data = getFiles(variable, time);
if (data.size() > 0) return data.get(0);
if (data.size() > 0)
return data.get(0);
return null;
}
/**
* Returns the file that represents the specified hour on
* the specified day or null, if the file does not exist.
*
* @param variable The variable.
* @param time The time.
* @param hour The hour to search.
* Returns the file that represents the specified hour on the specified day or
* null, if the file does not exist.
*
* @param variable
* The variable.
* @param time
* The time.
* @param hour
* The hour to search.
* @return The file or null.
*/
public File getFile(Variable variable, Time time, int hour) {
List<File> data = getFiles(variable, time);
String search = String.format("_%03d_", hour);
for (int i = 0; i < data.size(); i++) {
if (data.get(i).getName().contains(search)) return data.get(i);
if (data.get(i).getName().contains(search))
return data.get(i);
}
return null;
}
/**
* Determines whether the data for a particular time is completely
* available.
*
* @param time The time stamp.
* Determines whether the data for a particular time is completely available.
*
* @param time
* The time stamp.
* @return True if all expected files are available. False otherwise.
*/
public boolean isAvailable(Time time) {
boolean success = true;
for (Variable v: variables) {
for (Variable v : variables) {
int count = getFiles(v, time).size();
int expected = v.isInvariant()?1:(type.getFiles() - 1); // we exclude hour 0 since it is not available for cosmo ww
int expected = v.isInvariant() ? 1 : (type.getFiles() - 1); // we exclude hour 0 since it is not available
// for cosmo ww
if (count != expected) {
// do not return immediately to generate full debug log of variable mismatches
log.log(Level.INFO, "Variable mismatch in " + v + ", expected " + expected + " was " + count + ".");
@@ -631,65 +678,73 @@ public class NumericPrediction {
}
}
return success;
}
}
/**
* Performs a remote synchronization.
*
* @param listener An optional listener to keep track of changes.
*
* @param listener
* An optional listener to keep track of changes.
*/
public void synchronize(FileStatusListener listener) {
log.log(Level.INFO, "Synchronizing " + type.getServer() + type.getFolder() + " to " + localFolder.getAbsolutePath() + ".");
for (Variable v: variables) {
log.log(Level.INFO,
"Synchronizing " + type.getServer() + type.getFolder() + " to " + localFolder.getAbsolutePath() + ".");
for (Variable v : variables) {
log.log(Level.INFO, "Synchronizing files for variable " + v.name());
String f = v.getFolder();
Predicate<File> fileFilter = new Predicate<File>() {
@Override
public boolean test(File t) {
String substring = type.getSystem().getFilter();
return (t.exists() || t.getName().contains(substring)) && getHour(t.getName()) != 0 && t.getName().endsWith(GRIB_EXTENSION);
return (t.exists() || t.getName().contains(substring))
&& (getHour(t.getName()) != 0 || v.isInvariant()) && t.getName().endsWith(GRIB_EXTENSION);
}
};
FtpFolderSync sync = new FtpFolderSync(new File(localFolder, f), type.getServer(), type.getFolder() + f + "/", fileFilter);
};
FtpFolderSync sync = new FtpFolderSync(new File(localFolder, f), type.getServer(),
type.getFolder() + f + "/", fileFilter);
sync.setStatusListener(new FileStatusListener() {
@Override
public void onFileStatusChanged(FtpFolderSync source, FileStatus status) {
log.log(Level.FINE, status.getAction().name() + ": " + status.getFile().getName());
if (listener != null) listener.onFileStatusChanged(source, status);
log.log(Level.INFO, status.getAction().name() + ": " + status.getFile().getName());
if (listener != null)
listener.onFileStatusChanged(source, status);
}
});
try {
sync.synchronize();
} catch (IOException e) {
log.log(Level.WARNING, "File synchronization failed for "+ v.name() + ".");
log.log(Level.WARNING, "File synchronization failed for " + v.name() + ".");
}
}
}
}
/**
* Extracts the forecast hour from the file.
*
* @param input The input file.
*
* @param input
* The input file.
* @return The forecast hour.
* @throws IOException Thrown if the file cannot be read.
* @throws IOException
* Thrown if the file cannot be read.
*/
public int getForecastHour(File input) throws IOException {
Grib2File file = new Grib2File(createStream(input));
try {
Grib2Data data = file.nextData();
ForecastProduct product = (ForecastProduct)data.getProductSection().getTemplate();
ForecastProduct product = (ForecastProduct) data.getProductSection().getTemplate();
return product.time / 60;
} catch (Exception e) {
throw new IOException("Failed to extract forecast hour.", e);
} finally {
file.close();
file.close();
}
}
/**
* Extracts the hour from the file name.
*
* @param filename The file name.
*
* @param filename
* The file name.
* @return The hour.
*/
public static int getHour(String filename) {
@@ -705,43 +760,46 @@ public class NumericPrediction {
}
return -1;
}
/**
* Reads the values of the first data section of the file into a double array.
*
* @param input The input.
*
* @param input
* The input.
* @return The values of the first data section.
* @throws IOException Thrown if the data cannot be loaded.
* @throws IOException
* Thrown if the data cannot be loaded.
*/
public DoubleArray getValues(File input) throws IOException {
Grib2File file = new Grib2File(createStream(input));
try {
Grib2Data data = file.nextData();
SimpleDataDecoder decoder = new SimpleDataDecoder(data);
DoubleArray result = new DoubleArray((int)data.getGridSection().getPointCount());
int s = (int)data.getGridSection().getPointCount();
for (int i = 0; i < s; i++) {
result.setValue(i, decoder.readNext());
DoubleArray result = new DoubleArray((int) decoder.getPoints());
int current = 0;
for (int i = 0, s = (int) decoder.getSize(); i < s; i++) {
boolean valid = decoder.hasNext();
double value = decoder.readNext();
if (valid) result.setValue(current++, value);
}
return result;
} catch (Exception e) {
throw new IOException("Failed to read data.", e);
} finally {
file.close();
file.close();
}
}
/**
* Creates an input stream from a bzip2 compressed file.
*
* @param input The input file.
*
* @param input
* The input file.
* @return The stream to the file data.
* @throws IOException Thrown if the stream cannot be created.
* @throws IOException
* Thrown if the stream cannot be created.
*/
public InputStream createStream(File input) throws IOException {
return new BZip2CompressorInputStream(new BufferedInputStream(new FileInputStream(input)));
}
}
@@ -0,0 +1,152 @@
package com.mowesta.data.grib2.decoder;
import com.mowesta.data.grib2.section.BitmapSection;
import com.mowesta.data.process.util.DoubleArray;
/**
* Creates a new bitmap handler.
*
* @author Marcus
*/
public class BitmapInterpreter {
/**
* The bitmap or null.
*/
private byte[] bitmap;
/**
* The grid size.
*/
private long size;
/**
* The current index.
*/
private int current = 0;
/**
* Creates a new bitmap handler.
*
* @param section The section.
* @param size The point count.
*/
public BitmapInterpreter(BitmapSection section, long size) {
this.size = size;
if (section.getBitmapIndicator().getValue() == 0) {
bitmap = section.getBitmap();
} else {
bitmap = null;
}
}
/**
* Returns true if there is a bitmap.
*
* @return True if there is a bitmap.
*/
public boolean hasBitmap() {
return bitmap != null;
}
/**
* The total point count which may include
* invalid points.
*
* @return The total point count.
*/
public long getSize() {
return size;
}
/**
* Returns the number of valid points.
*
* @return The points.
*/
public long getPoints() {
if (bitmap == null) {
return size;
} else {
int points = 0;
for (long i = 0, s = size; i < s; i++) {
if (isSet(bitmap, i)) points += 1;
}
return points;
}
}
/**
* The number of bits in the bitmap.
*
* @return The number of bits in the bitmap.
*/
public int getBits() {
return bitmap.length * 8;
}
/**
* Returns true if the next value is present.
*
* @return True if the next value is present.
*/
public boolean hasNext() {
if (current < size) {
if (bitmap == null) {
return true;
} else {
return isSet(this.bitmap, current);
}
} else {
return false;
}
}
/**
* Moves the next value.
*
* @return True if we moved.
*/
public boolean moveNext() {
if (current < size) {
current += 1;
return true;
} else {
return false;
}
}
/**
* Filters an existing array using the bitmap.
*
* @param input The input.
* @return The filtered array.
*/
public DoubleArray filter(DoubleArray input) {
if (input.getSize() != size) throw new RuntimeException("Unexpected filter input size.");
DoubleArray result = new DoubleArray((int)getPoints());
int next = 0;
for (int i = 0, s = (int)size; i < s; i++) {
if (bitmap == null || isSet(bitmap, i)) {
result.setValue(next, input.getValue(i));
next += 1;
}
}
return result;
}
/**
* Determines whether the i-th bit is set.
*
* @param bitmap The bitmap.
* @param index The index of the bit.
* @return True if the bit is set, false otherwise.
*/
public static boolean isSet(byte[] bitmap, long index) {
int idx = (int)index / 8;
if (idx < 0 || idx >= bitmap.length) return false;
return ((0x80 & (bitmap[idx] & 0xff << index - idx * 8)) != 0);
}
}
@@ -6,26 +6,26 @@ import com.mowesta.data.process.util.DoubleArray;
/**
* A decoder for regular grids.
*
*
* @author Marcus
*
*/
public class RegularGridDecoder {
/**
* The typical devider for latitudes and longitudes.
* Grib2 recommendation is micro-degrees.
*/
private static final double DIVIDER = 1e6;
/**
* The grid template.
*/
private AbstractFixedLatLonGrid grid;
/**
* Creates a new decoder.
*
*
* @param section The grid section defining the grid.
* @throws IllegalArgumentException Thrown if the section does
* not contain a regular grid or if the scanning mode is not supported.
@@ -38,7 +38,7 @@ public class RegularGridDecoder {
throw new IllegalArgumentException("Decoder requires fixed latitude longitude grid.");
}
}
/**
* Performs a sanity check on the coordinates.
*/
@@ -54,10 +54,10 @@ public class RegularGridDecoder {
if (Math.abs(dlon - grid.di) > 1) // allow minor rounding errors (present in dwd output)
throw new IllegalArgumentException("Unsupported di specification, expected " + grid.di + " computed " + dlon + " (unsupported scan mode?).");
}
/**
* Returns the latitudes.
*
*
* @return The latitudes.
*/
public DoubleArray getLatitudes() {
@@ -74,10 +74,10 @@ public class RegularGridDecoder {
}
return latitudes;
}
/**
* Returns the longitude and corrects its values.
*
*
* @param value The value.
* @return The longitude.
*/
@@ -87,11 +87,11 @@ public class RegularGridDecoder {
else if (result < -180) result += 360;
return result;
}
/**
* Returns the longitudes.
*
*
* @return The longitudes.
*/
public DoubleArray getLongitudes() {
@@ -109,10 +109,10 @@ public class RegularGridDecoder {
}
return longitudes;
}
/**
* Returns the latitude and corrects its values.
*
*
* @param value The value.
* @return The latitude.
*/
@@ -122,6 +122,6 @@ public class RegularGridDecoder {
if (result < -90) result += 180;
return result;
}
}
@@ -7,11 +7,11 @@ import com.mowesta.data.grib2.io.DataStream;
import com.mowesta.data.grib2.template.data.SimpleData;
/**
* A streaming decoder for data with simple packing.
*
* A streaming decoder for data with simple packing.
*
* @author Marcus
*/
public class SimpleDataDecoder implements StreamDecoder {
public class SimpleDataDecoder {
/**
* The data stream.
@@ -37,15 +37,21 @@ public class SimpleDataDecoder implements StreamDecoder {
* The number of octets (= bits / 8).
*/
private int octets;
/**
* The bitmap interpreter.
*/
private BitmapInterpreter bitmap;
/**
* Creates a simple decoder for the data.
*
*
* @param data The data.
* @throws RuntimeException Thrown if the decoder does not support the format.
*/
public SimpleDataDecoder(Grib2Data data) {
SimpleData simpleData = (SimpleData)data.getRepresentationSection().getTemplate();
this.bitmap = new BitmapInterpreter(data.getBitmapSection(), data.getGridSection().getPointCount());
reference = simpleData.getReferenceValue();
bscale = Math.pow(2, simpleData.getBinaryScaleFactor());
dscale = Math.pow(10, -simpleData.getDecimalScaleFactor());
@@ -54,9 +60,44 @@ public class SimpleDataDecoder implements StreamDecoder {
if (bits % 8 != 0 || octets > 8) throw new RuntimeException("Unsupported bit count (" + bits + ")");
stream = data.getStream();
}
@Override
/**
* Returns the total number of valid and invalid points.
*
* @return The total number of points.
*/
public long getSize() {
return bitmap.getSize();
}
/**
* Returns the number of valid points.
*
* @return The number of valid points.
*/
public long getPoints() {
return bitmap.getPoints();
}
/**
* Determines whether the next value is valid.
*
* @return True if the next value is valid.
*/
public boolean hasNext() {
return bitmap.hasNext();
}
/**
* Reads the next grid value.
*
* @return The next value for the grid.
* @throws IOException Thrown if something fails.
*/
public double readNext() throws IOException {
boolean next = bitmap.hasNext();
bitmap.moveNext();
if (!next) return Double.NaN;
// special case, if bits is 0, return only reference value
if (bits == 0) return reference;
long longBits = 0;
@@ -68,5 +109,5 @@ public class SimpleDataDecoder implements StreamDecoder {
}
return (longBits * bscale + reference) * dscale;
}
}
@@ -0,0 +1,36 @@
package com.mowesta.data.grib2.decoder;
import java.io.IOException;
/**
* A stream decoder that provides a streaming interface
* for a simple decoder.
*
* @author Marcus
*/
public class SimpleStreamDecoder implements StreamDecoder {
/**
* The simple decoder.
*/
private SimpleDataDecoder decoder;
/**
* Creates a new stream decoder from the simple decoder.
*
* @param decoder The decoder.
*/
public SimpleStreamDecoder(SimpleDataDecoder decoder) {
this.decoder = decoder;
}
@Override
public double readNext() throws IOException {
while (! decoder.hasNext()) {
decoder.readNext();
}
return decoder.readNext();
}
}
@@ -4,17 +4,19 @@ import java.io.IOException;
/**
* An interface for streaming decoders.
*
*
* @author Marcus
*/
public interface StreamDecoder {
/**
* Reads the next value from the stream.
*
*
* @return The next value.
* @throws IOException Thrown by the stream.
*/
double readNext() throws IOException;
}
@@ -25,10 +25,10 @@ import javax.inject.Inject;
import org.infinispan.Cache;
import com.mowesta.api.Coordinate;
import com.mowesta.api.weather.WeatherSource;
import com.mowesta.api.weather.SoilType;
import com.mowesta.api.weather.WeatherCondition;
import com.mowesta.api.weather.WeatherForecast;
import com.mowesta.api.weather.WeatherSource;
import com.mowesta.api.weather.WeatherType;
import com.mowesta.api.weather.WindDirection;
import com.mowesta.data.dwd.NumericPrediction;
@@ -37,6 +37,7 @@ import com.mowesta.data.dwd.NumericPrediction.Variable;
import com.mowesta.data.grib2.Grib2Data;
import com.mowesta.data.grib2.Grib2File;
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
import com.mowesta.data.grib2.decoder.SimpleStreamDecoder;
import com.mowesta.data.process.conversion.KelvinCelsiusConversion;
import com.mowesta.data.process.source.Grib2MixedSource;
import com.mowesta.data.process.source.IDataSource;
@@ -46,33 +47,33 @@ import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
/**
* A bean to synchronize the weather forecasts.
*
*
* @author Marcus
*/
@Stateless
public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
/**
* The class with the metadata about the imported forecast.
*
*
* @author Marcus
*/
public static class ForecastMetadata extends Metadata {
/**
* The serialization version.
*/
private static final long serialVersionUID = -624323280988785919L;
/**
* The timestamps hashed by weather source.
*/
private Map<WeatherSource, Time> times = new HashMap<>();
/**
* Returns the time for the source that has been imported.
*
*
* @param source The source to check.
* @return The time for the source.
*/
@@ -81,20 +82,20 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
if (l == null) return new Time(0, 0, 0);
return l;
}
/**
* Sets the time for the source.
*
*
* @param source The source.
* @param time The time that has been imported.
*/
public void setTime(WeatherSource source, Time time) {
times.put(source, time);
}
/**
* Custom deserializer for times.
*
*
* @param ois The input stream.
* @throws IOException Thrown by the stream.
* @throws ClassNotFoundException Never thrown.
@@ -110,10 +111,10 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
times.put(v[i], new Time(year, month, day));
}
}
/**
* Custom serializer for times.
*
*
* @param oos The output stream.
* @throws IOException Thrown by the stream.
*/
@@ -126,18 +127,18 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
oos.writeInt(t.month);
oos.writeInt(t.day);
}
}
}
}
/**
* The chunk size for batch processing. Larger sizes
* will result in faster processing but will also require
* more memory.
*/
private static final int CHUNK_SIZE = 8000;
/**
* The maximum hour to import during testing.
*/
@@ -157,7 +158,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
/**
* Updates the prediction for the current time.
*
*
* @param first A flag to indicate whether this is the first execution.
* @throws Exception Thrown if something fails.
*/
@@ -169,10 +170,10 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
Time time = new Time(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));
syncForecasts(first, time);
}
/**
* Updates the prediction for the specified time.
*
*
* @param first A flag to indicate whether this is the first execcution.
* @param time The time to load from the server.
* @throws Exception Thrown if something fails.
@@ -206,12 +207,12 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
}
}
}
/**
* Checks whether the first entry in the infinispan cache for the
* weather source is available. This checks basically whether the
* cache has been deleted externally without deleting the metadata.
*
*
* @param source The source.
* @return The data.
*/
@@ -219,11 +220,11 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
Long id = WeatherForecastContainer.getId(source, 0);
return infinispanSession.getDataCache().get(id) != null;
}
/**
* Downloads the data for the prediction and returns whether
* something has changed.
*
*
* @param time The time.
* @param prediction The prediction.
* @return True if there was one download.
@@ -250,10 +251,10 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
log.log(Level.INFO, "Ftp sync results are " + counters[0] + " downloaded, " + counters[1] + " maintained and " + counters[2] + " deleted.");
return counters[0] > 0;
}
/**
* Prepares the import of all data from the prediction.
*
* Prepares the import of all data from the prediction.
*
* @param prediction The prediction.
* @param source The source for nice debug output.
* @param time The time.
@@ -265,7 +266,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
log.log(Level.INFO, "Preparing data import for " + source + ".");
long startTime = System.currentTimeMillis();
DoubleArray longitudes = prediction.getLongitues(time);
DoubleArray latitudes = prediction.getLatitudes(time);
DoubleArray latitudes = prediction.getLatitudes(time);
int counter = 0;
Set<Integer> hours = new HashSet<>();
for (Variable v: prediction.getVariables()) {
@@ -282,9 +283,9 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
Grib2Data data = grib2.nextData();
hours.add(hour);
SimpleDataDecoder decoder = new SimpleDataDecoder(data);
IDataSource ds = new Grib2MixedSource(longitudes, latitudes, decoder);
IDataSource ds = new Grib2MixedSource(longitudes, latitudes, new SimpleStreamDecoder(decoder));
prepareData(v, hour, ds);
counter += 1;
counter += 1;
} finally {
grib2.close();
}
@@ -298,7 +299,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
/**
* Adds the data in chunks to the temporary cache.
*
*
* @param variable The variable.
* @param hour The hour.
* @param source The source.
@@ -321,12 +322,12 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
cache.put(getKey(variable, hour, counter), data);
counter += 1;
}
log.log(Level.FINE, "Finished preparation of variable " + variable.name() + " for hour " + hour + ".");
log.log(Level.FINE, "Finished preparation of variable " + variable.name() + " for hour " + hour + ".");
}
/**
* Imports the data after it has been prepared.
*
*
* @param prediction The prediction to read.
* @param time The time to read.
* @param source The source.
@@ -337,7 +338,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
private void importData(NumericPrediction prediction, WeatherSource source, Time time, Set<Integer> hours) throws IOException {
// approximately 45 minutes for ICON_GLOBAL, 30GB cache size (only global)
DoubleArray longitudes = prediction.getLongitues(time);
DoubleArray latitudes = prediction.getLatitudes(time);
DoubleArray latitudes = prediction.getLatitudes(time);
DoubleArray plcov = prediction.getValues(prediction.getFile(Variable.PLCOV, time));
DoubleArray hsurf = prediction.getValues(prediction.getFile(Variable.HSURF, time));
DoubleArray soiltyp = prediction.getValues(prediction.getFile(Variable.SOILTYP, time));
@@ -383,7 +384,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
/**
* Creates the weather condition at the specified index for the specified hour.
*
*
* @param prediction The prediction.
* @param source The source of the condition.
* @param index The index.
@@ -414,16 +415,16 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
/**
* Returns the temperature value in centigrade.
*
*
* @param value The temperature in kelvin.
*/
private double getTemperature(double value) {
return new KelvinCelsiusConversion().convert(value);
}
/**
* Returns the wind speed in meter per second.
*
*
* @param u The u wind.
* @param v The v wind.
* @return The wind speed.
@@ -431,20 +432,20 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
private double getWindSpeed(double u, double v) {
return Math.sqrt(Math.pow(u, 2) + Math.pow(v, 2));
}
/**
* Converts the pressure value from pa to hpa.
*
*
* @param pa The pressure value in pa.
* @return The pressure value in hpa.
*/
private double getPressure(double pa) {
return pa / 100.0;
}
/**
* Returns the wind direction.
*
*
* @param u The u wind.
* @param v The v wind.
* @return The wind direction.
@@ -455,11 +456,11 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
int angle = ((int) Math.round(Math.atan2(v, u) * 8d / Math.PI) * -1 + 10) % 8;
return WindDirection.getByCode(angle);
}
/**
* Returns the value for the variable at the index.
*
*
* @param variable The variable.
* @param hour The hour.
* @param chunk The chunk.
@@ -472,18 +473,18 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
if (value == null) {
String key = getKey(variable, hour, chunk);
//log.log(Level.INFO, "Loading from infinispan cache " + key + ".");
value = (double[])infinispanSession.getTempCache().get(key);
value = infinispanSession.getTempCache().get(key);
//log.log(Level.INFO, "Loaded from infinispan cache " + key + ".");
memcache.addData(variable, chunk, hour, value);
}
return value[index];
}
/**
* Returns the key for a particular chunk.
*
*
* @param variable The variable.
* @param hour The hour.
* @param chunk The 0-based chunk index.
@@ -492,19 +493,19 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
private String getKey(Variable variable, int hour, int chunk) {
return variable.name() + "-" + hour + "-" + chunk;
}
/**
* An implementation of a memory cache that should be significantly
* faster than running generated string keys with java's hashmap.
*
*
* @author Marcus
*/
private static class MemoryCache {
/**
* An entry for data by variable.
*
*
* @author Marcus
*/
private static class VariableEntry {
@@ -514,7 +515,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
private List<ChunkEntry> entries = new ArrayList<>(1);
/**
* Returns the entry for the chunk.
*
*
* @param chunk The chunk.
* @return The entry or null.
*/
@@ -524,12 +525,12 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
if (e.chunck == chunk) return e;
}
return null;
}
}
}
/**
* An entry for data by chunk.
*
*
* @author Marcus
*/
private static class ChunkEntry {
@@ -543,7 +544,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
private Map<Integer, double[]> entries = new HashMap<>(MAX_HOUR);
/**
* Returns the entry for the hour.
*
*
* @param hour The hour.
* @return The entry or null.
*/
@@ -551,15 +552,15 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
return entries.get(Integer.valueOf(hour));
}
}
/**
* The variables.
*/
private VariableEntry[] variables = new VariableEntry[Variable.values().length];
/**
* Adds a data item to the local cache.
*
*
* @param v The vector.
* @param chunk The chunk.
* @param hour The hour.
@@ -577,12 +578,12 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
ce.chunck = chunk;
ve.entries.add(ce);
}
ce.entries.put(Integer.valueOf(hour), data);
ce.entries.put(Integer.valueOf(hour), data);
}
/**
* Returns a data item from the cache.
*
*
* @param v The variable.
* @param chunk The chunk.
* @param hour The hour.
@@ -595,7 +596,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
if (ce == null) return null;
else return ce.getHour(hour);
}
/**
* Removes all data from the cache.
*/
@@ -603,9 +604,9 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
for (int i = variables.length - 1; i >= 0; i--) variables[i] = null;
}
}
}
@@ -25,7 +25,7 @@ public class VideoGeneratorExample {
* @throws IOException Thrown if the files cannot be read.
*/
public static void main(String[] args) throws IOException {
Time time = new Time(2021, 1, 15);
Time time = new Time(2021, 2, 14);
NumericPrediction[] predictions = new NumericPrediction[] {
new NumericPrediction(PredictionType.ICON_GLOBAL, new File("dwd-data/global")),
@@ -6,6 +6,7 @@ import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Request;
@@ -23,7 +24,7 @@ import com.mowesta.service.session.LocationSessionBean;
/**
* Implements the location service.
*
*
* @author Marcus
*/
@RequestScoped
@@ -52,8 +53,8 @@ public class LocationResource implements ILocationService {
*/
@Inject
Logger log;
@Override
public Response searchLocations(PageConfig pageConfig, SearchContext context, String term) {
EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedLocation()));
@@ -63,7 +64,7 @@ public class LocationResource implements ILocationService {
}
return b.tag(tag).build();
}
@Override
public Response searchCities(@Valid PageConfig pageConfig, double longitude1, double latitude1, double longitude2, double latitude2) {
EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedLocation()));
@@ -73,7 +74,7 @@ public class LocationResource implements ILocationService {
}
return b.tag(tag).build();
}
@Override
public Response getCities(PageConfig pageConfig) {
@@ -91,7 +92,7 @@ public class LocationResource implements ILocationService {
ResponseBuilder b = request.evaluatePreconditions(tag);
if (b == null) {
try {
b = Response.ok(locationSession.getCity(id, false));
b = Response.ok(locationSession.getCity(id, false));
} catch (EntityNotFoundException e) {
b = Response.status(Status.NOT_FOUND);
}
@@ -108,7 +109,7 @@ public class LocationResource implements ILocationService {
String boundary = locationSession.getCityBoundary(id);
if (boundary == null)
b = Response.noContent();
else
else
b = Response.ok(boundary);
} catch (EntityNotFoundException e) {
b = Response.status(Status.NOT_FOUND);
@@ -133,7 +134,7 @@ public class LocationResource implements ILocationService {
ResponseBuilder b = request.evaluatePreconditions(tag);
if (b == null) {
try {
b = Response.ok(locationSession.getState(id, false));
b = Response.ok(locationSession.getState(id, false));
} catch (EntityNotFoundException e) {
b = Response.status(Status.NOT_FOUND);
}
@@ -150,15 +151,20 @@ public class LocationResource implements ILocationService {
String boundary = locationSession.getStateBoundary(id);
if (boundary == null)
b = Response.noContent();
else
else
b = Response.ok(boundary);
} catch (EntityNotFoundException e) {
b = Response.status(Status.NOT_FOUND);
}
}
return b.tag(tag).build();
}
}
@Override
public Response getStateBoundaryDeprecated(@Valid @Min(0) long id) {
return getStateBoundary(id);
}
@Override
public Response getStateCities(long id, PageConfig pageConfig) {
EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedLocation()));
@@ -173,7 +179,7 @@ public class LocationResource implements ILocationService {
return b.tag(tag).build();
}
@Override
public Response getCountries(PageConfig pageConfig) {
EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedLocation()));
@@ -183,21 +189,22 @@ public class LocationResource implements ILocationService {
}
return b.tag(tag).build();
}
@Override
public Response getCountry(long id) {
EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedCountry(id)));
ResponseBuilder b = request.evaluatePreconditions(tag);
if (b == null) {
try {
b = Response.ok(locationSession.getCountry(id, false));
b = Response.ok(locationSession.getCountry(id, false));
} catch (EntityNotFoundException e) {
b = Response.status(Status.NOT_FOUND);
}
}
return b.tag(tag).build();
};
};
@Override
public Response getCountryBoundary(long id) {
EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedCountry(id)));
@@ -207,7 +214,7 @@ public class LocationResource implements ILocationService {
String boundary = locationSession.getCountryBoundary(id);
if (boundary == null)
b = Response.noContent();
else
else
b = Response.ok(boundary);
} catch (EntityNotFoundException e) {
b = Response.status(Status.NOT_FOUND);
@@ -215,7 +222,7 @@ public class LocationResource implements ILocationService {
}
return b.tag(tag).build();
}
@Override
public Response getCountryCities(long id, PageConfig pageConfig) {
EntityTag tag = new EntityTag(Long.toString(locationSession.getLastModifiedLocation()));
+3 -3
View File
@@ -28,7 +28,7 @@ task cleanup(type: Delete) {
task ngBuildApp(type: IoNodeTask) {
script = file('node_modules/@angular/cli/bin/ng')
args = ['build', '--prod']
args = ['build', '--prod', '--source-map=false']
inputDir = project.file('./src/')
outputDir = project.file('./build/outputs/mowesta-app/')
}
@@ -41,7 +41,7 @@ task buildApp(type: Copy) {
task ngBuildForecast(type: IoNodeTask) {
script = file('node_modules/@angular/cli/bin/ng')
args = ['build', '--prod', 'mowesta-forecast']
args = ['build', '--prod', '--source-map=false', 'mowesta-forecast']
inputDir = project.file('./src/')
outputDir = project.file('./build/outputs/mowesta-forecast/')
}
@@ -55,7 +55,7 @@ task buildForecast(type: IoNodeTask) {
task ngBuildSearch(type: IoNodeTask) {
script = file('node_modules/@angular/cli/bin/ng')
args = ['build', '--prod', 'mowesta-search']
args = ['build', '--prod', '--source-map=false', 'mowesta-search']
inputDir = project.file('./src/')
outputDir = project.file('./build/outputs/mowesta-search/')
}
@@ -1,3 +1,5 @@
@import "../../styles.scss";
$mws-accent-color: #f9a825;
div { padding: 0; }
@@ -1,3 +1,5 @@
@import "../../styles.scss";
div.element-container {
display: inline-flex;
padding: 0;
@@ -17,15 +17,15 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that redirects requests to files and folders that do
* not exist to a specific file. This will enable HTML5 style routes
* A servlet that redirects requests to files and folders that do
* not exist to a specific file. This will enable HTML5 style routes
* produced by the Angular router when using the default settings.
*
*
* See https://angular.io/guide/router#browser-url-styles for more
* information on this topic. An alternative approach would be to
* fallback to hashes, but the document provides some arguments,
* why using HTML5 routes is a good idea.
*
*
* @author Marcus
*/
public class AngularRouterServlet extends HttpServlet {
@@ -34,36 +34,46 @@ public class AngularRouterServlet extends HttpServlet {
* The serialization version.
*/
private static final long serialVersionUID = 3929749263522914374L;
/**
* A 4kb buffer to copy data.
*/
public static final int DEFAULT_BUFFER_SIZE = 4096;
/**
* The parameter to define a pattern to match.
*/
public static final String PARAMETER_PATTERN = "pattern";
/**
* The default pattern if nothing is configured.
*/
public static final String DEFAULT_PATTERN = ".*";
/**
* The parameter to define the output file that will be
* delivered, if the resource with the specified name
* delivered, if the resource with the specified name
* cannot be found. This means that the angular app will
* have to handle 404.
* have to handle 404.
*/
public static final String PARAMETER_FILE = "file";
/**
* The default file that will be delivered, if the file
* parameter is not configured.
*/
public static final String DEFAULT_FILE = "/index.html";
/**
* The path name segments of public files
*/
public static final String[] PUBLIC_FILES = new String[] {
"mowesta-forecast", "mowesta-search", // scripts
".eot", ".ttf", ".woff", ".woff2", // fonts
".svg", ".png", ".jpg", // images
".txt" // text files
};
/**
* The pattern to match.
*/
@@ -75,7 +85,7 @@ public class AngularRouterServlet extends HttpServlet {
* handle unexploded war deployments as well.
*/
private URL file;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
@@ -91,33 +101,33 @@ public class AngularRouterServlet extends HttpServlet {
throw new ServletException("Cannot access file.", e);
}
try {
this.pattern = Pattern.compile(pattern);
this.pattern = Pattern.compile(pattern);
} catch (PatternSyntaxException e) {
throw new ServletException("Cannot parse pattern.", e);
}
}
@Override
protected long getLastModified(HttpServletRequest req) {
URL url = getFile(req);
if (url != null) return getLastModified(url);
else return -1;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
URL url = getFile(req);
if (url != null) {
setCorsHeader(url, resp);
sendFile(req.getServletContext(), url, resp);
sendFile(req.getServletContext(), url, resp);
} else {
sendNotFound(resp);
}
}
/**
* Returns the modification date of the file.
*
*
* @param url The url pointing to a file.
* @return The modification date.
*/
@@ -127,19 +137,19 @@ public class AngularRouterServlet extends HttpServlet {
c.setDoInput(true);
c.setDoOutput(false);
try {
return c.getLastModified();
return c.getLastModified();
} finally {
c.getInputStream().close();
}
}
} catch (IOException e) {
log("Failed to get modification date.", e);
}
return -1;
}
/**
* Returns the file that should be delivered for the request.
*
*
* @param req The request.
* @return The file.
*/
@@ -161,14 +171,14 @@ public class AngularRouterServlet extends HttpServlet {
if (! pattern.matcher(requestPath).matches()) {
return null;
} else {
return file;
return file;
}
}
/**
* Copies the input to the output stream, no questions asked.
* Note that the streams will not be closed after the operation.
*
*
* @param in The input stream to read from.
* @param out The output stream to write to.
* @throws IOException Thrown if something fails.
@@ -188,19 +198,20 @@ public class AngularRouterServlet extends HttpServlet {
* @param resp The response.
*/
protected void setCorsHeader(URL url, HttpServletResponse resp) {
boolean setCorsHeader = url.getPath().contains("weather-forecast-today")
|| url.getPath().contains("weather-search");
if (setCorsHeader) {
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "origin, content-type, accept");
resp.setHeader("Access-Control-Allow-Headers", "GET");
resp.setHeader("Access-Control-Max-Age", "3600");
}
for (String file: PUBLIC_FILES) {
if (url.getPath().contains(file)) {
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "origin, content-type, accept");
resp.setHeader("Access-Control-Allow-Headers", "GET");
resp.setHeader("Access-Control-Max-Age", "3600");
break;
}
}
}
/**
* Sends the file to the response.
*
*
* @param context The servlet context.
* @param file The file to send.
* @param resp The response.
@@ -220,23 +231,23 @@ public class AngularRouterServlet extends HttpServlet {
try {
OutputStream out = resp.getOutputStream();
try {
copy(in, out);
copy(in, out);
} finally {
out.close();
out.close();
}
} finally {
in.close();
in.close();
}
}
/**
* Sends a not found error to the response.
*
*
* @param resp The response.
* @throws IOException Thrown if status code cannot be sent.
*/
protected void sendNotFound(HttpServletResponse resp) throws IOException {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}