Author SHA1 Message Date
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
handte 3eced06154 Release 1.0.12.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-14 00:12:05 +01:00
handte 894b24a4ff Properly handle predictions that are not updated.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-13 23:51:49 +01:00
53 changed files with 2148 additions and 3835 deletions
Vendored
+1 -1
View File
@@ -51,7 +51,7 @@ node {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
sh 'scp -i $KEYFILE android-app/build/outputs/apk/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
}
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feature/auth") {
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feat/auth") {
echo "Deploying to beta server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-dev.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear'
+1 -1
View File
@@ -89,7 +89,7 @@ android {
applicationId "com.mowesta.android.app"
minSdkVersion 19
targetSdkVersion 29
versionCode 12
versionCode 13
versionName "${version}"
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+2 -3
View File
@@ -21,7 +21,7 @@ allprojects {
// set version for our project
group = 'com.mowesta'
version = '1.0.12-SNAPSHOT'
version = '1.0.13'
// set versions for our libraries
ext {
@@ -55,8 +55,7 @@ allprojects {
versionAndroidXRoom = '2.2.6'
versionAndroidXPreference = '1.1.1'
versionRobolectric = '4.5'
//oauth dependencies
versionJWT = '0.11.2'
}
-1
View File
@@ -32,7 +32,6 @@ swagger {
'com.mowesta.api.measurement.IMeasurementService',
'com.mowesta.api.settings.ISettingsService',
'com.mowesta.api.user.IUserService',
'com.mowesta.api.oauth2.IOAuth2Service',
'com.mowesta.api.version.IVersionService',
'com.mowesta.api.weather.IWeatherService',
]
@@ -43,11 +43,6 @@ public class Tags {
*/
public static final String SETTINGS = "Settings";
/**
* Tag for OAuth.
*/
public static final String OAUTH = "OAuth";
/**
* Prevent instantiation.
@@ -2,66 +2,61 @@ package com.mowesta.api.access;
/**
* The user roles used by the application.
*
*
* @author Marcus
*/
public class Roles {
/**
* The string value of the admin role.
*/
public static final String ADMIN = "admin";
/**
* The string value of the user role.
*/
public static final String USER = "user";
/**
* The string value of the device role.
*/
public static final String DEVICE = "device";
/**
* The role granted to valid services that may
* use oauth to authenticate for a user.
*/
public static final String SERVICE = "service";
/**
* Prevents accidential instantiation.
*/
private Roles() { }
/**
* Returns the names of roles used for human
* subjects.
*
*
* @return The roles used for humans.
*/
public static String[] getHumanRoles() {
return new String[] { ADMIN, USER };
}
/**
* Returns the names of roles used for machines.
*
*
* @return The roles used for machines.
*/
public static String[] getMachineRoles() {
return new String[] { DEVICE, SERVICE };
return new String[] { DEVICE };
}
/**
* Returns the names of all roles.
*
*
* @return The names of all roles.
*/
public static String[] getAllRoles() {
return new String[] { ADMIN, USER, DEVICE, SERVICE };
return new String[] { ADMIN, USER, DEVICE };
}
}
@@ -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);
}
@@ -1,25 +0,0 @@
package com.mowesta.api.oauth2;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@XmlRootElement
@ApiModel(description="Represents an authorization grant. The AccessCode is only used once to get an AuthorizationToken/RequestToken pair.")
public class AuthorizationResponse {
@NotNull
@XmlAttribute(required=true)
@ApiModelProperty(value="The Access Code.", required=true)
private String accessCode;
public String getAccessCode() {
return accessCode;
}
public void setAccessCode(String accessCode) {
this.accessCode = accessCode;
}
}
@@ -1,73 +0,0 @@
package com.mowesta.api.oauth2;
import java.net.URI;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.mowesta.api.Tags;
import com.mowesta.api.access.Authorizations;
import com.mowesta.api.access.Roles;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
/**
* A service to authenticate with the oauth2 protocol.
*
* @author Tobias Stottrop
*/
@Api
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON })
@Path("/")
public interface IOAuth2Service {
@GET
@Path("oauth2/authorize")
@ApiOperation(value = "Use this endpoint to authenticate a user with a social provider. Will return an Access- and Refreshtoken.", authorizations = { @Authorization(Authorizations.USER)}, tags = {Tags.DEFAULT, Tags.OAUTH})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Access token created successfully.", response = AuthorizationResponse.class),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request."),
@ApiResponse(code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message = "Error creating AccessCode."),
@ApiResponse(code = HttpServletResponse.SC_UNAUTHORIZED, message = "User was not authorized.")
})
@RolesAllowed({Roles.USER})
Response getAccessCode(
@ApiParam(value = "Client identifier.", required = true) @QueryParam(value = "client_id") String client_id,
@ApiParam(value = "Endpoint to which should be redirected.", required = true) @QueryParam(value = "redirect_uri") URI redirect_uri,
@ApiParam(value = "Indicates the type of response that should be returned.", required = true) @QueryParam(value="response_type") String response_type,
@ApiParam(value = "Internal state of service which wants to authenticate.", required = true) @QueryParam(value="state") String state,
@ApiParam(value = "Scope of access.", required = true) @QueryParam(value="scope") String scope
);
@POST
@Path("oauth2/token")
@ApiOperation(value = "Use this endpoint to get an Access Token.", tags = {Tags.DEFAULT, Tags.OAUTH})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_FOUND, message = "Access token created successfully.", response = TokenResponse.class),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request.")
})
@RolesAllowed({Roles.SERVICE})
Response getAccessRefreshTokenPair(
@ApiParam(value = "Grant Type.", required = true) @QueryParam(value = "grant_type") String grant_type,
@ApiParam(value = "Client identifier.", required = true) @QueryParam(value = "client_id") String client_id,
@ApiParam(value = "Client secret.", required = true) @QueryParam(value = "client_secret") String client_secret,
@ApiParam(value = "Access Code.", required = false) @QueryParam(value="code") String code,
@ApiParam(value = "Refresh Token.", required = false) @QueryParam(value = "refresh_token") String refresh_token
);
}
@@ -1,79 +0,0 @@
package com.mowesta.api.oauth2;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@XmlRootElement
@ApiModel(description="Represents a token response.")
public class TokenResponse {
@NotNull
@XmlAttribute(required=true)
@ApiModelProperty(value="type of token", required=true)
private String token_type;
@NotNull
@XmlAttribute(required=false)
@ApiModelProperty(value="expiration in seconds", required=false)
private long expires_in;
@NotNull
@XmlAttribute(required=true)
@ApiModelProperty(value="The access token", required=true)
private String access_token;
@NotNull
@XmlAttribute(required=false)
@ApiModelProperty(value="The refresh token.", required=false)
private String refresh_token;
@XmlAttribute(required=false)
@ApiModelProperty(value="The granted scope.", required=false)
private String scope;
public long getExpires_in() {
return expires_in;
}
public void setExpires_in(long expires_in) {
this.expires_in = expires_in;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
}
@@ -1,12 +1,12 @@
package com.mowesta.api.weather;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@@ -80,13 +80,6 @@ public class WeatherCondition {
@XmlAttribute(required = true)
@ApiModelProperty(value="The wind speed at ten meters above the ground in meters per second.", required=true)
private double windSpeed;
/**
* The maximal wind speed 10 meter above the ground.
*/
@XmlAttribute(required = true)
@ApiModelProperty(value="The maximal wind speed at ten meters above the ground in meters per second.", required=true)
private double maxWindSpeed;
/**
* The cloud cover in percent from 0 (no clouds) to 1 (just clouds).
@@ -410,19 +403,5 @@ public class WeatherCondition {
public void setSnowDepth(double snowDepth) {
this.snowDepth = snowDepth;
}
/**
* Returns the maxWindSpeed.
*
* @return The maxWindSpeed.
*/
public double getMaxWindSpeed() { return maxWindSpeed; }
/**
* Sets the maxWindSpeed.
*
* @param maxWindSpeed The maxWindSpeed to set.
*/
public void setMaxWindSpeed(double maxWindSpeed) { this.maxWindSpeed = maxWindSpeed; }
}
-6
View File
@@ -6,7 +6,6 @@ description = 'Mowesta Alexa Service'
dependencies {
implementation project(path: ':service-war')
providedCompile project(':service-ejb')
compile "com.amazon.alexa:ask-sdk:2.37.1"
@@ -15,11 +14,6 @@ dependencies {
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
compile "io.jsonwebtoken:jjwt-api:0.11.2"
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
compile "org.bouncycastle:bcprov-jdk15on:1.60"
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
}
@@ -2,7 +2,6 @@ package com.mowesta.service.alexa;
import com.amazon.ask.Skills;
import com.amazon.ask.servlet.SkillServlet;
import com.mowesta.api.measurement.Measurement;
import com.mowesta.service.alexa.impl.CancelandStopIntentHandler;
import com.mowesta.service.alexa.impl.ClothingRecommendationIntentHandler;
import com.mowesta.service.alexa.impl.CurrentWeatherIntentHandler;
@@ -10,11 +9,7 @@ import com.mowesta.service.alexa.impl.HelpIntentHandler;
import com.mowesta.service.alexa.impl.LaunchRequestHandler;
import com.mowesta.service.alexa.impl.SessionEndedRequestHandler;
import com.mowesta.service.alexa.impl.WeatherForecastIntentHandler;
import com.mowesta.service.alexa.impl.WeatherstationIntentHandler;
import com.mowesta.service.session.DeviceSessionBean;
import com.mowesta.service.session.LocationSessionBean;
import com.mowesta.service.session.MeasurementSessionBean;
import com.mowesta.service.session.UserSessionBean;
import com.mowesta.service.session.WeatherSessionBean;
import java.io.IOException;
@@ -23,7 +18,6 @@ import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@@ -41,18 +35,6 @@ public class AlexaServlet extends HttpServlet {
@Inject
WeatherSessionBean weatherSessionBean;
@Inject
UserSessionBean userSessionBean;
@Inject
DeviceSessionBean deviceSessionBean;
@Inject
MeasurementSessionBean measurementSessionBean;
@Inject
protected EntityManager entityManager;
Logger log = Logger.getLogger(getClass().getName());
@Override
@@ -82,9 +64,9 @@ public class AlexaServlet extends HttpServlet {
new SessionEndedRequestHandler(),
new CurrentWeatherIntentHandler(locationSessionBean, weatherSessionBean),
new WeatherForecastIntentHandler(locationSessionBean, weatherSessionBean),
new WeatherstationIntentHandler(userSessionBean, deviceSessionBean, measurementSessionBean, entityManager),
new ClothingRecommendationIntentHandler(locationSessionBean, weatherSessionBean))
.withSkillId("amzn1.ask.skill.208278db-dd0c-477e-9946-5ebe634831aa")
.build());
}
}
@@ -4,51 +4,14 @@ import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
import com.amazon.ask.model.IntentRequest;
import com.amazon.ask.model.Response;
import com.mowesta.api.PageConfig;
import com.mowesta.api.TimeRange;
import com.mowesta.api.device.Device;
import com.mowesta.api.device.DevicePage;
import com.mowesta.api.measurement.Measurement;
import com.mowesta.service.entity.EntityForbiddenException;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.entity.OAuthSecretEntity;
import com.mowesta.service.entity.UserEntity;
import com.mowesta.service.session.DeviceSessionBean;
import com.mowesta.service.session.MeasurementSessionBean;
import com.mowesta.service.session.UserSessionBean;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import static com.amazon.ask.request.Predicates.intentName;
public class WeatherstationIntentHandler implements IntentRequestHandler {
UserSessionBean userSessionBean;
DeviceSessionBean deviceSessionBean;
MeasurementSessionBean measurementSessionBean;
EntityManager entityManager;
Logger logger = Logger.getLogger(getClass().getName());
public WeatherstationIntentHandler(UserSessionBean userSessionBean,
DeviceSessionBean deviceSessionBean,
MeasurementSessionBean measurementSessionBean,
EntityManager entityManager) {
this.userSessionBean = userSessionBean;
this.deviceSessionBean = deviceSessionBean;
this.measurementSessionBean = measurementSessionBean;
this.entityManager = entityManager;
}
@Override
public boolean canHandle(HandlerInput input, IntentRequest intentRequest) {
return input.matches(intentName("WeatherstationIntent"));
@@ -56,14 +19,10 @@ public class WeatherstationIntentHandler implements IntentRequestHandler {
@Override
public Optional<Response> handle(HandlerInput input, IntentRequest intentRequest) {
logger.log(Level.INFO, "WeatherStationIntent started");
String accessToken = input.getRequestEnvelope().getContext().getSystem().getUser().getAccessToken();
logger.log(Level.INFO, "AccessToken: " + accessToken);
if (accessToken == null) {
if (accessToken!=null) {
String errorText = "Du musst mit angemeldet sein, um diesen Service nutzen zu können. " +
"Bitte gehe in die Alexa App und melde dich an.";
return input.getResponseBuilder()
@@ -71,88 +30,12 @@ public class WeatherstationIntentHandler implements IntentRequestHandler {
.withLinkAccountCard()
.build();
} else {
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
if (secretKey.isPresent()) {
OAuthSecretEntity secretEntity = secretKey.get();
Claims claims = Jwts
.parserBuilder()
.setSigningKey(secretEntity.getSecret().getBytes())
.build()
.parseClaimsJws(accessToken)
.getBody();
String userId = claims.getId();
logger.log(Level.INFO, "UserID: " + userId);
UserEntity userEntity = userSessionBean.findUser(userId);
if (userEntity != null) {
logger.log(Level.INFO, "UserEntity: " + userEntity.getName());
DevicePage devicePage = null;
try {
devicePage = deviceSessionBean.getAllDevicesForCurrentUser(new PageConfig(0, 60), true);
} catch (EntityNotFoundException e) {
e.printStackTrace();
}
logger.log(Level.INFO, "device at 0: " + devicePage.getElements().get(0));
if (devicePage == null) {
String errorText = "Es konnten keine Geräte gefunden werden.";
return input.getResponseBuilder()
.withSpeech(errorText)
.withSimpleCard("Error", errorText)
.build();
}
Device device = devicePage.getElements().get(0);
Measurement measurement = null;
try {
measurement = measurementSessionBean.getDeviceMeasurements(device.getId(), new TimeRange(System.currentTimeMillis(), System.currentTimeMillis() + 10),
new PageConfig(0, 1), false).getElements().get(0);
logger.log(Level.INFO, "measurement: " + measurement.getTemperature());
} catch (EntityNotFoundException e) {
e.printStackTrace();
} catch (EntityForbiddenException e) {
e.printStackTrace();
}
String measurementString = "";
if (measurement != null) {
measurementString += "Die Temperatur beträgt " + measurement.getTemperature() + " Grad.";
} else measurementString += "Es wurde keine Messung gefunden.";
return input.getResponseBuilder()
.withSpeech(measurementString)
.withSimpleCard("Measurement", measurementString)
.build();
} else {
String errorText = "Der Nutzer konnte nicht gefunden werden.";
return input.getResponseBuilder()
.withSpeech(errorText)
.withSimpleCard("Error", errorText)
.build();
}
} else {
String errorText = "Es ist ein Fehler aufgetreten. Bitte versuche es später nochmal.";
return input.getResponseBuilder()
.withSpeech(errorText)
.withSimpleCard("Error", errorText)
.build();
}
String errorText = "Herzlichen Glückwunsch";
return input.getResponseBuilder()
.withSpeech(errorText)
.withSimpleCard("Glückwunsch", errorText)
.build();
}
}
private Optional<OAuthSecretEntity> findCurrentValidSecret() {
TypedQuery<OAuthSecretEntity> query = entityManager.createNamedQuery("OAuth.findAllSecrets", OAuthSecretEntity.class);
List<OAuthSecretEntity> oAuthSecretEntityList = query.getResultList();
return oAuthSecretEntityList.stream()
.filter(oAuthSecretEntity -> oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() < System.currentTimeMillis())
.findAny();
}
}
@@ -1,19 +1,5 @@
package com.mowesta.data.dwd;
import com.mowesta.data.ftp.FileStatus;
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.RegularGridDecoder;
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
import com.mowesta.data.grib2.template.product.ForecastProduct;
import com.mowesta.data.process.util.DoubleArray;
import com.mowesta.data.process.util.FileNameComparator;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -27,20 +13,34 @@ import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import com.mowesta.data.ftp.FileStatus;
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;
import com.mowesta.data.grib2.template.product.ForecastProduct;
import com.mowesta.data.process.util.DoubleArray;
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,70 +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 maximum wind speed at 10m height.
*/
VMAX_10M("vmax_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> {
@@ -353,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));
@@ -384,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;
}
@@ -396,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);
@@ -408,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.
*/
@@ -434,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.VMAX_10M, 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) {
@@ -555,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);
}
@@ -564,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 + ".");
@@ -636,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) {
@@ -710,43 +760,47 @@ 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,8 +7,8 @@ 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 {
@@ -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,39 @@ public class SimpleDataDecoder implements StreamDecoder {
if (bits % 8 != 0 || octets > 8) throw new RuntimeException("Unsupported bit count (" + bits + ")");
stream = data.getStream();
}
/**
* 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();
}
@Override
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 +104,5 @@ public class SimpleDataDecoder implements StreamDecoder {
}
return (longBits * bscale + reference) * dscale;
}
}
@@ -4,17 +4,18 @@ 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;
}
-7
View File
@@ -12,12 +12,6 @@ dependencies {
compile "org.mapstruct:mapstruct-jdk8:${mapstructVersion}"
compile "org.infinispan:infinispan-query:${versionInfinispan}"
compile "io.jsonwebtoken:jjwt-api:0.11.2"
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
// Uncomment the next line if you want to use RSASSA-PSS (PS256, PS384, PS512) algorithms:
compile "org.bouncycastle:bcprov-jdk15on:1.60"
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
compileOnly "org.hibernate:hibernate-search-orm:${versionHibernateSearch}"
compileOnly "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
compileOnly "com.fasterxml.jackson.core:jackson-annotations:${versionJackson}"
@@ -80,4 +74,3 @@ compileJava {
options.annotationProcessorPath = configurations.annotationProcessor
}
@@ -1,62 +0,0 @@
package com.mowesta.service.entity;
import java.security.Key;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
/**
* The entity that represents an OAuthSecret.
*
* @author Tobias S.
*/
@Entity
@Table(name="oauthsecret", uniqueConstraints=@UniqueConstraint(columnNames= {"secret"}))
@NamedQueries({
@NamedQuery(name = "OAuth.findAllSecrets", query = "select o from OAuthSecretEntity o")
})
public class OAuthSecretEntity extends AbstractEntity {
/**
* The serialization version.
*/
private static final long serialVersionUID = 287153745987186120L;
@NotNull
private String secret;
@NotNull
private long timeValid;
@NotNull
private boolean valid;
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public long getTimeValid() {
return timeValid;
}
public void setTimeValid(long timeValid) {
this.timeValid = timeValid;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
}
@@ -1,104 +0,0 @@
package com.mowesta.service.entity;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
/**
* The entity that represents Refreshtoken.
*
* @author Tobias S.
*/
@Entity
@Table(name="authtoken", uniqueConstraints=@UniqueConstraint(columnNames= {"user_id", "refreshtoken"}))
@NamedQueries({
@NamedQuery(name="findRefreshToken", query="select r from RefreshTokenEntity r where r.refreshToken=:refreshToken"),
})
public class RefreshTokenEntity extends AbstractEntity {
/**
* The serialization version.
*/
private static final long serialVersionUID = 287453795983186000L;
/**
* The user that has this refreshtoken.
*/
@NotNull
@ManyToOne
@JoinColumn(name="user_id")
private UserEntity user;
/**
* The refreshtoken.
*/
@NotNull
@JoinColumn(name="refreshtoken")
private String refreshToken;
/**
* The service name.
*/
private String serviceName;
/**
* Returns the user.
*
* @return The user.
*/
public UserEntity getUser() {
return user;
}
/**
* Sets the user.
*
* @param user The user to set.
*/
public void setUser(UserEntity user) {
this.user = user;
}
/**
* Returns the refreshtoken.
*
* @return The refreshtoken.
*/
public String getRefreshToken() {
return refreshToken;
}
/**
* Sets the refreshtoken.
*
* @param refreshToken The Refreshtoken to set.
*/
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
/**
* Returns the refreshtoken.
*
* @return The refreshtoken.
*/
public String getServiceName() {
return serviceName;
}
/**
* Sets the name of the service.
*
* @param serviceName The servicename to set.
*/
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
}
@@ -1,7 +1,5 @@
package com.mowesta.service.entity;
import com.mowesta.api.PageConfig;
import java.util.List;
import java.util.Set;
@@ -30,6 +28,8 @@ import javax.persistence.criteria.Root;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import com.mowesta.api.PageConfig;
/**
* The entity to store users.
*
@@ -87,14 +87,7 @@ public class UserEntity extends AbstractEntity {
@CollectionTable(name = "user_location")
@ElementCollection(fetch = FetchType.LAZY)
private List<EmbeddedLocation> locations;
/**
* The refresh tokens of the user.
*/
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private Set<RefreshTokenEntity> refreshTokens;
/**
* The iterations of the password hash.
*/
@@ -111,13 +104,12 @@ public class UserEntity extends AbstractEntity {
*/
@NotNull
private byte[] salt;
/**
* A flag that indicates that the account is deactivated.
*/
private boolean suspended;
/**
* Returns the name.
*
@@ -279,24 +271,6 @@ public class UserEntity extends AbstractEntity {
public void setSuspended(boolean suspended) {
this.suspended = suspended;
}
/**
* Returns the Refreshtokens.
*
* @return The refreshTokens.
*/
public Set<RefreshTokenEntity> getRefreshTokens() {
return refreshTokens;
}
/**
* Sets the refreshtokens.
*
* @param refreshTokens The refreshTokens to set.
*/
public void setRefreshTokens(Set<RefreshTokenEntity> refreshTokens) {
this.refreshTokens = refreshTokens;
}
/**
@@ -1,12 +1,10 @@
package com.mowesta.service.entity;
import com.mowesta.api.Coordinate;
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 java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
@@ -23,11 +21,13 @@ import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.query.SearchManager;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import com.mowesta.api.Coordinate;
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;
/**
* A container to store weather forecasts in an infinispan cache with
@@ -136,7 +136,6 @@ public class WeatherForecastContainer implements Coordinates {
result.setType(WeatherType.values()[in.readInt()]);
result.setWindDirection(WindDirection.values()[in.readInt()]);
result.setWindSpeed(in.readDouble());
result.setMaxWindSpeed(in.readDouble());
return result;
}
@@ -162,7 +161,6 @@ public class WeatherForecastContainer implements Coordinates {
out.writeInt(c.getType().ordinal());
out.writeInt(c.getWindDirection().ordinal());
out.writeDouble(c.getWindSpeed());
out.writeDouble(c.getMaxWindSpeed());
}
}
@@ -21,24 +21,24 @@ import com.mowesta.service.session.sync.LocationSyncSessionBean;
/**
* A bean that is executed by the startup bean to initialize the database
* with a default set of roles and user accounts, unless they exist already.
*
*
* @author Marcus
*/
@Stateless
public class DataSessionBean {
@Inject
protected Logger log;
@Inject
protected EntityManager em;
@Inject
protected LocationSyncSessionBean syncSession;
@Inject
protected ShutdownSessionBean shutdownSession;
@Inject
protected WeatherSessionBean forecastSession;
@@ -65,12 +65,11 @@ public class DataSessionBean {
addRole(Roles.ADMIN, "Grants admin privileges.");
addRole(Roles.USER, "Grants user privileges.");
addRole(Roles.DEVICE, "Grants device privileges.");
addRole(Roles.SERVICE, "Grants service privileges.");
}
/**
* Adds a role, if it is not present already, and returns it.
*
*
* @param name The name of the role.
* @param description The description of the role.
* @return The role that was present or has been added.
@@ -100,12 +99,11 @@ public class DataSessionBean {
log.log(Level.INFO, "Initializing users.");
initUser("admin", "Administrator", "admin", "nes-admin@uni-due.de", new String[] { Roles.ADMIN, Roles.USER});
initUser("handte", "Marcus Handte", "secure", "marcus.handte@uni-due.de", new String[] { Roles.USER });
initUser("alexa", "Amazon Alexa", "p8exqbInnyYKe5YkLIDVbKftiNnXbtHTVNohEYSqUfFXF66NuVnrF6psufLPg2BuNRdTjqHkSlz", "nes-admin@uni-due.de", new String[] { Roles.SERVICE });
}
/**
* Adds a user, if it does not exist already, and returns it.
*
*
* @param login The login.
* @param name The name.
* @param password The password.
@@ -123,10 +121,10 @@ public class DataSessionBean {
return createUser(login, name, password, email, roles);
}
}
/**
* Creates the specified user.
*
*
* @param login The login name.
* @param name The user name.
* @param password The password.
@@ -155,7 +153,7 @@ public class DataSessionBean {
/**
* Creates a new email entity for the user.
*
*
* @param u The user.
* @param email The email address.
* @param verified The state of the verified flag.
@@ -170,7 +168,7 @@ public class DataSessionBean {
u.getEmails().add(e);
em.persist(e);
}
}
@@ -125,7 +125,7 @@ public class DeviceSessionBean extends AbstractUserSpecificSessionBean {
* @return The page of devices.
* @throws EntityNotFoundException Thrown if the user cannot be found.
*/
@RolesAllowed({ Roles.USER , Roles.SERVICE})
@RolesAllowed({ Roles.USER })
public DevicePage getAllDevicesForCurrentUser(PageConfig pageConfig, boolean filtered)
throws EntityNotFoundException {
UserEntity user = getPrincipalUser();
@@ -1,5 +1,18 @@
package com.mowesta.service.session;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.inject.Inject;
import com.mowesta.api.PageConfig;
import com.mowesta.api.access.Roles;
import com.mowesta.api.user.Email;
@@ -20,26 +33,12 @@ import com.mowesta.service.entity.EntityConflictException;
import com.mowesta.service.entity.EntityForbiddenException;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.entity.OrderCriterion;
import com.mowesta.service.entity.RefreshTokenEntity;
import com.mowesta.service.entity.RoleEntity;
import com.mowesta.service.entity.UserEntity;
import com.mowesta.service.principal.LoginManager;
import com.mowesta.service.template.EmailAssignment;
import com.mowesta.service.template.EmailTemplate;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.inject.Inject;
/**
* A stateful session bean that provides methods to manipulate
* users.
@@ -117,21 +116,6 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
if (u.isDeleted() || u.isSuspended()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "Cannot access suspended or deleted user.");
return Convert.with(UserConverter.class).apply(u, true);
}
/**
* Returns the account of the user that is currently logged in as UserEntity.
*
* @return The user that is currently logged in as UserEntity.
* @throws EntityForbiddenException Thrown if the current account is suspended or deleted.
* @throws EntityNotFoundException Thrown if the current account is not found.
*/
@RolesAllowed({ Roles.USER })
public UserEntity getCurrentUserEntity() throws EntityForbiddenException, EntityNotFoundException {
UserEntity u = getPrincipalUser();
if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot access current user.");
if (u.isDeleted() || u.isSuspended()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "Cannot access suspended or deleted user.");
return u;
}
/**
* Modifies the current user.
@@ -227,17 +211,6 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
return page;
}
@PermitAll
public void addRefreshTokenToUser(String login, RefreshTokenEntity refreshTokenEntity) throws EntityNotFoundException {
UserEntity u = findUser(login);
if (u == null)
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(login), "User request by admin for non-existing user.");
refreshTokenEntity.setUser(u);
u.getRefreshTokens().add(refreshTokenEntity);
em.persist(refreshTokenEntity);
em.flush();
}
/**
* Registers the user and returns the new account or
@@ -261,7 +234,6 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
setPassword(u, registration.getPassword());
setRoles(u, roles);
u.setEmails(new HashSet<EmailEntity>());
u.setRefreshTokens(new HashSet<RefreshTokenEntity>());
em.persist(u);
EmailEntity e = addEmail(u, registration.getEmail(), true);
em.persist(e);
@@ -544,19 +516,6 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
emailSession.sendEmailTemplate(email.getAddress(), EmailTemplate.RESET_USER, assignment);
}
}
/**
* Returns true, if refreshToken matches
*
* @param refreshToken The refreshToken to compare.
*
*/
@PermitAll
public Boolean compareRefreshToken(String refreshToken) throws EntityNotFoundException {
UserEntity u = getPrincipalUser();
if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot access current user.");
return true;
}
/**
* Gets and updates an exisiting code for the specified action type
@@ -688,6 +647,4 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
c.setExpirationTime(expirationTime);
return c;
}
}
@@ -40,32 +40,32 @@ import com.mowesta.service.session.sync.WeatherVideoSyncSessionBean;
/**
* The session bean that handles weather reports.
*
*
* @author Marcus
*/
@Stateless
public class WeatherSessionBean extends AbstractPrincipalSessionBean {
/**
* The maximum age of weather reports included in weather conditions.
*/
private static final long MAX_REPORT_AGE = 60*60*1000;
/**
* The infinispan session bean.
*/
@Inject
private InfinispanSessionBean infinispanSession;
/**
* The session bean to access video metadata.
*/
@Inject
private WeatherVideoSyncSessionBean videoSession;
/**
* Returns the best and longest forecast for a given coordinate.
*
*
* @param location The coordinate.
* @return The best forecast for the coordinate or null, if there is none.
*/
@@ -74,11 +74,22 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
public WeatherForecast getForecast(Coordinate location) {
SearchManager manager = Search.getSearchManager(infinispanSession.getDataCache());
List<WeatherForecastContainer> containers = WeatherForecastContainer.findByLocation(manager, location, 10);
// compute the map of forecasts
// compute the map of forecasts (distance is considered since list is ordered)
Map<WeatherSource, WeatherForecast> forecasts = new HashMap<>();
for (int i = containers.size() - 1; i >= 0; i--) {
forecasts.put(containers.get(i).getSource(), containers.get(i).getForecast());
}
// find the most recent prediction time from all sources
long threshold = 0;
for (WeatherForecast forecast: forecasts.values()) {
if (forecast.getConditions().size() > 0) {
long time = forecast.getConditions().get(0).getTime();
for (int i = 1, s = forecast.getConditions().size(); i < s; i++) {
time = Math.min(forecast.getConditions().get(i).getTime(), time);
}
threshold = Math.max(threshold, time);
}
}
// compute the set of "best" conditions from all sources
Map<Long, WeatherCondition> conditions = new HashMap<>();
WeatherForecast result = null;
@@ -88,7 +99,11 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
if (next != null) {
result = next;
for (WeatherCondition c: next.getConditions()) {
conditions.put(c.getTime(), c);
// only keep data that is fresher than the latest
// prediction, in case some prediction is not updated
if (c.getTime() >= threshold) {
conditions.put(c.getTime(), c);
}
}
}
}
@@ -103,22 +118,22 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
/**
* Returns the forecast with the specified id.
*
*
* @param id The id of the forecast.
* @return The forecast with the id or null, if the id is invalid.
*/
@PermitAll
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public WeatherForecast getForecast(long id){
WeatherForecastContainer container = (WeatherForecastContainer)infinispanSession.getDataCache().get(id);
WeatherForecastContainer container = infinispanSession.getDataCache().get(id);
if (container == null) return null;
else return container.getForecast();
}
/**
* Returns a page of weather stations that match the term. If the
* Returns a page of weather stations that match the term. If the
* term is null or the empty string, all stations will be returned.
*
*
* @param term The search term.
* @param config The page config.
* @param filtered True to filter deleted.
@@ -138,10 +153,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
page.setTotal(count);
return page;
}
/**
* Returns the weather station with the specified id.
*
*
* @param id The id of the station.
* @return The weather station.
* @throws EntityNotFoundException
@@ -151,10 +166,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
WeatherStationEntity station = getStationEntity(id);
return Convert.with(WeatherStationConverter.class).apply(station, false);
}
/**
* Returns the weather station entity with the specified id.
*
*
* @param id The id to search.
* @return The entity.
* @throws EntityNotFoundException Thrown if not found.
@@ -165,20 +180,20 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
throw new EntityNotFoundException(WeatherStationEntity.class, id);
return station;
}
/**
* Returns the last modification date over all stations.
*
*
* @return The last modification date over all stations.
*/
@PermitAll
public long getLastModifiedStation() {
return AbstractEntity.getLastModified(em, WeatherStationEntity.class);
}
/**
* Returns the last modification time stamp for the station.
*
*
* @param id The station id.
* @return The last modification time stamp.
* @throws EntityNotFoundException Thrown if the entity does not exist.
@@ -188,10 +203,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
WeatherStationEntity station = getStationEntity(id);
return WeatherReportEntity.getLastModifiedForStation(em, station);
}
/**
* Returns a report page for a specific station and time range.
*
*
* @param id The station id.
* @param range The time range.
* @param config The page configuration.
@@ -214,10 +229,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
}
return page;
}
/**
* Returns the latest report from the station.
*
*
* @param id The id of the station.
* @param filtered True to filter deleted.
* @return The weather report.
@@ -228,10 +243,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
WeatherStationEntity station = getStationEntity(id);
return Convert.with(WeatherReportConverter.class).apply(getLatestReportEntity(station, filtered), filtered);
}
/**
* Returns the latest report from the station.
*
*
* @param station The weather station.
* @param filtered True to filter deleted, false otherwise.
* @return The weather report.
@@ -241,12 +256,12 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
if (time == 0) return null;
else return WeatherReportEntity.findByTime(em, station, time);
}
/**
* Returns the nearest weather station for the coordinate or
* null, if there is no nearby station.
*
*
* @param coordinate The coordinate.
* @param filtered True to filter deleted.
* @return The weather station.
@@ -255,10 +270,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
public WeatherStation getStation(Coordinate coordinate, boolean filtered) {
return Convert.with(WeatherStationConverter.class).apply(getStationEntity(coordinate, filtered), filtered);
}
/**
* Returns the closest station to the entity.
*
*
* @param coordinate The coordinate.
* @param filtered True to filter deleted.
* @return The station entity.
@@ -270,13 +285,13 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
}
return null;
}
/**
* Returns the weather conditions for the coordinate.
*
*
* @param coordinate The coordinate.
*
*
* @return The weather condition or null.
*/
@PermitAll
@@ -307,32 +322,32 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
}
return result;
}
/**
* Returns the last modification timestamp of the weather video metadata.
*
*
* @return The last modification timestamp.
*/
@PermitAll
public long getLastModifiedVideo() {
return videoSession.getMetadata().getModificationTime();
}
/**
* Returns a page of all videos.
*
*
* @param config The page config.
* @return The video page.
*/
@PermitAll
public WeatherVideoPage getVideos(PageConfig config) {
return getVideoPage(videoSession.getMetadata().getVideos(false), config);
}
/**
* Returns a page of videos that are relevant for the coordinate.
*
*
* @param c The coordinate.
* @param config The page config.
* @return The video page.
@@ -341,10 +356,10 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
public WeatherVideoPage getVideos(Coordinate c, PageConfig config) {
return getVideoPage(videoSession.getMetadata().getVideos(c, false), config);
}
/**
* Creates a page of videos using the list of videos and the page config.
*
*
* @param videos The videos to select from.
* @param config The page configuration.
* @return The video page with contents from the list as defined by the config.
@@ -363,7 +378,7 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
/**
* Returns only the latest videos.
*
*
* @return The latest videos.
*/
@PermitAll
@@ -373,7 +388,7 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
/**
* Returns the latest videos for the coordinate.
*
*
* @param c The coordinate.
* @return The list of latest videos for the coordinate.
*/
@@ -381,6 +396,6 @@ public class WeatherSessionBean extends AbstractPrincipalSessionBean {
public List<WeatherVideo> getLatestVideos(Coordinate c) {
return videoSession.getMetadata().getVideos(c, true);
}
}
@@ -1,110 +0,0 @@
package com.mowesta.service.session.sync;
import com.mowesta.api.PageConfig;
import com.mowesta.service.entity.AbstractEntity;
import com.mowesta.service.entity.OAuthSecretEntity;
import com.mowesta.service.entity.OrderCriterion;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.annotation.security.PermitAll;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
@Stateless
public class GenerateOAuthSecretSessionBean extends AbstractSyncSessionBean {
private final long offset = 720000;
private final long secretValidTime = 360000;
@PermitAll
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void syncToken(boolean first) {
deleteOldToken();
if (first) {
invalidateAllToken();
} else {
invalidateOldToken();
}
createSecretKey();
}
/**
* Creates a new Secret Key.
*/
private void createSecretKey() {
log.log(Level.INFO, "Creating new Secret Key.");
Key secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
OAuthSecretEntity oAuthSecretEntity = new OAuthSecretEntity();
oAuthSecretEntity.setValid(true);
oAuthSecretEntity.setTimeValid(secretValidTime);
oAuthSecretEntity.setSecret(Encoders.BASE64.encode(secretKey.getEncoded()));
em.persist(oAuthSecretEntity);
log.log(Level.INFO, "New Secret Key: " + oAuthSecretEntity.getSecret().toString());
}
/**
* Invalidates all OAuthSecretEntities without validation check.
*/
private void invalidateAllToken() {
log.log(Level.INFO, "First Startup - invalidating all OAuthSecretEntities.");
List<OAuthSecretEntity> oAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
oAuthSecretEntities.forEach((oAuthSecretEntity -> {
oAuthSecretEntity.setValid(false);
em.persist(oAuthSecretEntity);
}));
}
/**
* Invalidates all OAuthSecretEntities, which are no longer valid.
*/
private void invalidateOldToken() {
log.log(Level.INFO, "Checking all OAuthSecretEntities for validation.");
List<OAuthSecretEntity> oAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
List<OAuthSecretEntity> invalidateoAuthSecretEntities = new ArrayList<>();
oAuthSecretEntities.forEach((oAuthSecretEntity -> {
if (oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() + offset < System.currentTimeMillis()) {
invalidateoAuthSecretEntities.add(oAuthSecretEntity);
}
}));
log.log(Level.INFO,"Found " + invalidateoAuthSecretEntities.size() + " Entities to invalidate");
invalidateoAuthSecretEntities.forEach((invalidOAuthSecretEntity) -> {
invalidOAuthSecretEntity.setValid(false);
em.persist(invalidOAuthSecretEntity);
});
log.log(Level.INFO, "Invalidated all old OAuthSecretEntities");
}
/**
* Deletes all OAuthSecretEntities, which are longer invalid than a defined offset.
*/
private void deleteOldToken() {
log.log(Level.INFO, "Checking for old OAuthSecretEntities.");
List<OAuthSecretEntity> allOAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
List<OAuthSecretEntity> allOldOAuthSecretEntites = new ArrayList<>();
allOAuthSecretEntities.forEach((oAuthSecretEntity -> {
if (oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() + offset < System.currentTimeMillis()) {
allOldOAuthSecretEntites.add(oAuthSecretEntity);
}
}));
log.log(Level.INFO, "Found " + allOldOAuthSecretEntites.size() + "Entities to remove.");
allOldOAuthSecretEntites.forEach((oldOAuthSecretEntity) -> {
oldOAuthSecretEntity.setDeleted(true);
em.remove(oldOAuthSecretEntity);
em.persist(oldOAuthSecretEntity);
});
log.log(Level.INFO, "Removed all old OAuthSecretEntities");
}
}
@@ -52,11 +52,7 @@ public class PeriodicSyncSessionBean {
/**
* The task that generates weather videos.
*/
VIDEO,
/**
* The task that generates oauth-tokens.
*/
OAUTHTOKEN;
VIDEO;
};
@@ -77,9 +73,6 @@ public class PeriodicSyncSessionBean {
@Inject
protected WeatherVideoSyncSessionBean videoSyncSession;
@Inject
protected GenerateOAuthSecretSessionBean generateOAuthSecretSessionBean;
@Resource
protected SessionContext context;
@@ -101,9 +94,6 @@ public class PeriodicSyncSessionBean {
jobs[JobType.VIDEO.ordinal()] = new Job("VideoSync", (first)-> {
videoSyncSession.syncVideos(first);
});
jobs[JobType.OAUTHTOKEN.ordinal()] = new Job("OAuthTokenSync", (first)-> {
generateOAuthSecretSessionBean.syncToken(first);
});
}
@@ -121,8 +111,6 @@ public class PeriodicSyncSessionBean {
timerService.createIntervalTimer(TimeUnit.MINUTES.toMillis(3), TimeUnit.HOURS.toMillis(1), forecastConfig);
final TimerConfig locationConfig = new TimerConfig(JobType.LOCATION, false);
timerService.createIntervalTimer(0, TimeUnit.MINUTES.toMillis(5), locationConfig);
final TimerConfig oAuthConfig = new TimerConfig(JobType.OAUTHTOKEN, false);
timerService.createIntervalTimer(0, TimeUnit.MINUTES.toMillis(12), oAuthConfig);
}
/**
@@ -1,27 +1,5 @@
package com.mowesta.service.session.sync;
import com.mowesta.api.Coordinate;
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;
import com.mowesta.data.dwd.NumericPrediction.Time;
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.process.conversion.KelvinCelsiusConversion;
import com.mowesta.data.process.source.Grib2MixedSource;
import com.mowesta.data.process.source.IDataSource;
import com.mowesta.data.process.util.DoubleArray;
import com.mowesta.service.entity.WeatherForecastContainer;
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
import org.infinispan.Cache;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -44,6 +22,28 @@ import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
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.WeatherType;
import com.mowesta.api.weather.WindDirection;
import com.mowesta.data.dwd.NumericPrediction;
import com.mowesta.data.dwd.NumericPrediction.Time;
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.process.conversion.KelvinCelsiusConversion;
import com.mowesta.data.process.source.Grib2MixedSource;
import com.mowesta.data.process.source.IDataSource;
import com.mowesta.data.process.util.DoubleArray;
import com.mowesta.service.entity.WeatherForecastContainer;
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
/**
* A bean to synchronize the weather forecasts.
*
@@ -408,7 +408,6 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
double u = getValue(Variable.U10M, hour, chunk, index, cache);
double v = getValue(Variable.V10M, hour, chunk, index, cache);
result.setWindSpeed(getWindSpeed(u, v));
result.setMaxWindSpeed(getValue(Variable.VMAX_10M, hour, chunk, index, cache));
result.setWindDirection(getWindDirection(u, v));
return result;
}
@@ -23,8 +23,6 @@
<class>com.mowesta.service.entity.RoleEntity</class>
<class>com.mowesta.service.entity.StateEntity</class>
<class>com.mowesta.service.entity.UserEntity</class>
<class>com.mowesta.service.entity.RefreshTokenEntity</class>
<class>com.mowesta.service.entity.OAuthSecretEntity</class>
<class>com.mowesta.service.entity.WeatherReportEntity</class>
<class>com.mowesta.service.entity.WeatherStationEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
@@ -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")),
-8
View File
@@ -12,19 +12,11 @@ dependencies {
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
compile "io.jsonwebtoken:jjwt-api:0.11.2"
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
// Uncomment the next line if you want to use RSASSA-PSS (PS256, PS384, PS512) algorithms:
compile "org.bouncycastle:bcprov-jdk15on:1.60"
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
compile 'com.google.code.gson:gson:2.8.6'
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
providedCompile("org.jboss.resteasy:resteasy-client:${versionResteasy}") {
exclude group: 'org.reactivestreams', module: 'reactive-streams'
}
}
jar {
@@ -1,29 +1,17 @@
package com.mowesta.service.app;
import java.util.HashSet;
import java.util.Set;
import com.mowesta.service.access.AccessControlFilter;
import com.mowesta.service.rest.*;
import org.jboss.resteasy.plugins.interceptors.CorsFilter;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.jboss.resteasy.plugins.interceptors.CorsFilter;
import com.mowesta.service.access.AccessControlFilter;
import com.mowesta.service.rest.CorsResponseFilter;
import com.mowesta.service.rest.DeviceResource;
import com.mowesta.service.rest.LocationResource;
import com.mowesta.service.rest.LogResource;
import com.mowesta.service.rest.MeasurementResource;
import com.mowesta.service.rest.ProcessingTimeFilter;
import com.mowesta.service.rest.ServerDebugFilter;
import com.mowesta.service.rest.SettingsResource;
import com.mowesta.service.rest.UserResource;
import com.mowesta.service.rest.VersionResource;
import com.mowesta.service.rest.WeatherResource;
import java.util.HashSet;
import java.util.Set;
/**
* The application is the main entry point of JAX-RS.
*
*
* @author Marcus
*
*/
@@ -34,7 +22,7 @@ public class MowestaApplication extends Application {
* The cors filter implementing the cors policy.
*/
protected CorsFilter corsFilter = new CorsFilter();
/**
* The set of classes.
*/
@@ -44,7 +32,7 @@ public class MowestaApplication extends Application {
* The singleton objects.
*/
protected Set<Object> singletons = new HashSet<>();
/**
* Initializes the application and explicitly
* sets the cors policy and the exposed resources.
@@ -69,17 +57,17 @@ public class MowestaApplication extends Application {
classes.add(SettingsResource.class);
classes.add(CorsResponseFilter.class);
// uncomment to enable heavy debugging
classes.add(ServerDebugFilter.class);
// classes.add(ServerDebugFilter.class);
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
@Override
public Set<Class<?>> getClasses() {
return classes;
}
}
@@ -33,22 +33,22 @@ import com.mowesta.service.principal.LoginManager;
import com.mowesta.service.principal.MowestaPrincipal;
/**
* The server authentication module that
*
* The server authentication module that
*
*/
public class MowestaAuthModule extends AbstractHttpServletAuthModule {
/**
* The realm transmitted as part of a challenge.
*/
public static final String REALM_CHALLENGE = "Basic realm=\"mowesta-api\"";
/**
* The "magic" parameter that enables challenges.
*/
public static final String PARAMETER_CHALLENGE = "testAuth";
/**
* The logger to write debug data to the console.
*/
@@ -56,6 +56,7 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
@Override
protected AuthStatus validateRequest(HttpServletMessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
// extract credentials from (possibly multiple headers)
HttpServletRequest request = messageInfo.getRequest();
BearerAuthCredential deviceCredential = null;
@@ -67,10 +68,8 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
String[] subHeaders = header.split(",");
for (String subHeader: subHeaders) {
subHeader = subHeader.trim();
if (deviceCredential == null)
deviceCredential = BearerAuthCredential.valueOf(subHeader);
if (userCredential == null)
userCredential = BasicAuthCredential.valueOf(subHeader);
if (deviceCredential == null) deviceCredential = BearerAuthCredential.valueOf(subHeader);
if (userCredential == null) userCredential = BasicAuthCredential.valueOf(subHeader);
}
}
}
@@ -84,7 +83,7 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
return sendForbidden(messageInfo, "Access not allowed.");
}
}
// perform user and device authentication
Device device = null;
User user = null;
@@ -100,16 +99,15 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
try {
LoginManager manager = new LoginManager(em);
ta.begin();
if (deviceCredential != null)
device = manager.login(deviceCredential.getToken());
if (userCredential != null)
user = manager.login(userCredential.getUsername(), userCredential.getPassword());
if (deviceCredential != null) device = manager.login(deviceCredential.getToken());
if (userCredential != null) user = manager.login(userCredential.getUsername(), userCredential.getPassword());
} finally {
ta.commit();
}
} catch (Exception e) {
return sendServerError(messageInfo, "Transactional error.");
}
// create principal or issue error
if (user != null || device != null) {
// create principal
@@ -145,11 +143,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
return sendForbidden(messageInfo, "Access not allowed.");
}
}
/**
* Tests whether the request requires an auth challenge to be sent out.
* This is done, if the caller has set the
*
*
* @param request The request.
* @return
*/
@@ -165,37 +163,37 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
/**
* Returns the entity manager for the mowesta datastore.
*
*
* @return The entity manager or null, if the entity manager cannot be found.
*/
private EntityManager getEntityManager() {
try {
Context context = new InitialContext();
return (EntityManager)context.lookup("java:app/mowesta/datastore");
return (EntityManager)context.lookup("java:app/mowesta/datastore");
} catch (NamingException e) {
log.log(Level.SEVERE, "Failed to resolve entity manager.", e);
return null;
}
}
/**
* Returns a user transaction for the datastore.
*
*
* @return The user transaction or null, if the transaction cannot be found.
*/
private UserTransaction getUserTransaction() {
try {
Context context = new InitialContext();
return (UserTransaction)context.lookup("java:comp/UserTransaction");
return (UserTransaction)context.lookup("java:comp/UserTransaction");
} catch (NamingException e) {
log.log(Level.SEVERE, "Failed to resolve user transaction.", e);
return null;
}
}
/**
* Sends a forbidden message and returns failed.
*
*
* @param messageInfo The message info.
* @param message The error message.
* @return AuthStatus.FAILED
@@ -204,11 +202,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
HttpServletResponse response = messageInfo.getResponse();
return sendError(response, HttpServletResponse.SC_FORBIDDEN, message);
}
/**
* Sends an unauthorized message and returns failed. A browser will create a
* credentials dialog in response to receiving this message.
*
*
* @param messageInfo The message info.
* @param message The error message.
* @return AuthStatus.FAILED
@@ -218,10 +216,10 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
response.addHeader(HttpHeaders.WWW_AUTHENTICATE, REALM_CHALLENGE);
return sendError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
}
/**
* Sends a server error and returns a auth status failure.
*
*
* @param messageInfo The message info.
* @param message The error message.
* @return AuthStatus.FAILED
@@ -229,11 +227,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
private AuthStatus sendServerError(HttpServletMessageInfo messageInfo, String message) {
return sendError(messageInfo.getResponse(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
}
/**
* Sends an http error with the specified code and message and returns failure.
*
*
* @param response The servlet response.
* @param code The message code.
* @param message The error message.
@@ -241,11 +239,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
*/
private AuthStatus sendError(HttpServletResponse response, int code, String message) {
try {
response.sendError(code, message);
response.sendError(code, message);
} catch (IOException e) {
log.log(Level.WARNING, "Failed to send error " + code + " " + message + ".", e);
}
return AuthStatus.FAILURE;
}
}
@@ -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()));
@@ -7,8 +7,6 @@ import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -17,39 +15,42 @@ import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
/**
* A filter that provides heavy (i.e. expensive) debug output after the
* completion of each request.
*
*
* @author Marcus
*/
@Provider
public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequestFilter {
@Inject
Logger log;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
log.log(Level.INFO, "Request: " + requestContext.getMethod() + " " + requestContext.getUriInfo().getAbsolutePath().toString());
printParameters("Path", requestContext.getUriInfo().getPathParameters());
printParameters("Query", requestContext.getUriInfo().getQueryParameters());
Map<String, List<String>> allHeaders = requestContext.getHeaders();
for (Entry<String, List<String>> e: allHeaders.entrySet()) {
for (String s: e.getValue()) {
log.log(Level.INFO, " " + e.getKey() + ": " + s);
}
List<String> authHeaders = requestContext.getHeaders().get(HttpHeaders.AUTHORIZATION);
if (authHeaders != null) {
for (String authHeader: authHeaders) {
log.log(Level.INFO, " Authorization: " + authHeader);
}
}
log.log(Level.INFO, " Accept: " + requestContext.getHeaderString(HttpHeaders.ACCEPT));
log.log(Level.INFO, " Encoding: " + requestContext.getHeaderString(HttpHeaders.ACCEPT_ENCODING));
byte[] data = readBytes(requestContext.getEntityStream());
if (data != null) {
if (data.length > 0) {
log.log(Level.INFO, "Begin request entity (" + data.length + " bytes):");
log.log(Level.INFO, new String(data, "UTF-8"));
log.log(Level.INFO, "End request entity.");
log.log(Level.INFO, "End request entity.");
} else {
log.log(Level.INFO, "Request entity has 0 bytes.");
}
@@ -58,10 +59,10 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
log.log(Level.INFO, "Request entity stream is null.");
}
}
/**
* Prints a parameter map.
*
*
* @param type The parameter type.
* @param params The parameter map.
*/
@@ -76,10 +77,10 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
log.log(Level.INFO, " " + paramName + " = " + b.toString());
}
}
/**
* Logs most parts of the request and the resulting response.
*
*
* @param requestContext The request context.
* @param responseContext The response context.
*/
@@ -97,13 +98,13 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
log.log(Level.INFO, "Result header: " + key + ": " + o);
}
}
}
/**
* Copies the response entity from the input stream and returns it.
*
*
* @param is The input stream which may be null.
* @return The bytes that have been read or null (if the input stream
* is null).
@@ -1,178 +0,0 @@
package com.mowesta.service.servlet;
import com.google.gson.Gson;
import com.mowesta.api.oauth2.AuthorizationResponse;
import com.mowesta.api.user.User;
import com.mowesta.service.entity.EntityForbiddenException;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.session.UserSessionBean;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.security.Key;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
@WebServlet(urlPatterns = "/oauth2/authorize")
public class OAuthAccessCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final long timeAccessCodeIsValidInMilliSeconds = 240000;
protected static final String secretKey = "SecretForGeneratingAccessCode730474";
//only authorization code is supported
private final List<String> supportedGrantTypes = Arrays.asList("code");
@Inject
protected EntityManager em;
@Inject
UserSessionBean userSessionBean;
Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String client_id = "";
String redirect_uri = "";
String response_type = "";
String state = "";
String scope = "";
logger.log(Level.INFO, "Received Authorize Request - HEADER:");
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
logger.log(Level.INFO,"Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
logger.log(Level.INFO, "Received Authorize Request - PARAMETERS:");
Enumeration<String> parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
logger.log(Level.INFO,"Param Name - " + paramName + ", Value - " + request.getParameter(paramName));
}
logger.log(Level.INFO, "End Authorize request.");
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
if (paramName.equals("redirect_uri")) redirect_uri = request.getParameter(paramName);
if (paramName.equals("response_type")) response_type = request.getParameter(paramName);
if (paramName.equals("state")) state = request.getParameter(paramName);
if (paramName.equals("scope")) scope = request.getParameter(paramName);
}
//logger.log(Level.INFO, "Authorize Request with: clientid " + client_id + "; redirect_uri: " + redirect_uri + "; response_type " + response_type + "; state:" + state + "; scope: " + scope);
if (!supportedGrantTypes.contains(response_type)) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Grant Type currently not supported.");
w.close();
throw new UnsupportedJwtException("Grant Type currently not supported.");
}
// state and scope are optional, checking if client_id, redirect_uri and response type is set
if (Arrays.asList(client_id, redirect_uri, response_type).contains("")) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Please provide a client_id, redirect_uri and response_type.");
w.close();
throw new UnsupportedJwtException("Request needs to include client_id, redirect_uri and response_type.");
}
//an authorization code can only be generated if user is logged in
if (request.getUserPrincipal() != null || request.authenticate(response)) {
logger.log(Level.INFO, "UserPrincipal: " + request.getUserPrincipal().getName());
//Principal is set, we can use the UserSessionBean to get the current user
try {
User user = userSessionBean.getCurrentUser();
logger.log(Level.INFO, "User: " + user.getName() + " with ID:" + user.getId() + "and login: " + user.getLogin());
//generate AccessCode
String accessCode = createAccessCode(user.getLogin());
String base64Accesscode = Base64.getUrlEncoder().encodeToString(accessCode.getBytes());
AuthorizationResponse authorizationResponse = new AuthorizationResponse();
authorizationResponse.setAccessCode(base64Accesscode);
Gson gson = new Gson();
String jsonAuthorizationResponse = gson.toJson(authorizationResponse);
//generate Response
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(jsonAuthorizationResponse);
out.flush();
out.close();
} catch (EntityForbiddenException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Could not identify user.");
w.close();
throw new UserPrincipalNotFoundException("Could not identify user");
} catch (EntityNotFoundException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("An error occurred. Please try again.");
w.close();
throw new UserPrincipalNotFoundException("Could not identify user");
}
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Could not identify user.");
w.close();
throw new UserPrincipalNotFoundException("Could not identify user");
}
}
public String createAccessCode(String id) {
Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
return Jwts.builder()
.setSubject("mowesta:access")
.setId(id)
.setIssuedAt(new Date())
.setNotBefore(new Date())
.setExpiration(new Date(System.currentTimeMillis() + timeAccessCodeIsValidInMilliSeconds))
.signWith(key).compact();
}
public String getAccessToken(String refreshToken, String secret) {
Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(secret.getBytes())).build().parseClaimsJws(refreshToken).getBody().getSubject().equals("access");
return null;
}
}
@@ -1,311 +0,0 @@
package com.mowesta.service.servlet;
import com.google.gson.Gson;
import com.mowesta.api.oauth2.TokenResponse;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.entity.OAuthSecretEntity;
import com.mowesta.service.entity.RefreshTokenEntity;
import com.mowesta.service.entity.UserEntity;
import com.mowesta.service.session.UserSessionBean;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
@WebServlet(urlPatterns = "/oauth2/token")
public class OAuthTokenServlet extends HttpServlet {
//only authorization code is supported
enum SupportedGrantTypes {
authorization_code ("authorization_code"),
refresh_token ("refresh_token");
private final String identifier;
private SupportedGrantTypes(String s) {
identifier = s;
}
public boolean equals(String other) {
// (otherName == null) check is not needed because name.equals(null) returns false
return identifier.equals(other);
}
public String toString() {
return this.identifier;
}
}
private final List<String> supportedGrantTypes = Arrays.asList("authorization_code, refresh_token");
private static final long timeAccessTokenIsValidInMilliSeconds = 360000;
@Inject
protected EntityManager em;
@Inject
protected UserSessionBean userSessionBean;
Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String code = "";
logger.log(Level.INFO, "Received Token Request - HEADER:");
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
logger.log(Level.INFO,"Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
logger.log(Level.INFO, "Received Authorize Request - PARAMETERS:");
Enumeration<String> parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
logger.log(Level.INFO,"Param Name - " + paramName + ", Value - " + request.getParameter(paramName));
}
logger.log(Level.INFO, "End Token request.");
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()) {
String paramName = params.nextElement();
if (paramName.equals("grant_type")) code = request.getParameter(paramName);
}
//if code is present in request, verify and return refresh/accesstoken pair
if (code.equals("authorization_code")) {
handleAccessCodeRequest(request, response);
} else if (code.equals("refresh_token")) {
handleRefreshTokenRequest(request, response);
}
}
private void handleRefreshTokenRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String grant_type = "";
String client_id = "";
String refresh_token = "";
String code = "";
Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()) {
String paramName = params.nextElement();
if (paramName.equals("grant_type")) grant_type = request.getParameter(paramName);
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
if (paramName.equals("refresh_token")) refresh_token = request.getParameter(paramName);
}
if (Arrays.asList(grant_type, refresh_token).contains("")) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Please provide a refresh token.");
w.close();
throw new UnsupportedJwtException("Request needs to include grant type and refresh_token.");
}
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
//find the current secret to generate an AccessToken
if (!secretKey.isPresent()) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("An error occurred. Please try again.");
w.close();
}
try {
Claims claims = Jwts.parserBuilder().setSigningKey(OAuthAccessCodeServlet.secretKey.getBytes()).build().parseClaimsJws(code).getBody();
String userId = claims.getId();
UserEntity u = userSessionBean.findUser(userId);
if (u == null)
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(userId), "User request for non-existing user.");
String accessToken = createAccessTokenForUser(u, secretKey.get());
long accessTokenExpirationTime = (timeAccessTokenIsValidInMilliSeconds / 1000);
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setAccess_token(accessToken);
tokenResponse.setToken_type("bearer");
tokenResponse.setExpires_in(accessTokenExpirationTime);
Gson gson = new Gson();
String jsonAuthorizationResponse = gson.toJson(tokenResponse);
logger.log(Level.INFO, "Token response: " + tokenResponse.getAccess_token() + " " + tokenResponse.getToken_type() + " " + tokenResponse.getExpires_in());
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write(jsonAuthorizationResponse);
w.close();
} catch (Exception e) {
}
}
private void handleAccessCodeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String grant_type = "";
String client_id = "";
String client_secret = "";
String code = "";
Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()) {
String paramName = params.nextElement();
if (paramName.equals("grant_type")) grant_type = request.getParameter(paramName);
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
if (paramName.equals("code")) code = request.getParameter(paramName);
}
if (Arrays.asList(grant_type, client_id, code).contains("")) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Please provide a client_id and accesscode.");
w.close();
throw new UnsupportedJwtException("Request needs to include client_id, redirect_uri and response_type.");
}
try {
byte[] accessClaimBytes = Base64.getUrlDecoder().decode(code);
String accessClaimString = new String(accessClaimBytes, StandardCharsets.UTF_8);
Claims claims = Jwts.parserBuilder().setSigningKey(OAuthAccessCodeServlet.secretKey.getBytes()).build().parseClaimsJws(accessClaimString).getBody();
if (new Date().after(claims.getExpiration())) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("AccessCode was invalid");
w.close();
throw new UnsupportedJwtException("AccessCode expired.");
}
String userId = claims.getId();
logger.log(Level.INFO, "Claims had userID: " + userId);
UserEntity u = userSessionBean.findUser(userId);
if (u == null)
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(userId), "User request for non-existing user.");
//here we could use client secret to identify service type (for example alexa as service type)
String refreshToken = createRefreshTokenForUser(u);
RefreshTokenEntity refreshTokenEntity = new RefreshTokenEntity();
refreshTokenEntity.setRefreshToken(refreshToken);
refreshTokenEntity.setServiceName("dummy");
userSessionBean.addRefreshTokenToUser(userId, refreshTokenEntity);
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
//find the current secret to generate an AccessToken
if (!secretKey.isPresent()) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("An error occurred. Please try again.");
w.close();
}
String accessToken = createAccessTokenForUser(u, secretKey.get());
long accessTokenExpirationTime = (timeAccessTokenIsValidInMilliSeconds / 1000);
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setAccess_token(accessToken);
tokenResponse.setExpires_in(accessTokenExpirationTime);
tokenResponse.setRefresh_token(refreshToken);
tokenResponse.setToken_type("bearer");
Gson gson = new Gson();
String jsonAuthorizationResponse = gson.toJson(tokenResponse);
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write(jsonAuthorizationResponse);
w.close();
} catch (JwtException | EntityNotFoundException e) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Something went wrong.");
w.close();
throw new UnsupportedJwtException("AccessCode could not be verified.");
}
}
/**
* @return returns an refresh token. The refresh token is signed with a static secret and is mapped to a user
*/
private String createRefreshTokenForUser(UserEntity userEntity) {
Key key = Keys.hmacShaKeyFor(OAuthAccessCodeServlet.secretKey.getBytes());
return Jwts.builder()
.setSubject("mowesta:refresh:token")
.setId(String.valueOf(userEntity.getLogin()))
.setIssuedAt(new Date())
.setNotBefore(new Date())
.signWith(key).compact();
}
/**
* @param userEntity
* @param oAuthSecretEntity
* @return returns an access token. An access token includes a user id and expiration date in his body and is signed with a dynamically changing key.
*/
private String createAccessTokenForUser(UserEntity userEntity, OAuthSecretEntity oAuthSecretEntity) {
Key key = Keys.hmacShaKeyFor(oAuthSecretEntity.getSecret().getBytes());
return Jwts.builder()
.setSubject("mowesta:acess:token")
.setId(String.valueOf(userEntity.getId()))
.setIssuedAt(new Date())
.setNotBefore(new Date())
.setExpiration(new Date(System.currentTimeMillis() + timeAccessTokenIsValidInMilliSeconds))
.signWith(key).compact();
}
private Optional<OAuthSecretEntity> findCurrentValidSecret() {
TypedQuery<OAuthSecretEntity> query = em.createNamedQuery("OAuth.findAllSecrets", OAuthSecretEntity.class);
List<OAuthSecretEntity> oAuthSecretEntityList = query.getResultList();
return oAuthSecretEntityList.stream()
.filter(oAuthSecretEntity -> oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() < System.currentTimeMillis())
.findAny();
}
}
@@ -22,7 +22,6 @@
<filter-name>Resteasy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
@@ -26,7 +26,6 @@ public class WarDeployment {
public static JavaArchive createEjb() {
return mergeLibraries(ShrinkWrap.create(JavaArchive.class, "ejb.jar")) // name used in ear (see application.xml)
.addPackages(true, "org.geojson")
.addPackages(true, "io.jsonwebtoken")
.addPackages(true, "org.apache.commons.compress")
.addPackages(true, "com.mowesta.api")
.addPackages(true, "com.mowesta.data")
+2 -34
View File
@@ -2630,16 +2630,6 @@
"integrity": "sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ==",
"dev": true
},
"bindings": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
"integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
"dev": true,
"optional": true,
"requires": {
"file-uri-to-path": "1.0.0"
}
},
"blob": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/blob/-/blob-0.0.5.tgz",
@@ -5215,13 +5205,6 @@
}
}
},
"file-uri-to-path": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
"dev": true,
"optional": true
},
"fill-range": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
@@ -7911,13 +7894,6 @@
"integrity": "sha512-1t2payD3Y8izfZRq7tfUQlhL2fKzjeLr9v1/2qNCTkEQnd9Abtn1JgzsBgGZubEXh6lM5L8B0iLGoWQiukjtbQ==",
"dev": true
},
"nan": {
"version": "2.14.2",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz",
"integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==",
"dev": true,
"optional": true
},
"nanomatch": {
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz",
@@ -12980,11 +12956,7 @@
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
"dev": true,
"optional": true,
"requires": {
"bindings": "^1.5.0",
"nan": "^2.12.1"
}
"optional": true
},
"glob-parent": {
"version": "3.1.0",
@@ -13661,11 +13633,7 @@
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
"dev": true,
"optional": true,
"requires": {
"bindings": "^1.5.0",
"nan": "^2.12.1"
}
"optional": true
},
"glob-parent": {
"version": "3.1.0",
+127 -346
View File
@@ -1,197 +1,93 @@
import {
ActivateComponent,
ChangeComponent,
LoadingComponent,
LoginComponent,
RegisterComponent,
ResetComponent,
} from "./views-common";
import { AuthInterceptor, DelayInterceptor } from "./interceptors";
import {
BingMapsPipe,
CityTypePipe,
CloudPipe,
DirectionIconPipe,
DirectionPipe,
GoogleMapsPipe,
HumidityPipe,
LocalDatePipe,
LocalNamePipe,
LocalTimePipe,
LocationIconPipe,
MeasurementTypeIconPipe,
MeasurementTypePipe,
OsIconPipe,
PrecipitationPipe,
PressurePipe,
SnowPipe,
SourcePipe,
SpeedPipe,
TemperaturePipe,
VideoSourcePipe,
VideoTypePipe,
WeatherIconPipe,
WeatherPipe,
WikipediaPipe,
} from "./pipes";
import {
BootstrapResolver,
CityResolver,
CountryResolver,
DeviceResolver,
LanguageResolver,
StateResolver,
StationResolver,
UserResolver,
} from "./resolvers";
import {
CitiesComponent,
CityComponent,
ConditionMapComponent,
CountryComponent,
StateComponent,
StationComponent,
StationsComponent,
VideosComponent,
} from "./views-weather";
import {
CitiesListComponent,
WeatherConditionComponent,
WeatherDiagramComponent,
WeatherReportComponent,
WeatherReportsListComponent,
WeatherStationsListComponent,
WeatherSummaryComponent,
WeatherVideoBarComponent,
WeatherVideoComponent,
WeatherVideoListComponent,
} from "./widgets-weather";
import {
CitiesService,
ConsoleService,
CredentialService,
DeviceService,
ManageLogService,
ManageUserService,
MeasurementsService,
ReportsService,
ResourceService,
SettingsService,
StationsService,
UserService,
VersionService,
VideosService,
} from "./services";
import {
ClickButtonComponent,
DecisionPanelComponent,
EmailFieldComponent,
FavoriteButtonComponent,
LanguageSelectComponent,
LocationAutocompleteComponent,
LoginFieldComponent,
LogoPanelComponent,
MapComponent,
NameFieldComponent,
PasswordFieldComponent,
ProfileButtonComponent,
SearchFieldComponent,
ToolbarButtonComponent,
} from "./widgets-common";
import {
CodeDialogComponent,
ConditionsDialogComponent,
ConfirmationDialogComponent,
LogDialogComponent,
MessageDialogComponent,
} from "./dialogs";
import { Configuration, DefaultService } from "./api";
import {
DatePipe,
LocationStrategy,
PathLocationStrategy,
registerLocaleData,
} from "@angular/common";
import {
DrawerComponent,
FooterComponent,
LayoutDoubleComponent,
LayoutDrawerComponent,
LayoutPlainComponent,
LayoutSingleComponent,
} from "./layouts";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { HTTP_INTERCEPTORS, HttpClientModule } from "@angular/common/http";
import { LOCALE_ID, NgModule } from "@angular/core";
import {
ManageLogComponent,
ManageSystemComponent,
ManageUsersComponent,
} from "./views-manage";
import {
MatPaginatorIntl,
MatPaginatorModule,
} from "@angular/material/paginator";
import {
UserAccountComponent,
UserDeviceComponent,
UserDevicesComponent,
UserFavoritesComponent,
} from "./views-user";
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, LOCALE_ID } from '@angular/core';
import { FlexLayoutModule } from '@angular/flex-layout';
import { NgxGaugeModule } from 'ngx-gauge';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatNativeDateModule } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatPaginatorModule, MatPaginatorIntl } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { LocationStrategy, PathLocationStrategy, registerLocaleData, DatePipe } from '@angular/common';
import LocaleDE from '@angular/common/locales/de';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppRoutingModule } from './app.routing';
import { AppComponent } from './app.component';
import { LayoutDrawerComponent, LayoutPlainComponent, DrawerComponent, FooterComponent,
LayoutSingleComponent, LayoutDoubleComponent } from './layouts';
import { ToolbarButtonComponent, DecisionPanelComponent, EmailFieldComponent, LanguageSelectComponent,
LoginFieldComponent, MapComponent, NameFieldComponent, PasswordFieldComponent, ProfileButtonComponent,
SearchFieldComponent, FavoriteButtonComponent, LogoPanelComponent, ClickButtonComponent,
LocationAutocompleteComponent } from './widgets-common';
import { CitiesListComponent, WeatherConditionComponent, WeatherVideoComponent,
WeatherVideoBarComponent, WeatherVideoListComponent, WeatherStationsListComponent, WeatherReportsListComponent,
WeatherReportComponent, WeatherSummaryComponent, WeatherDiagramComponent } from './widgets-weather';
import { LoginComponent, ActivateComponent, ChangeComponent, RegisterComponent, ResetComponent,
LoadingComponent } from './views-common';
import { CitiesComponent, CityComponent, CountryComponent, StateComponent, VideosComponent,
StationsComponent, StationComponent, ConditionMapComponent } from './views-weather';
import { UserAccountComponent, UserDevicesComponent, UserFavoritesComponent, UserDeviceComponent } from './views-user';
import { ManageLogComponent, ManageSystemComponent, ManageUsersComponent } from './views-manage';
import { DelayInterceptor, AuthInterceptor } from './interceptors';
import { DefaultService, Configuration } from './api';
import { MessageDialogComponent, ConfirmationDialogComponent, LogDialogComponent,
ConditionsDialogComponent, CodeDialogComponent } from './dialogs';
import { ConsoleService, UserService, CredentialService, DeviceService, ManageLogService, ManageUserService,
ResourceService, VersionService, CitiesService, VideosService, StationsService, ReportsService,
SettingsService, MeasurementsService } from './services';
import { UseParentFormDirective } from './directives';
import { GermanPaginatorProvider } from './providers/paginator.provider';
import { CityResolver, UserResolver, StateResolver, CountryResolver, StationResolver,
DeviceResolver, LanguageResolver, BootstrapResolver } from './resolvers';
import { HumidityPipe, CloudPipe, PressurePipe, TemperaturePipe, SpeedPipe, SnowPipe, PrecipitationPipe,
WeatherPipe, DirectionPipe, SourcePipe, LocalTimePipe, LocalDatePipe, LocalNamePipe, BingMapsPipe,
GoogleMapsPipe, WikipediaPipe, CityTypePipe, VideoSourcePipe, VideoTypePipe, LocationIconPipe, WeatherIconPipe,
DirectionIconPipe, MeasurementTypePipe, MeasurementTypeIconPipe, OsIconPipe } from './pipes';
import { ManageMeasurementsMapComponent } from './views-manage/manage-measurements-map.component';
import { AccessGrantComponent } from "./views-oauth/access-grant/access-grant.component";
import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app.routing";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { BrowserModule } from "@angular/platform-browser";
import { FlexLayoutModule } from "@angular/flex-layout";
import { GermanPaginatorProvider } from "./providers/paginator.provider";
import LocaleDE from "@angular/common/locales/de";
import { ManageMeasurementsMapComponent } from "./views-manage/manage-measurements-map.component";
import { MatAutocompleteModule } from "@angular/material/autocomplete";
import { MatButtonModule } from "@angular/material/button";
import { MatCardModule } from "@angular/material/card";
import { MatCheckboxModule } from "@angular/material/checkbox";
import { MatDatepickerModule } from "@angular/material/datepicker";
import { MatDialogModule } from "@angular/material/dialog";
import { MatExpansionModule } from "@angular/material/expansion";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatGridListModule } from "@angular/material/grid-list";
import { MatIconModule } from "@angular/material/icon";
import { MatInputModule } from "@angular/material/input";
import { MatListModule } from "@angular/material/list";
import { MatNativeDateModule } from "@angular/material/core";
import { MatProgressBarModule } from "@angular/material/progress-bar";
import { MatProgressSpinnerModule } from "@angular/material/progress-spinner";
import { MatSelectModule } from "@angular/material/select";
import { MatSidenavModule } from "@angular/material/sidenav";
import { MatSnackBarModule } from "@angular/material/snack-bar";
import { MatTableModule } from "@angular/material/table";
import { MatTabsModule } from "@angular/material/tabs";
import { MatToolbarModule } from "@angular/material/toolbar";
import { MatTooltipModule } from "@angular/material/tooltip";
import { NgxGaugeModule } from "ngx-gauge";
import { OAuthLoginComponentComponent } from "./views-oauth/oauth-login-component/oauth-login-component.component";
import { UseParentFormDirective } from "./directives";
/**
* Computes the api domain from the browser location.
*/
const apidomain = (): { http: string; ws: string } => {
const apidomain = (): { http: string, ws: string } => {
const host = document.location.hostname;
const port = document.location.port;
const protocol = document.location.protocol;
let hostportpath = "";
let hostportpath = '';
if (port.length > 0) {
hostportpath = "://" + host + ":" + port + "/api";
hostportpath = '://' + host + ':' + port + '/api';
} else {
hostportpath = "://" + host + "/api";
hostportpath = '://' + host + '/api';
}
const secure = protocol !== "http:" ? "s" : "";
return {
http: "http" + secure + hostportpath,
ws: "ws" + secure + hostportpath,
};
const secure = (protocol !== 'http:') ? 's' : '';
return { http: 'http' + secure + hostportpath, ws: 'ws' + secure + hostportpath };
};
/**
@@ -201,180 +97,65 @@ registerLocaleData(LocaleDE);
@NgModule({
declarations: [
AppComponent,
FooterComponent,
LayoutDrawerComponent,
LayoutPlainComponent,
LayoutSingleComponent,
AppComponent, FooterComponent, LayoutDrawerComponent, LayoutPlainComponent, LayoutSingleComponent,
LayoutDoubleComponent,
ToolbarButtonComponent,
ProfileButtonComponent,
LanguageSelectComponent,
DrawerComponent,
LoginFieldComponent,
PasswordFieldComponent,
EmailFieldComponent,
NameFieldComponent,
DecisionPanelComponent,
MessageDialogComponent,
ConfirmationDialogComponent,
ConditionsDialogComponent,
LogoPanelComponent,
LoginComponent,
RegisterComponent,
ActivateComponent,
ResetComponent,
ChangeComponent,
UserDevicesComponent,
UserAccountComponent,
ManageLogComponent,
LogDialogComponent,
ManageSystemComponent,
ManageUsersComponent,
SearchFieldComponent,
CityComponent,
CountryComponent,
StateComponent,
MapComponent,
WeatherConditionComponent,
CitiesListComponent,
CitiesComponent,
WeatherVideoListComponent,
WeatherVideoComponent,
WeatherVideoBarComponent,
VideosComponent,
WeatherStationsListComponent,
StationsComponent,
StationComponent,
WeatherReportsListComponent,
WeatherReportComponent,
WeatherSummaryComponent,
UserFavoritesComponent,
FavoriteButtonComponent,
LoadingComponent,
UserDeviceComponent,
WeatherDiagramComponent,
HumidityPipe,
CloudPipe,
PressurePipe,
TemperaturePipe,
SpeedPipe,
SnowPipe,
PrecipitationPipe,
WeatherPipe,
DirectionPipe,
SourcePipe,
BingMapsPipe,
GoogleMapsPipe,
WikipediaPipe,
LocalTimePipe,
LocalDatePipe,
LocalNamePipe,
LocationIconPipe,
CityTypePipe,
VideoSourcePipe,
VideoTypePipe,
WeatherIconPipe,
DirectionIconPipe,
OsIconPipe,
MeasurementTypePipe,
MeasurementTypeIconPipe,
UseParentFormDirective,
ClickButtonComponent,
CodeDialogComponent,
ConditionMapComponent,
LocationAutocompleteComponent,
ManageMeasurementsMapComponent,
OAuthLoginComponentComponent,
AccessGrantComponent,
ToolbarButtonComponent, ProfileButtonComponent, LanguageSelectComponent,
DrawerComponent, LoginFieldComponent, PasswordFieldComponent, EmailFieldComponent,
NameFieldComponent, DecisionPanelComponent, MessageDialogComponent, ConfirmationDialogComponent,
ConditionsDialogComponent, LogoPanelComponent,
LoginComponent, RegisterComponent, ActivateComponent, ResetComponent, ChangeComponent,
UserDevicesComponent, UserAccountComponent, ManageLogComponent, LogDialogComponent, ManageSystemComponent,
ManageUsersComponent, SearchFieldComponent, CityComponent, CountryComponent, StateComponent,
MapComponent, WeatherConditionComponent, CitiesListComponent, CitiesComponent, WeatherVideoListComponent,
WeatherVideoComponent, WeatherVideoBarComponent, VideosComponent,
WeatherStationsListComponent, StationsComponent, StationComponent, WeatherReportsListComponent,
WeatherReportComponent, WeatherSummaryComponent, UserFavoritesComponent, FavoriteButtonComponent,
LoadingComponent, UserDeviceComponent, WeatherDiagramComponent,
HumidityPipe, CloudPipe, PressurePipe, TemperaturePipe, SpeedPipe, SnowPipe, PrecipitationPipe,
WeatherPipe, DirectionPipe, SourcePipe, BingMapsPipe, GoogleMapsPipe, WikipediaPipe, LocalTimePipe,
LocalDatePipe, LocalNamePipe, LocationIconPipe, CityTypePipe, VideoSourcePipe, VideoTypePipe,
WeatherIconPipe, DirectionIconPipe, OsIconPipe, MeasurementTypePipe, MeasurementTypeIconPipe,
UseParentFormDirective, ClickButtonComponent, CodeDialogComponent, ConditionMapComponent, LocationAutocompleteComponent, ManageMeasurementsMapComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
FlexLayoutModule,
NgxGaugeModule,
HttpClientModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatPaginatorModule,
MatExpansionModule,
MatTableModule,
MatButtonModule,
MatInputModule,
MatFormFieldModule,
MatListModule,
MatIconModule,
MatCardModule,
MatSelectModule,
MatSnackBarModule,
MatTooltipModule,
MatToolbarModule,
MatSidenavModule,
MatProgressBarModule,
MatDialogModule,
MatCheckboxModule,
MatDatepickerModule,
MatNativeDateModule,
MatTabsModule,
MatGridListModule,
AppRoutingModule,
MatAutocompleteModule,
BrowserModule, BrowserAnimationsModule,
FormsModule, ReactiveFormsModule,
FlexLayoutModule, NgxGaugeModule,
HttpClientModule, MatProgressBarModule,
MatProgressSpinnerModule, MatPaginatorModule,
MatExpansionModule, MatTableModule,
MatButtonModule, MatInputModule,
MatFormFieldModule, MatListModule,
MatIconModule, MatCardModule,
MatSelectModule, MatSnackBarModule,
MatTooltipModule, MatToolbarModule,
MatSidenavModule, MatProgressBarModule,
MatDialogModule, MatCheckboxModule,
MatDatepickerModule, MatNativeDateModule,
MatTabsModule, MatGridListModule,
AppRoutingModule, MatAutocompleteModule
],
providers: [
// injection token for http client
{
provide: Configuration,
useValue: new Configuration({ basePath: apidomain().http }),
},
{ provide: "wsdomain", useValue: apidomain().ws },
{ provide: Configuration, useValue: new Configuration({ basePath: apidomain().http }) },
{ provide: 'wsdomain', useValue: apidomain().ws },
// location stategy for passing that with the router
{ provide: LocationStrategy, useClass: PathLocationStrategy },
// add two global interceptors (one two slow down the server and one for authentication)
// {provide: HTTP_INTERCEPTORS, useClass: DelayInterceptor, multi: true},
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true},
// change the locale to DE and add custom paginator provider for tables
{ provide: LOCALE_ID, useValue: "de" },
{ provide: LOCALE_ID, useValue: 'de' },
{ provide: MatPaginatorIntl, useClass: GermanPaginatorProvider },
DatePipe,
LocalNamePipe,
LocalDatePipe,
LocalTimePipe,
HumidityPipe,
PressurePipe,
TemperaturePipe,
DatePipe, LocalNamePipe, LocalDatePipe, LocalTimePipe, HumidityPipe, PressurePipe, TemperaturePipe,
// add our application services (api access, logging, authentication)
DefaultService,
ConsoleService,
UserResolver,
CityResolver,
StateResolver,
CountryResolver,
StationResolver,
DeviceResolver,
LanguageResolver,
BootstrapResolver,
ResourceService,
CredentialService,
UserService,
VersionService,
DeviceService,
MeasurementsService,
ManageLogService,
ManageUserService,
CitiesService,
VideosService,
StationsService,
ReportsService,
SettingsService,
],
entryComponents: [
MessageDialogComponent,
ConfirmationDialogComponent,
LogDialogComponent,
ConditionsDialogComponent,
],
bootstrap: [AppComponent],
DefaultService, ConsoleService, UserResolver, CityResolver, StateResolver, CountryResolver, StationResolver,
DeviceResolver, LanguageResolver, BootstrapResolver,
ResourceService, CredentialService, UserService, VersionService, DeviceService, MeasurementsService,
ManageLogService, ManageUserService, CitiesService, VideosService, StationsService, ReportsService,
SettingsService
],
entryComponents: [MessageDialogComponent, ConfirmationDialogComponent, LogDialogComponent, ConditionsDialogComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
export class AppModule { }
+67 -175
View File
@@ -1,190 +1,82 @@
import {
ActivateComponent,
ChangeComponent,
LoadingComponent,
LoginComponent,
RegisterComponent,
ResetComponent,
} from "./views-common";
import {
BootstrapResolver,
CityResolver,
CountryResolver,
DeviceResolver,
LanguageResolver,
StateResolver,
StationResolver,
UserResolver,
} from "./resolvers";
import {
CitiesComponent,
CityComponent,
ConditionMapComponent,
CountryComponent,
StateComponent,
StationComponent,
StationsComponent,
VideosComponent,
} from "./views-weather";
import {
ManageLogComponent,
ManageSystemComponent,
ManageUsersComponent,
} from "./views-manage";
import { RouterModule, Routes } from "@angular/router";
import {
UserAccountComponent,
UserDeviceComponent,
UserDevicesComponent,
UserFavoritesComponent,
} from "./views-user";
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccessGrantComponent } from "./views-oauth/access-grant/access-grant.component";
import { CanDeactivateGuard } from "./guards/can-deactivate.guard";
// Import custom pages
import { LayoutDrawerComponent } from "./layouts";
import { LayoutDrawerComponent } from './layouts';
import { LoginComponent, RegisterComponent, ActivateComponent, ChangeComponent, ResetComponent, LoadingComponent } from './views-common';
import { CityComponent, StateComponent, CountryComponent, CitiesComponent, VideosComponent,
StationsComponent, StationComponent, ConditionMapComponent } from './views-weather';
import { UserDevicesComponent, UserAccountComponent, UserFavoritesComponent, UserDeviceComponent } from './views-user';
import { ManageLogComponent, ManageSystemComponent, ManageUsersComponent } from './views-manage';
import { CityResolver, StateResolver, CountryResolver, UserResolver, StationResolver, LanguageResolver,
BootstrapResolver, DeviceResolver } from './resolvers';
import { CanDeactivateGuard } from "./guards/can-deactivate.guard";
import { ManageMeasurementsMapComponent } from "./views-manage/manage-measurements-map.component";
import { NgModule } from "@angular/core";
import { OAuthLoginComponentComponent } from "./views-oauth/oauth-login-component/oauth-login-component.component";
export const routes: Routes = [
// backwards compatibility
{
path: "activate/:token",
resolve: { bs: BootstrapResolver },
component: LoadingComponent,
},
{
path: "reset/:token",
resolve: { bs: BootstrapResolver },
component: LoadingComponent,
},
{ path: "loading", component: LoadingComponent },
{ path: "oauth/login", component: OAuthLoginComponentComponent },
{ path: "oauth/grant", component: AccessGrantComponent },
// main app routing
{
path: ":lang",
component: LayoutDrawerComponent,
resolve: { user: UserResolver, lang: LanguageResolver },
children: [
// backwards compatibility
{ path: 'activate/:token', resolve: { bs: BootstrapResolver}, component: LoadingComponent },
{ path: 'reset/:token', resolve: { bs: BootstrapResolver}, component: LoadingComponent },
{ path: 'loading', component: LoadingComponent },
// main app routing
{ path: ':lang', component: LayoutDrawerComponent, resolve: { user: UserResolver, lang: LanguageResolver }, children: [
/// administrative functions
{
path: "manage",
children: [
{ path: "logs", component: ManageLogComponent },
{ path: "system", component: ManageSystemComponent },
{ path: "users", component: ManageUsersComponent },
{
path: "measurements",
component: ManageMeasurementsMapComponent,
canDeactivate: [CanDeactivateGuard],
},
{ path: "**", redirectTo: "/manage/system" },
],
},
{ path: 'manage', children: [
{ path: 'logs', component: ManageLogComponent },
{ path: 'system', component: ManageSystemComponent },
{ path: 'users', component: ManageUsersComponent },
{ path: 'measurements', component: ManageMeasurementsMapComponent, canDeactivate: [CanDeactivateGuard] },
{ path: '**', redirectTo: '/manage/system' }
]},
// user functions
{
path: "user",
children: [
{
path: "devices",
children: [
{
path: ":id",
component: UserDeviceComponent,
resolve: { device: DeviceResolver },
},
{ path: "**", component: UserDevicesComponent },
],
},
{
path: "account",
component: UserAccountComponent,
canDeactivate: [CanDeactivateGuard],
},
{ path: "favorites", component: UserFavoritesComponent },
{ path: "**", redirectTo: "/user/account" },
],
},
{ path: 'user', children: [
{ path: 'devices', children: [
{ path: ':id', component: UserDeviceComponent, resolve: { device: DeviceResolver } },
{ path: '**', component: UserDevicesComponent },
] },
{ path: 'account', component: UserAccountComponent, canDeactivate: [CanDeactivateGuard] },
{ path: 'favorites', component: UserFavoritesComponent },
{ path: '**', redirectTo: '/user/account' }
]},
// weather functions
{
path: "weather",
children: [
{ path: "map", component: ConditionMapComponent },
{
path: "cities",
children: [
{
path: ":id",
component: CityComponent,
resolve: { city: CityResolver },
},
{ path: "**", component: CitiesComponent },
],
},
{
path: "states",
children: [
{
path: ":id",
component: StateComponent,
resolve: { state: StateResolver },
},
],
},
{
path: "countries",
children: [
{
path: ":id",
component: CountryComponent,
resolve: { country: CountryResolver },
},
],
},
{
path: "stations",
children: [
{
path: ":id",
component: StationComponent,
resolve: { station: StationResolver },
},
{ path: "**", component: StationsComponent },
],
},
{ path: "videos", component: VideosComponent },
],
},
{ path: 'weather', children: [
{ path: 'map', component: ConditionMapComponent },
{ path: 'cities', children: [
{ path: ':id', component: CityComponent, resolve: { city: CityResolver } },
{ path: '**', component: CitiesComponent },
]},
{ path: 'states', children: [
{ path: ':id', component: StateComponent, resolve: { state: StateResolver } }
]},
{ path: 'countries', children: [
{ path: ':id', component: CountryComponent, resolve: { country: CountryResolver } }
]},
{ path: 'stations', children: [
{ path: ':id', component: StationComponent, resolve: { station: StationResolver } },
{ path: '**', component: StationsComponent },
]},
{ path: 'videos', component: VideosComponent },
]},
// common functions
{ path: "login", component: LoginComponent },
{ path: "register", component: RegisterComponent },
{
path: "reset",
children: [
{ path: "", component: ResetComponent },
{ path: ":token", component: ChangeComponent },
],
},
{
path: "activate",
children: [{ path: ":token", component: ActivateComponent }],
},
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'reset', children: [
{ path: '', component: ResetComponent },
{ path: ':token', component: ChangeComponent }
]},
{ path: 'activate', children: [
{ path: ':token', component: ActivateComponent }
] },
// catch all
{ path: "**", redirectTo: "weather/map" },
],
},
// catch all, redirect to browser language
{
path: "**",
resolve: { bs: BootstrapResolver },
component: LoadingComponent,
},
{ path: '**', redirectTo: 'weather/map' }
]},
// catch all, redirect to browser language
{ path: '**', resolve: { bs: BootstrapResolver}, component: LoadingComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes, { relativeLinkResolution: "legacy" })],
exports: [RouterModule],
imports: [ RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' }) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
@@ -1,55 +0,0 @@
import { Inject, Injectable } from "@angular/core";
import { DOCUMENT } from '@angular/common';
import { DefaultService } from "../../api/api/default.service";
import { HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable({
providedIn: "root",
})
export class OAuthService {
public client_id: string = "";
public redirect_uri: string = "";
public response_type: string = "";
public scope: string = "";
public state: string = "";
private accessCode: string;
constructor(private apiClientService: DefaultService) {}
public getAccessCode(): void {
this.apiClientService
.getAccessCode(
this.client_id,
this.redirect_uri,
this.response_type,
this.state,
this.scope,
)
.subscribe((val) => {
this.accessCode = val.accessCode;
this.redirect();
/**
this.apiClientService
.getAccessRefreshTokenPairFromAccessCode(
"code",
"1222",
"312525",
val.accessCode
)
.subscribe((val) => {
console.log(val);
});
*/
});
}
private redirect(): void {
const url: string = this.redirect_uri + "?state=" + this.state + "&code=" + this.accessCode;
console.log("Redirecting to: ", url)
window.location.href = url;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,33 +0,0 @@
<div class="fx-fill fx-column fx-stretch fx-mh100">
<app-layout-single class="fx-fill fx-row fx-stretch">
<div id="main" class="fx-column">
<div class="mat-typography">
<h2>
{{ res.strings("oauth_grant_title") }}
</h2>
<p>
{{ res.strings("oauth_grant_body") }}
</p>
</div>
<div
class="fx-row"
style="justify-content: space-around; align-items: center"
>
<button
#grantAcessButton
mat-raised-button
color="accent"
(click)="onGrantAcess()"
>
<mat-icon class="icon-button">lock_open</mat-icon>
<span>{{ res.strings("oauth_grant_button_grant") }}</span>
</button>
<button #dismissAcessButton mat-raised-button color="primary">
<mat-icon class="icon-button">clear</mat-icon>
<span>{{ res.strings("oauth_grant_button_dismiss") }}</span>
</button>
</div>
</div>
</app-layout-single>
<app-footer></app-footer>
</div>
@@ -1,24 +0,0 @@
import { Component, OnInit } from "@angular/core";
import { DefaultService } from "../../../api/api/default.service";
import { HttpClient } from "@angular/common/http";
import { OAuthService } from "../../services/oauth.service";
import { ResourceService } from "../../services";
@Component({
selector: "app-access-grant",
templateUrl: "./access-grant.component.html",
})
export class AccessGrantComponent implements OnInit {
constructor(
public res: ResourceService,
private oAuthService: OAuthService,
private apiClientService: DefaultService
) {}
ngOnInit(): void {}
onGrantAcess(): void {
this.oAuthService.getAccessCode();
}
}
@@ -1,39 +0,0 @@
<div class="fx-fill fx-column fx-stretch fx-mh100">
<app-layout-single class="fx-fill fx-row fx-stretch">
<div id="main" class="fx-column">
<div class="m-lg mat-typography">
<h2>{{ res.strings("login_login_title") }}</h2>
<h4>{{ res.strings("oauth_login_subtitle") }}</h4>
<form #loginForm="ngForm">
<app-login-field class="mb-sm" [login]="login"></app-login-field>
<app-password-field
class="mb-lg"
[password]="password"
(keyup.enter)="loginForm.valid && onLogin()"
></app-password-field>
</form>
<div
class="fx-row"
style="justify-content: space-around; align-items: center"
>
<ng-container *ngIf="idle | async as submittable; else progressBar">
<button
#loginButton
mat-raised-button
color="accent"
[disabled]="!submittable || loginForm.invalid"
(click)="onLogin()"
>
<mat-icon class="icon-button">open_in_browser</mat-icon>
<span>{{ res.strings("button_login") }}</span>
</button>
</ng-container>
<ng-template #progressBar>
<mat-spinner [diameter]="36"></mat-spinner>
</ng-template>
</div>
</div>
</div>
</app-layout-single>
<app-footer></app-footer>
</div>
@@ -1,89 +0,0 @@
import { ActivatedRoute, Router } from "@angular/router";
import { BehaviorSubject, Subscription } from "rxjs";
import { Component, HostListener, OnInit, ViewChild } from "@angular/core";
import { HttpStatusCode, Snackbars } from "../../utils";
import {
LoginFieldComponent,
PasswordFieldComponent,
} from "../../widgets-common";
import { ResourceService, UserService, UserState } from "../../services";
import { MatSnackBar } from "@angular/material/snack-bar";
import { NgForm } from "@angular/forms";
import { OAuthService } from "../../services/oauth.service";
@Component({
selector: "app-oauth-login-component",
templateUrl: "./oauth-login-component.component.html",
})
export class OAuthLoginComponentComponent implements OnInit {
login: string;
password: string;
readonly idle = new BehaviorSubject<boolean>(false);
@ViewChild(LoginFieldComponent, { static: true })
loginField: LoginFieldComponent;
@ViewChild(PasswordFieldComponent, { static: true })
passwordField: PasswordFieldComponent;
@ViewChild("loginForm", { static: true }) loginForm: NgForm;
private errorSubscription: Subscription;
private stateSubscription: Subscription;
constructor(
public res: ResourceService,
private snackbar: MatSnackBar,
private oAuthService: OAuthService,
private userService: UserService,
private router: Router,
private route: ActivatedRoute
) {}
ngOnInit(): void {
this.route.queryParams.subscribe((params) => {
this.oAuthService.client_id = params["client_id"];
this.oAuthService.redirect_uri = params["redirect_uri"];
this.oAuthService.response_type = params["response_type"];
this.oAuthService.scope = params["scope"];
this.oAuthService.state = params["state"];
});
this.stateSubscription = this.userService.state.subscribe((state) => {
if (state === UserState.Available) {
this.idle.next(false);
const url = "/oauth/grant";
this.router.navigateByUrl(url);
} else {
this.idle.next(state !== UserState.Changing);
this.loginField.disabled = !this.idle.getValue();
this.loginField.disabled = !this.idle.getValue();
}
});
this.errorSubscription = this.userService.error.subscribe((error) => {
this.password = "";
if (error.status === HttpStatusCode.FORBIDDEN) {
Snackbars.showError(
this.snackbar,
"Zugriff verweigert. Prüf Deine Eingaben und versuchs nochmal."
);
} else {
Snackbars.showError(
this.snackbar,
"Fehler bei der Anmeldung (" +
error.status +
"). Hast Du gerade kein Netz?"
);
}
});
}
onLogin(): void {
this.snackbar.dismiss();
if (!this.idle || !this.loginForm.valid) {
return;
}
this.login = this.loginField.login;
this.password = this.passwordField.password;
this.userService.setUser(this.login, this.password);
this.userService.login();
}
}
@@ -1,278 +1,233 @@
import {
Component,
Input,
OnChanges,
OnInit,
SimpleChanges,
} from "@angular/core";
import { LocalDatePipe, LocalTimePipe } from "../pipes/location.pipes";
import { ConditionsDialogComponent } from "../dialogs/conditions-dialog.component";
import { MatDialog } from "@angular/material/dialog";
import { ResourceService } from "../services/resource.service";
import { WeatherCondition } from "../api";
import { Component, Input, OnChanges, SimpleChanges, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ResourceService } from '../services/resource.service';
import { WeatherCondition } from '../api';
import { LocalTimePipe, LocalDatePipe } from '../pipes/location.pipes';
import { ConditionsDialogComponent } from '../dialogs/conditions-dialog.component';
/**
* Implements a component to display a single
* weather condition.
*/
@Component({
selector: "app-weather-summary",
templateUrl: "./weather-summary.component.html",
selector: 'app-weather-summary',
templateUrl: './weather-summary.component.html'
})
export class WeatherSummaryComponent implements OnInit, OnChanges {
@Input() conditions: WeatherCondition[];
@Input() timezone: string;
@Input() title: string;
@Input() subtitle: string;
@Input() clickHandler: () => void;
@Input() noMargin: boolean;
@Input() concise: boolean;
min: WeatherCondition = null;
max: WeatherCondition = null;
displayTitle = "";
displaySubtitle = "";
@Input() conditions: WeatherCondition[];
@Input() timezone: string;
@Input() title: string;
@Input() subtitle: string;
@Input() clickHandler: () => void;
@Input() noMargin: boolean;
@Input() concise: boolean;
constructor(
public res: ResourceService,
private localTime: LocalTimePipe,
private localDate: LocalDatePipe,
private dialog: MatDialog
) {}
min: WeatherCondition = null;
max: WeatherCondition = null;
displayTitle = '';
displaySubtitle = '';
hasCondition() {
return this.min != null && this.max != null;
}
constructor(
public res: ResourceService,
private localTime: LocalTimePipe,
private localDate: LocalDatePipe,
private dialog: MatDialog
) { }
ngOnInit(): void {
if (!this.clickHandler) {
this.clickHandler = () => {
ConditionsDialogComponent.open(
this.dialog,
this.conditions,
this.timezone
);
};
hasCondition() {
return this.min != null && this.max != null;
}
}
ngOnChanges(c: SimpleChanges) {
if (
c.conditions &&
c.conditions.currentValue != null &&
c.conditions.currentValue.length > 0
) {
this.min = this.copyCondition(c.conditions.currentValue[0]);
this.max = this.copyCondition(c.conditions.currentValue[0]);
for (let i = 1; i < c.conditions.currentValue.length; i++) {
const next = c.conditions.currentValue[i];
// compute maximum
this.max.cloudCoverage = Math.max(
this.max.cloudCoverage,
next.cloudCoverage
);
this.max.cloudDepth = Math.max(this.max.cloudDepth, next.cloudDepth);
this.max.duration = Math.max(this.max.duration, next.duration);
this.max.hour = Math.max(this.max.duration, next.duration);
this.max.humidity = Math.max(this.max.humidity, next.humidity);
this.max.precipitation = Math.max(
this.max.precipitation,
next.precipitation
);
this.max.pressure = Math.max(this.max.pressure, next.pressure);
this.max.snowDepth = Math.max(this.max.snowDepth, next.snowDepth);
this.max.temperature = Math.max(this.max.temperature, next.temperature);
this.max.time = Math.max(this.max.time, next.time);
this.max.source = this.maximum(
this.max.source,
next.source,
this.sourceValue
);
this.max.type = this.maximum(this.max.type, next.type, this.typeValue);
if (next.windSpeed > this.max.windSpeed) {
this.max.windSpeed = next.windSpeed;
this.max.windDirection = next.windDirection;
ngOnInit(): void {
if (!this.clickHandler) {
this.clickHandler = () => {
ConditionsDialogComponent.open(this.dialog, this.conditions, this.timezone);
};
}
// compute minimum
this.min.cloudCoverage = Math.min(
this.min.cloudCoverage,
next.cloudCoverage
);
this.min.cloudDepth = Math.min(this.min.cloudDepth, next.cloudDepth);
this.min.duration = Math.min(this.min.duration, next.duration);
this.min.hour = Math.min(this.min.duration, next.duration);
this.min.humidity = Math.min(this.min.humidity, next.humidity);
this.min.precipitation = Math.min(
this.min.precipitation,
next.precipitation
);
this.min.pressure = Math.min(this.min.pressure, next.pressure);
this.min.snowDepth = Math.min(this.min.snowDepth, next.snowDepth);
this.min.temperature = Math.min(this.min.temperature, next.temperature);
this.min.time = Math.min(this.min.time, next.time);
this.min.source = this.minimum(
this.min.source,
next.source,
this.sourceValue
);
this.min.type = this.minimum(this.min.type, next.type, this.typeValue);
if (next.windSpeed < this.min.windSpeed) {
this.min.windSpeed = next.windSpeed;
this.min.windDirection = next.windDirection;
}
ngOnChanges(c: SimpleChanges) {
if (c.conditions && c.conditions.currentValue != null && c.conditions.currentValue.length > 0) {
this.min = this.copyCondition(c.conditions.currentValue[0]);
this.max = this.copyCondition(c.conditions.currentValue[0]);
for (let i = 1; i < c.conditions.currentValue.length; i++) {
const next = c.conditions.currentValue[i];
// compute maximum
this.max.cloudCoverage = Math.max(this.max.cloudCoverage, next.cloudCoverage);
this.max.cloudDepth = Math.max(this.max.cloudDepth, next.cloudDepth);
this.max.duration = Math.max(this.max.duration, next.duration);
this.max.hour = Math.max(this.max.duration, next.duration);
this.max.humidity = Math.max(this.max.humidity, next.humidity);
this.max.precipitation = Math.max(this.max.precipitation, next.precipitation);
this.max.pressure = Math.max(this.max.pressure, next.pressure);
this.max.snowDepth = Math.max(this.max.snowDepth, next.snowDepth);
this.max.temperature = Math.max(this.max.temperature, next.temperature);
this.max.time = Math.max(this.max.time, next.time);
this.max.source = this.maximum(this.max.source, next.source, this.sourceValue);
this.max.type = this.maximum(this.max.type, next.type, this.typeValue);
if (next.windSpeed > this.max.windSpeed) {
this.max.windSpeed = next.windSpeed;
this.max.windDirection = next.windDirection;
}
// compute minimum
this.min.cloudCoverage = Math.min(this.min.cloudCoverage, next.cloudCoverage);
this.min.cloudDepth = Math.min(this.min.cloudDepth, next.cloudDepth);
this.min.duration = Math.min(this.min.duration, next.duration);
this.min.hour = Math.min(this.min.duration, next.duration);
this.min.humidity = Math.min(this.min.humidity, next.humidity);
this.min.precipitation = Math.min(this.min.precipitation, next.precipitation);
this.min.pressure = Math.min(this.min.pressure, next.pressure);
this.min.snowDepth = Math.min(this.min.snowDepth, next.snowDepth);
this.min.temperature = Math.min(this.min.temperature, next.temperature);
this.min.time = Math.min(this.min.time, next.time);
this.min.source = this.minimum(this.min.source, next.source, this.sourceValue);
this.min.type = this.minimum(this.min.type, next.type, this.typeValue);
if (next.windSpeed < this.min.windSpeed) {
this.min.windSpeed = next.windSpeed;
this.min.windDirection = next.windDirection;
}
}
} else {
this.min = null;
this.max = null;
}
}
} else {
this.min = null;
this.max = null;
this.updateTitle();
}
this.updateTitle();
}
private updateTitle() {
if (this.title && this.title != null) {
this.displayTitle = this.title;
} else if (this.hasCondition()) {
const minDate = this.localDate.transform(this.min.time, this.timezone);
const maxDate = this.localDate.transform(this.max.time, this.timezone);
if (minDate === maxDate) {
this.displayTitle = minDate;
} else {
this.displayTitle = minDate + " - " + maxDate;
}
} else {
this.displayTitle = "";
private updateTitle() {
if (this.title && this.title != null) {
this.displayTitle = this.title;
} else if (this.hasCondition()) {
const minDate = this.localDate.transform(this.min.time, this.timezone);
const maxDate = this.localDate.transform(this.max.time, this.timezone);
if (minDate === maxDate) {
this.displayTitle = minDate;
} else {
this.displayTitle = minDate + ' - ' + maxDate;
}
} else {
this.displayTitle = '';
}
if (this.subtitle && this.subtitle != null) {
this.displaySubtitle = this.subtitle;
} else if (this.hasCondition()) {
const minTime = this.localTime.transform(this.min.time, this.timezone);
const maxTime = this.localTime.transform(this.max.time, this.timezone);
if (minTime === maxTime) {
this.displaySubtitle = minTime;
} else {
this.displaySubtitle = minTime + ' - ' + maxTime;
}
} else {
this.displaySubtitle = '';
}
}
if (this.subtitle && this.subtitle != null) {
this.displaySubtitle = this.subtitle;
} else if (this.hasCondition()) {
const minTime = this.localTime.transform(this.min.time, this.timezone);
const maxTime = this.localTime.transform(this.max.time, this.timezone);
if (minTime === maxTime) {
this.displaySubtitle = minTime;
} else {
this.displaySubtitle = minTime + " - " + maxTime;
}
} else {
this.displaySubtitle = "";
private copyCondition(c: WeatherCondition): WeatherCondition {
return { cloudCoverage: c.cloudCoverage, cloudDepth: c.cloudDepth, duration: c.duration, hour: c.hour,
humidity: c.humidity, precipitation: c.precipitation, pressure: c.pressure, snowDepth: c.snowDepth,
source: c.source, temperature: c.temperature, time: c.time, type: c.type, windDirection: c.windDirection,
windSpeed: c.windSpeed };
}
}
private copyCondition(c: WeatherCondition): WeatherCondition {
return {
cloudCoverage: c.cloudCoverage,
cloudDepth: c.cloudDepth,
duration: c.duration,
hour: c.hour,
humidity: c.humidity,
precipitation: c.precipitation,
pressure: c.pressure,
snowDepth: c.snowDepth,
source: c.source,
temperature: c.temperature,
time: c.time,
type: c.type,
windDirection: c.windDirection,
windSpeed: c.windSpeed,
maxWindSpeed: c.maxWindSpeed,
};
}
private maximum<T>(a: T, b: T, v: (T) => number): T {
const va = v(a);
const vb = v(b);
if (va >= vb && va >= 0) {
return a;
} else {
return b;
private maximum<T>(a: T, b: T, v: (T) => number): T {
const va = v(a);
const vb = v(b);
if (va >= vb && va >= 0) {
return a;
} else {
return b;
}
}
}
private minimum<T>(a: T, b: T, v: (T) => number): T {
const va = v(a);
const vb = v(b);
if (va <= vb && va >= 0) {
return a;
} else {
return b;
private minimum<T>(a: T, b: T, v: (T) => number): T {
const va = v(a);
const vb = v(b);
if (va <= vb && va >= 0) {
return a;
} else {
return b;
}
}
}
private sourceValue(s: WeatherCondition.SourceEnum): number {
switch (s) {
case WeatherCondition.SourceEnum.ICONGLOBAL:
return 2;
case WeatherCondition.SourceEnum.ICONEUROPE:
return 1;
case WeatherCondition.SourceEnum.COSMOEUROPE:
return 0;
default:
return -1;
private sourceValue(s: WeatherCondition.SourceEnum): number {
switch (s) {
case WeatherCondition.SourceEnum.ICONGLOBAL:
return 2;
case WeatherCondition.SourceEnum.ICONEUROPE:
return 1;
case WeatherCondition.SourceEnum.COSMOEUROPE:
return 0;
default:
return -1;
}
}
}
private typeValue(t: WeatherCondition.TypeEnum): number {
switch (t) {
case WeatherCondition.TypeEnum.CLEARSKY:
return 0;
case WeatherCondition.TypeEnum.MAINLYCLEAR:
return 1;
case WeatherCondition.TypeEnum.PARTLYCLOUDY:
return 2;
case WeatherCondition.TypeEnum.CLOUDY:
return 3;
case WeatherCondition.TypeEnum.FOG:
return 4;
case WeatherCondition.TypeEnum.FOGDEPOSITINGRIME:
return 5;
case WeatherCondition.TypeEnum.SLIGHTDRIZZLE:
return 6;
case WeatherCondition.TypeEnum.SLIGHTRAINNOTFREEZING:
return 7;
case WeatherCondition.TypeEnum.RAINSHOWERSLIGHT:
return 8;
case WeatherCondition.TypeEnum.DRIZZLEFREEZINGSLIGHT:
return 9;
case WeatherCondition.TypeEnum.RAINFREEZINGSLIGHT:
return 10;
case WeatherCondition.TypeEnum.SLIGHTFALLOFSNOWFLAKES:
return 11;
case WeatherCondition.TypeEnum.SNOWSHOWERSLIGHT:
return 12;
case WeatherCondition.TypeEnum.MODERATEDRIZZLE:
return 13;
case WeatherCondition.TypeEnum.HEAVYDRIZZLE:
return 14;
case WeatherCondition.TypeEnum.MODERATERAINNOTFREEZING:
return 15;
case WeatherCondition.TypeEnum.SNOWGRAINS:
return 16;
case WeatherCondition.TypeEnum.MODERATEFALLOFSNOWFLAKES:
return 17;
case WeatherCondition.TypeEnum.HEAVYRAINNOTFREEZING:
return 18;
case WeatherCondition.TypeEnum.DRIZZLEFREEZINGMODERATEHEAVY:
return 19;
case WeatherCondition.TypeEnum.HEAVYFALLOFSNOWFLAKES:
return 20;
case WeatherCondition.TypeEnum.RAINSHOWERMODERATEHEAVY:
return 21;
case WeatherCondition.TypeEnum.RAINFREEZINGMODERATEHEAVY:
return 22;
case WeatherCondition.TypeEnum.SNOWSHOWERMODERATEHEAVY:
return 23;
case WeatherCondition.TypeEnum.RAINSHOWERVIOLENT:
return 24;
case WeatherCondition.TypeEnum.THUNDERSTORMSLIGHTMODERATE:
return 25;
case WeatherCondition.TypeEnum.THUNDERSTORMHAILHEAVY:
return 26;
default:
return -1;
private typeValue(t: WeatherCondition.TypeEnum): number {
switch (t) {
case WeatherCondition.TypeEnum.CLEARSKY:
return 0;
case WeatherCondition.TypeEnum.MAINLYCLEAR:
return 1;
case WeatherCondition.TypeEnum.PARTLYCLOUDY:
return 2;
case WeatherCondition.TypeEnum.CLOUDY:
return 3;
case WeatherCondition.TypeEnum.FOG:
return 4;
case WeatherCondition.TypeEnum.FOGDEPOSITINGRIME:
return 5;
case WeatherCondition.TypeEnum.SLIGHTDRIZZLE:
return 6;
case WeatherCondition.TypeEnum.SLIGHTRAINNOTFREEZING:
return 7;
case WeatherCondition.TypeEnum.RAINSHOWERSLIGHT:
return 8;
case WeatherCondition.TypeEnum.DRIZZLEFREEZINGSLIGHT:
return 9;
case WeatherCondition.TypeEnum.RAINFREEZINGSLIGHT:
return 10;
case WeatherCondition.TypeEnum.SLIGHTFALLOFSNOWFLAKES:
return 11;
case WeatherCondition.TypeEnum.SNOWSHOWERSLIGHT:
return 12;
case WeatherCondition.TypeEnum.MODERATEDRIZZLE:
return 13;
case WeatherCondition.TypeEnum.HEAVYDRIZZLE:
return 14;
case WeatherCondition.TypeEnum.MODERATERAINNOTFREEZING:
return 15;
case WeatherCondition.TypeEnum.SNOWGRAINS:
return 16;
case WeatherCondition.TypeEnum.MODERATEFALLOFSNOWFLAKES:
return 17;
case WeatherCondition.TypeEnum.HEAVYRAINNOTFREEZING:
return 18;
case WeatherCondition.TypeEnum.DRIZZLEFREEZINGMODERATEHEAVY:
return 19;
case WeatherCondition.TypeEnum.HEAVYFALLOFSNOWFLAKES:
return 20;
case WeatherCondition.TypeEnum.RAINSHOWERMODERATEHEAVY:
return 21;
case WeatherCondition.TypeEnum.RAINFREEZINGMODERATEHEAVY:
return 22;
case WeatherCondition.TypeEnum.SNOWSHOWERMODERATEHEAVY:
return 23;
case WeatherCondition.TypeEnum.RAINSHOWERVIOLENT:
return 24;
case WeatherCondition.TypeEnum.THUNDERSTORMSLIGHTMODERATE:
return 25;
case WeatherCondition.TypeEnum.THUNDERSTORMHAILHEAVY:
return 26;
default:
return -1;
}
}
onClick() {
this.clickHandler();
}
}
onClick() {
this.clickHandler();
}
}
@@ -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,43 @@ 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[] {
"app/mowesta-forecast", "app/mowesta-search"
};
/**
* The pattern to match.
*/
@@ -75,7 +82,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 +98,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 +134,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 +168,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 +195,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 +228,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);
}
}