Answered step by step
Verified Expert Solution
Question
1 Approved Answer
How do resolve the fix me comments in GameAuthApplication.java?: Here is the code: GameAuthApplication.java package com.gamingroom.gameauth; import io.dropwizard.A pplication; import io.dropw izard.Configuration; import io.dropw izard.auth.A
How do resolve the fix me comments in GameAuthApplication.java?:
Here is the code: GameAuthApplication.java package com.gamingroom.gameauth; import io.dropwizard.A pplication; import io.dropw izard.Configuration; import io.dropw izard.auth.A uthD ynam icF eature; import io.dropwizard.auth.Auth ValueFactoryProvider; import io.dropwizard.auth.basic.B asicCredentialAuthFilter; import io.dropw izard.client.JerseyClientBuilder; import io.dropw izard.setup.Bootstrap; import io.dropw izard.setup. Environment; import javax.ws.rs.client.Client; import org.glassfish.jersey.server.filter.RolesA llowedDynam icF eature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.gamingroom.gameauth.auth.GameAuthenticator; import com.gamingroom.gameauth.auth.GameA uthorizer; import com.gamingroom.gameauth.auth.GameUser; import com.gamingroom.gameauth.controller.GameUserRESTController; import com.gamingroom.gameauth.controller.RESTClientController; import com.gamingroom.gameauth.healthcheck.AppHealthCheck; import com.gamingroom.gam eauth.healthcheck.HealthCheckController; public class GameAuthApplication extends Application>{ private static final Logger LOGGER = LoggerFactory getLogger(GameA uthApplication.class); (a) Override public void initialize(Bootstrap b) \{ (a) Override public void run(Configuration c, Environment e) throws Exception \{ LOGGER.info("Registering REST resources"); // FIXME: register GameUserRESTController (based on B asicAuth Security Exan // FIXME: Create io.dropwizard.client.JerseyClientBuilder instance and give it io.dropwizard.setup.Environment reference (based on BasicAuth Security Example) e.jersey().register(new GameUserRESTController(e.getValidator())); final Client client = new JerseyClientBuilder(e).build("DemoRESTClient"); e.jersey().register(new RESTClientController(client)); // Application health check e.healthChecks().register("APIHealthCheck", new AppHealthCheck(client)); // Run multiple health checks e.jersey().register(new HealthCheckController(e.healthChecks())); //Setup Basic Security e.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder () .setAuthenticator(new GameAuthenticator()) .setAuthorizer(new GameAuthorizer()) .setRealm("App Security") .buildAuthFilter())); e.jersey().register(new AuthValueFactoryProvider.Binder > (GameUser.class)); e.jersey().register(RolesAllowedDynamicFeature.class); 1 public static void main(String[] args) throws Exception \{ new GameAuthApplication().run(args); 1 1 GameAuthConfiguration.java package com.gamingroom.gamcauth; import io.dropwizard.Configuration; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.*; import javax.validation.constraints.*; public class GameAuthConfiguration extends Configuration \{ GameAuthenticator.java package com.gamingroom.gameauth.auth; import io.dropwizard.auth.A uthenticationException; import io.dropw izard.auth.Authenticator; import io.dropw izard.auth. basic.B asicCredentials; import java.util.Map; import java.util.Optional; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; public class GameAuthenticator implements A uthenticator \{ private static final Map > VALID_USERS = ImmutableMap.of( "guest", ImmutableSet.of( ), "user", ImmutableSet.of("USER"), "adm in", ImmutableSet.of("ADMIN", "USER") ); (a) Override public OptionakGameUser> authenticate(BasicCredentials credentials) throws Authentication Exception i. if (VALID_USERS.containsKey(credentials.getUsername()) \& \& "password".equals(credentials.getPassword())) \{ //FIXME: Finish the authorize method based on BasicAuth Security Example for new GameUser return Optional.of(new GameUser(credentials.getUsername () , VALID_USERS.get(credentials.getUsername()))); return Optional.empty(); ? GameAuthorizer.java package com.gamingroom.gameauth.auth; import io.dropwizard.auth.Authorizer; public class GameAuthorizer implements A uthorizer \{ (a) Override public boolean authorize(GameUser user, String role) return user.getRoles()!= null \&\& user.getRoles().contains(role); 3 ) GameUser.java package com.gamingroom.gameauth.auth; import java.security.Principal; import java.util.Set; public class GameUser implements Principal private String name = ""; private final S et roles; public GameUser(String name) \{ this.name = name; this.roles = null; 3 public GameUser(String name, Set roles) \{ this.name = name; this.roles = roles; ? public String getName() return name; \} public int getId() return (int) (Math.random ()100) \} public Set getRoles() \{ return roles; 1 ) GameUserRESTController.java package com.gamingroom.gameauth.controller; import io.dropw izard.auth.A uth; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Set; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.validation.ConstraintViolation; import javax.validation. Validator; import javax.ws.rs.DELETE; im port javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.gamingroom.gameauth.auth.GameUser; import com.gamingroom.gameauth.dao.GameUserDB; import com.gamingroom.gameauth.representations.GameUserInfo; // FIXME: Add path annotation for gameusers (a)Path("/gameusers/") (a) Produces(MediaType.APPLICATION_JSON) public class GameUscrRESTController private final Validator validator; public GameUserRESTController(Validator validator) \{ this.validator = validator; ? (a) PermitA ll (a) GET public Response getGameUsers(@A Ath GameUser user) return Response.ok(GameUserDB.getGameUsers()), build(); 3 // FIXME: Add RolesAllowed annotation for USER based on BasicAuth Security Example (a) RolesAllowed(\{ "USER" \}) (a) GET (a) Path("/\{id }") public Response getGameUserById(@PathParam("id") Integer id,(a)Auth GameUser user) //You can validate here if user is watching his record / if(id != user.getIdO)\{ //Not allowed y/ GameUserInfo gameUserInfo = GameUserDB.getGameUser(id); if (gameUserInfo != null) return Response.ok(gameUserInfo).build(); else return Response.status(Status.NOT FOUND).build(); // FIXME: Add RolesAllowed annotation for ADMIN based on BasicAuth Security Example (a) RolesAllowed(\{"ADMIN" }) (a) POST public Response createGameUser(GameUserInfo gameUserInfo, @A Ath GameUser user) throws URISyntaxException // validation Set > violations = validator.validate ( gameUserInfo); GameUserInfo e = GameUserDB.getGameUser(gameUserInfo.getId()); if (violations.size ()>0 ) \{ ArrayList String > validationMessages = new ArrayL ist String >(); for (ConstraintViolation violation : violations) \{ validationMessages.add(violation.getPropertyPath().toString()+":" + violation.getMessage()); \} return Response.status(Status.BAD_REQUEST).entity(validationMessages).build(); ? if (e != null) GameUserDB updateGameUser(gameUserInfo.getId(), gameUserInfo); return Response.created(new URI("/gameusers/" + gameUserInfo.getId())) build(); ; else return Response.status(Status.NOT_FOUND).build(); 3 (a) PUT (a) Path("/\{id } ") public Response updateGameUserById(@PathParam("id") Integer id, GameUserInfo gameUserInfo) \{ // validation Set > violations = validator.validate(gameUserInfo); GameUserInfo e = GameUserDB.getGameUser(gameUserInfo.getId()); if (violations.size ()>0 ) ArrayL ist validationMessages = new ArrayL is (); RESTClientController.java package com.gamingroom.gameauth.controller; import java.util.ArrayList; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; im port javax.ws.rs.client.Client; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.gamingroom.gameauth.representations.GameUserInfo; (a) Produces(MediaType.TEXT_PLAIN) (a) Path("/client/") public class RESTClientController private Client client; public RESTClientController(Client client) \{ this.client = client; \} // FIXME: Add annotation for GET and Path for gameusers // Here we set the correct HTTP method to request data from the DB. @GET // The GET method returns data of game users added to URL path defined below. @Path("/gameusers/") @Produces(MediaType.TEXT_PLAIN) public String getGameUsers() //Do not hard code in your application WebTarget webTarget = client.target("http://localhost:8080/gameusers"); Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.get () ; (a) SuppressWarnings("rawtypes") ArrayL ist gameusers = response readEntity(ArrayL ist.class); return gameusers.toString(); \} @GET @Path("/gameusers/\{id } ") public String getGameUserById(@PathParam("id") int id) \{ //Do not hard code in your application WebTarget webTarget = client.target("http://localhost:8080/gameusers/"+id); Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.get () ; GameUserInfo gameUserInfo = response.readEntity(GameUserInfo.class); return gameUserInfo.toString(); 3 ) GameUserDB.java package com.gamingroom.gameauth.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.gamingroom.gameauth.representations.GameUserInfo; public class GameUserDB public static HashMap gameUserInfos = new HashMap > (); static gameUserInfos.put(1, new GameUserInfo(1, "Lokesh", "Gupta", "India")); gameUserInfos.put(2, new GameUserInfo(2, "John", "Gruber", "USA")); gameUserInfos.put(3, new GameUserInfo(3, "Melcum", "Marshal", "AUS")); 3 public static List getGameUsers() return new ArrayList (gameUserInfos.values ()); 3 public static GameUserInfo getGameUser(Integer id) return gameUserInfos.get(id); ) public static void updateGameUser(Integer id, GameUserInfo gameUserInfo) \{ gameUserInfos.put(id, gameUserInfo); 3 public static void removeGameUser(Integer id) gameUserInfos.remove(id); \} y AppH ealthCheck.java package com.gamingroom.gameauth.healthcheck; import java.util.ArrayL ist; import javax.ws.rs.client.Client; import javax.ws.rs.client.Invocation; im port javax.ws.rs.client.W ebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.codahale.metrics.health.HealthCheck; public class AppHealthCheck extends HealthCheck \{ private final Client client; public AppHealthCheck(Client client) \{ super(); this.client = client; \} (a) Override protected Result check() throws Exception \{ WebTarget webTarget = client.target("http://localhost:8080/gameusers"); Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationB B ilder.get(); (a) SuppressWarnings("rawtypes") ArrayL ist gameusers = response.readEntity(ArrayList.class); if(gameusers !-null \&\& gameusers.size ()>0){ return Result.healthy(); \} return Result unhealthy("API Failed"); ) 1 HealthCheckController.java package com.gamingroom.gameauth.healthcheck; import java.util.Map.Entry; import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.codahale.metrics.health.HealthCheck.Result; import com.codahale.metrics.health.HealthCheckRegistry; (a) Produces(MediaType.APPLICATION_JSON) (a) Path("/status") public class HealthCheckController \{ private HealthCheckRegistry registry; public HealthCheckController(HealthCheckRegistry registry) \{ this.registry = registry; @GET public Set > getStatus( ){ return registry.runHealthChecks().entry Set(); ) GameUserInfo.java package com.gamingroom.gameauth.representations; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotB lank; (a) SuppressWarnings("deprecation") public class GameUserInfo \{ (@) NotNull private Integer id; (a) NotBlank (a) Length (min=2,max=255) private String firstName; (a) NotBlank (a Length (min=2,max=255) private String lastName; @ Pattern(regexp= ".+@.+11.[a-z]+") private String email; public GameUserInfo()\{ \} public GameUserInfo(Integer id, String firstName, String lastName, String email) this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; 3 public Integer getId() return id; 3 public void setId(Integer id) \{ this.id = id; public String getFirstName() return firstName; 3 public void setFirstName(String firstName) this.firstName = firstName; 3 public String getLastName()\{ return lastName; 3 public void setLastName(String lastName) \{ this.lastName = lastName; \} public String getEmail() return email; \} public void setEmail(String email) \{ this.cmail = cmail; 3 (a) Override public String toString() return "GameUser [id-" + id + ", firstName e"+ firstName + ", lastName " + lastName + ", email=" + email + "]"; )Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started