Skip to content

Commit

Permalink
Adding guava
Browse files Browse the repository at this point in the history
  • Loading branch information
i-laird committed Dec 18, 2023
1 parent dbec559 commit 0d2ca21
Show file tree
Hide file tree
Showing 38 changed files with 195 additions and 134 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# stage 1
FROM maven:3.9.1-amazoncorretto-20-debian-bullseye as build

MAINTAINER Ian Laird
LABEL maintainer = "Ian Laird"

WORKDIR /build

Expand Down
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,13 @@
<artifactId>spotless-maven-plugin</artifactId>
<version>${spotless.maven}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.3-jre</version>
</dependency>


</dependencies>

Expand Down
3 changes: 3 additions & 0 deletions src/main/java/calculator/DTO/DerivativeRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* A request for a mathematical expression.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
Expand Down
36 changes: 21 additions & 15 deletions src/main/java/calculator/controller/CalculatorController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,48 +3,54 @@
import calculator.DTO.DerivativeRequest;
import calculator.DTO.DerivativeResponse;
import calculator.service.CalculatorService;
import com.google.common.collect.ImmutableList;
import java.time.LocalTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**
Controller handling calculator requests.
*/
/** Controller handling calculator requests. */
@RestController
public final class CalculatorController {

@Autowired private CalculatorService calculatorServiceImpl;

/**
* Health check for the calculator.
*/
/** Health check for the calculator. */
@GetMapping("/health")
@ResponseStatus(HttpStatus.OK)
public String healthCheck() {
return LocalTime.now().toString();
}

/**
* Calculates the anti-derivative of a mathematical expression and then evaluates it at a specific point.
* Calculates the anti-derivative of a mathematical expression and then evaluates it at a specific
* point.
*
* @param request The request.
*
* @return the anti-derivative and result at a specific point.
*/
@GetMapping(value = "/derivative")
@ResponseStatus(HttpStatus.OK)
public DerivativeResponse generateDerivative(
@RequestBody DerivativeRequest request) {
return calculatorServiceImpl.evaluateDerivative(request.getExpression(), request.getPoints());
public DerivativeResponse generateDerivative(@RequestBody DerivativeRequest request) {
return calculatorServiceImpl.evaluateDerivative(
request.getExpression(), ImmutableList.copyOf(request.getPoints()));
}

/**
* Evaluates a mathematical expression.
*/
*
* @param request the request.
*
* @return The evaluation of a mathametical expression at specific points.
* */
@GetMapping(value = "/expression")
@ResponseStatus(HttpStatus.OK)
public double generateDerivative(@RequestParam("expression") final String expression) {
return calculatorServiceImpl.evaluateExpression(expression);
public double evaluateExpression(@RequestBody DerivativeRequest request) {
return calculatorServiceImpl.evaluateExpression(
request.getExpression(), ImmutableList.copyOf(request.getPoints()));
}
}
17 changes: 16 additions & 1 deletion src/main/java/calculator/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,36 @@
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
* Controller for user management.
*/
@RestController
public class UserController {
public final class UserController {

@Autowired private AuthenticationManager authenticationManager;

@Autowired private UserDetailsService userDetailsService;

@Autowired private UserService userService;

/**
* Registers a user.
* @param u the user to register.
* @return JWT for the registered user.
* @throws Exception if the user already exists.
*/
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody @Valid UserGeneration u) throws Exception {
userService.register(u.getEmail(), u.getPassword(), "STANDARD");
return createAuthenticationToken(new JwtRequest(u.getEmail(), u.getPassword()));
}

/**
* Logins in a user.
* @param authenticationRequest the users login credentials.
* @return JWT for the logged in user.
* @throws Exception If login fails.
*/
@PostMapping("/authenticate")
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest)
throws Exception {
Expand Down
19 changes: 13 additions & 6 deletions src/main/java/calculator/security/JwtRequestFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
* Handles JWT tokens.
*/
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
public final class JwtRequestFilter extends OncePerRequestFilter {
@Autowired private UserDetailsService jwtUserDetailsService;

@Override
Expand All @@ -43,20 +46,24 @@ protected void doFilterInternal(
}

// Once we get the token validate it.
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
if (username != null &&
SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails =
this.jwtUserDetailsService.loadUserByUsername(username);
// if token is valid configure Spring Security to manually set
// authentication
if (JwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken.setDetails(
authenticationToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request));
// After setting the Authentication in the context, we specify
// that the current user is authenticated. So it passes the
// Spring Security Configurations successfully.
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
SecurityContextHolder
.getContext()
.setAuthentication(authenticationToken);
}
}
chain.doFilter(request, response);
Expand Down
20 changes: 17 additions & 3 deletions src/main/java/calculator/security/JwtTokenUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,36 @@
@Component
public final class JwtTokenUtil implements Serializable {
private static final long serialVersionUID = 8562677648L;
public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;
public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60 * 1000;

private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512);

/**
* Gets the username from a JWT.
*
* @param token JWT token.
* @return the username.
*/
public static String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}

/**
* Gets the expiration date for a token.
*
* @param token JWT token.
* @return the expiration date of the token.
*/
public static Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}

/**
* Gets all claims for a token.
*
* @param token JWT token.
* @param claimsResolver claimsResolver
* @return the claims for the token.
*/
public static <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
Expand All @@ -57,8 +67,11 @@ private static Boolean isTokenExpired(String token) {

/**
* Generates a JWT.
*
* @param userDetails the users login credentials.
* @return JWT token.
*/
public static String generateToken(UserDetails userDetails) {
public static String generateToken(final UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
Expand All @@ -74,7 +87,8 @@ private static String doGenerateToken(Map<String, Object> claims, String subject
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
.setExpiration(
new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY))
.signWith(SECRET_KEY)
.compact();
}
Expand Down
7 changes: 4 additions & 3 deletions src/main/java/calculator/service/CalculatorService.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package calculator.service;

import calculator.DTO.DerivativeResponse;
import java.util.List;
import com.google.common.collect.ImmutableList;

public interface CalculatorService {
DerivativeResponse evaluateDerivative(String expression, List<Integer> evalPoints);

double evaluateExpression(String expression);
DerivativeResponse evaluateDerivative(String expression, ImmutableList<Integer> evalPoints);

double evaluateExpression(String expression, ImmutableList<Integer> evalPoints);
}
21 changes: 12 additions & 9 deletions src/main/java/calculator/service/impl/CalculatorServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,34 @@

import calculator.DTO.DerivativeResponse;
import calculator.service.CalculatorService;
import calculator.util.ast.AbstractSyntaxTree;
import calculator.util.StringToStream;
import calculator.util.ast.AbstractSyntaxTree;
import calculator.util.terms.Term;
import java.util.List;
import com.google.common.collect.ImmutableList;
import org.springframework.stereotype.Service;

/**
* TO USE: 1) create the Parser using an input stream 2) Call get root to get the term at the
* base of the AST.
* TO USE: 1) create the Parser using an input stream 2) Call get root to get the term at the base
* of the AST.
*
* <p>TO GET DERIVATIVE: call getDerivative on the term returned from getRoot()
*/
@Service
public class CalculatorServiceImpl implements CalculatorService {
@Override
public DerivativeResponse evaluateDerivative(String expression, List<Integer> evalPoints) {
AbstractSyntaxTree abstractSyntaxTree = new AbstractSyntaxTree(StringToStream.convertStringToStream(expression));
public DerivativeResponse evaluateDerivative(
String expression, ImmutableList<Integer> evalPoints) {
AbstractSyntaxTree abstractSyntaxTree =
new AbstractSyntaxTree(StringToStream.convertStringToStream(expression));
Term derivative = abstractSyntaxTree.getDeriv();
return new DerivativeResponse(derivative.toString(), derivative.evaluate(evalPoints));
}

@Override
public double evaluateExpression(String expression) {
AbstractSyntaxTree abstractSyntaxTree = new AbstractSyntaxTree(StringToStream.convertStringToStream(expression));
public double evaluateExpression(String expression, ImmutableList<Integer> evalPoints) {
AbstractSyntaxTree abstractSyntaxTree =
new AbstractSyntaxTree(StringToStream.convertStringToStream(expression));
Term root = abstractSyntaxTree.getRoot();
return root.evaluate(null);
return root.evaluate(evalPoints);
}
}
4 changes: 2 additions & 2 deletions src/main/java/calculator/util/rules/AdditionRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import static calculator.util.rules.RuleFactory.makeAdditionRule;

import calculator.util.terms.Term;
import com.google.common.collect.ImmutableList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
Expand Down Expand Up @@ -50,7 +50,7 @@ public AdditionRule addTerm(Term t) {
* @param dims the variable values to use when evaulating
* @return the result
*/
public double getResult(List<Integer> dims) {
public double getResult(ImmutableList<Integer> dims) {
return this.terms.stream().map(x -> x.evaluate(dims)).reduce(0.0, Double::sum);
}

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/calculator/util/rules/ArcCosRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import static calculator.util.rules.RuleFactory.*;

import calculator.util.terms.Term;
import com.google.common.collect.ImmutableList;
import java.util.LinkedList;
import java.util.List;

public final class ArcCosRule extends TrigRule {

Expand All @@ -28,7 +28,7 @@ public Term getDerivPart() {
}

@Override
public double getResult(List<Integer> dims) {
public double getResult(ImmutableList<Integer> dims) {
return 0;
}
}
4 changes: 2 additions & 2 deletions src/main/java/calculator/util/rules/ArcCotRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import static calculator.util.rules.RuleFactory.*;

import calculator.util.terms.Term;
import com.google.common.collect.ImmutableList;
import java.util.LinkedList;
import java.util.List;

public final class ArcCotRule extends TrigRule {

Expand All @@ -24,7 +24,7 @@ public Term getDerivPart() {
}

@Override
public double getResult(List<Integer> dims) {
public double getResult(ImmutableList<Integer> dims) {
return 0;
}
}
4 changes: 2 additions & 2 deletions src/main/java/calculator/util/rules/ArcSinRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import static calculator.util.rules.RuleFactory.*;

import calculator.util.terms.Term;
import com.google.common.collect.ImmutableList;
import java.util.LinkedList;
import java.util.List;

public final class ArcSinRule extends TrigRule {

Expand All @@ -28,7 +28,7 @@ public Term getDerivPart() {
}

@Override
public double getResult(List<Integer> dims) {
public double getResult(ImmutableList<Integer> dims) {
return 0;
}
}
4 changes: 2 additions & 2 deletions src/main/java/calculator/util/rules/ArcTanRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import static calculator.util.rules.RuleFactory.*;

import calculator.util.terms.Term;
import com.google.common.collect.ImmutableList;
import java.util.LinkedList;
import java.util.List;

public final class ArcTanRule extends TrigRule {

Expand All @@ -24,7 +24,7 @@ public Term getDerivPart() {
}

@Override
public double getResult(List<Integer> dims) {
public double getResult(ImmutableList<Integer> dims) {
return 0;
}
}
Loading

0 comments on commit 0d2ca21

Please sign in to comment.