Skip to content

Commit

Permalink
Merge branch 'feature/java-optional' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
mwarman committed Dec 10, 2018
2 parents b9274e5 + 4302831 commit 1632ba2
Show file tree
Hide file tree
Showing 10 changed files with 116 additions and 116 deletions.
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
package com.leanstacks.ws.repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.leanstacks.ws.model.Account;

/**
* The AccountRepository interface is a Spring Data JPA data repository for
* Account entities. The AccountRepository provides all the data access
* behaviors exposed by <code>JpaRepository</code> and additional custom
* behaviors may be defined in this interface.
* The AccountRepository interface is a Spring Data JPA data repository for Account entities. The AccountRepository
* provides all the data access behaviors exposed by <code>JpaRepository</code> and additional custom behaviors may be
* defined in this interface.
*
* @author Matt Warman
*/
@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {

/**
* Query for a single Account entities by username.
* Query for a single Account entity by username.
*
* @param username The username value to query the repository.
* @return An Account or <code>null</code> if none found.
* @return An Optional Account.
*/
Account findByUsername(String username);
Optional<Account> findByUsername(String username);

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.leanstacks.ws.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -43,25 +43,21 @@ public class AccountUserDetailsService implements UserDetailsService {
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
logger.info("> loadUserByUsername {}", username);

final Account account = accountService.findByUsername(username);
if (account == null) {
// Not found...
throw new UsernameNotFoundException("Invalid credentials.");
}
final Optional<Account> accountOptional = accountService.findByUsername(username);
final Account account = accountOptional
.orElseThrow(() -> new UsernameNotFoundException("Invalid credentials."));

final Set<Role> roles = account.getRoles();
if (roles == null || roles.isEmpty()) {
// No Roles assigned to Account...
throw new UsernameNotFoundException("Invalid credentials.");
}

final Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
for (final Role role : roles) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getCode()));
}
final Set<GrantedAuthority> authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.getCode()))
.collect(Collectors.toSet());

final User userDetails = new User(account.getUsername(), account.getPassword(), account.isEnabled(),
!account.isExpired(), !account.isCredentialsexpired(), !account.isLocked(), grantedAuthorities);
!account.isExpired(), !account.isCredentialsexpired(), !account.isLocked(), authorities);

logger.info("< loadUserByUsername {}", username);
return userDetails;
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/com/leanstacks/ws/service/AccountService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.leanstacks.ws.service;

import java.util.Optional;

import com.leanstacks.ws.model.Account;

/**
Expand All @@ -19,8 +21,8 @@ public interface AccountService {
* Find an Account by the username attribute value.
*
* @param username A String username to query the repository.
* @return An Account instance or <code>null</code> if none found.
* @return An Optional wrapped Account.
*/
Account findByUsername(String username);
Optional<Account> findByUsername(String username);

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.leanstacks.ws.service;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -29,13 +31,13 @@ public class AccountServiceBean implements AccountService {
private transient AccountRepository accountRepository;

@Override
public Account findByUsername(final String username) {
public Optional<Account> findByUsername(final String username) {
logger.info("> findByUsername");

final Account account = accountRepository.findByUsername(username);
final Optional<Account> accountOptional = accountRepository.findByUsername(username);

logger.info("< findByUsername");
return account;
return accountOptional;
}

}
17 changes: 9 additions & 8 deletions src/main/java/com/leanstacks/ws/service/GreetingService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.leanstacks.ws.service;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

import com.leanstacks.ws.model.Greeting;

Expand All @@ -19,17 +20,17 @@ public interface GreetingService {
/**
* Find all Greeting entities.
*
* @return A Collection of Greeting objects.
* @return A List of Greeting objects.
*/
Collection<Greeting> findAll();
List<Greeting> findAll();

/**
* Find a single Greeting entity by primary key identifier.
* Find a single Greeting entity by primary key identifier. Returns an Optional wrapped Greeting.
*
* @param id A BigInteger primary key identifier.
* @return A Greeting or <code>null</code> if none found.
* @param id A Long primary key identifier.
* @return A Optional Greeting
*/
Greeting findOne(Long id);
Optional<Greeting> findOne(Long id);

/**
* Persists a Greeting entity in the data store.
Expand All @@ -50,7 +51,7 @@ public interface GreetingService {
/**
* Removes a previously persisted Greeting entity from the data store.
*
* @param id A BigInteger primary key identifier.
* @param id A Long primary key identifier.
*/
void delete(Long id);

Expand Down
30 changes: 11 additions & 19 deletions src/main/java/com/leanstacks/ws/service/GreetingServiceBean.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package com.leanstacks.ws.service;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

import javax.persistence.EntityExistsException;
import javax.persistence.NoResultException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -83,12 +80,12 @@ public GreetingServiceBean(final GreetingRepository greetingRepository, final Me
}

@Override
public Collection<Greeting> findAll() {
public List<Greeting> findAll() {
logger.info("> findAll");

findAllMethodInvocationCounter.increment();

final Collection<Greeting> greetings = greetingRepository.findAll();
final List<Greeting> greetings = greetingRepository.findAll();

logger.info("< findAll");
return greetings;
Expand All @@ -97,19 +94,19 @@ public Collection<Greeting> findAll() {
@Cacheable(value = Application.CACHE_GREETINGS,
key = "#id")
@Override
public Greeting findOne(final Long id) {
public Optional<Greeting> findOne(final Long id) {
logger.info("> findOne {}", id);

findOneMethodInvocationCounter.increment();

final Optional<Greeting> result = greetingRepository.findById(id);
final Optional<Greeting> greetingOptional = greetingRepository.findById(id);

logger.info("< findOne {}", id);
return result.isPresent() ? result.get() : null;
return greetingOptional;
}

@CachePut(value = Application.CACHE_GREETINGS,
key = "#result.id")
key = "#result?.id")
@Transactional
@Override
public Greeting create(final Greeting greeting) {
Expand All @@ -123,7 +120,7 @@ public Greeting create(final Greeting greeting) {
if (greeting.getId() != null) {
logger.error("Attempted to create a Greeting, but id attribute was not null.");
logger.info("< create");
throw new EntityExistsException(
throw new IllegalArgumentException(
"Cannot create new Greeting with supplied id. The id attribute must be null to create an entity.");
}

Expand All @@ -142,15 +139,10 @@ public Greeting update(final Greeting greeting) {

updateMethodInvocationCounter.increment();

// Ensure the entity object to be updated exists in the repository to
// prevent the default behavior of save() which will persist a new
// findOne returns an Optional which will throw NoSuchElementException when null.
// This will prevent the default behavior of save() which will persist a new
// entity if the entity matching the id does not exist
final Greeting greetingToUpdate = findOne(greeting.getId());
if (greetingToUpdate == null) {
logger.error("Attempted to update a Greeting, but the entity does not exist.");
logger.info("< update {}", greeting.getId());
throw new NoResultException("Requested Greeting not found.");
}
final Greeting greetingToUpdate = findOne(greeting.getId()).get();

greetingToUpdate.setText(greeting.getText());
final Greeting updatedGreeting = greetingRepository.save(greetingToUpdate);
Expand Down
47 changes: 17 additions & 30 deletions src/main/java/com/leanstacks/ws/web/api/GreetingController.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package com.leanstacks.ws.web.api;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.persistence.NoResultException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -61,7 +60,7 @@ public class GreetingController {
* Web service endpoint to fetch all Greeting entities. The service returns the collection of Greeting entities as
* JSON.
*
* @return A ResponseEntity containing a Collection of Greeting objects.
* @return A List of Greeting objects.
*/
@ApiOperation(value = "${GreetingController.getGreetings.title}",
notes = "${GreetingController.getGreetings.notes}",
Expand All @@ -73,10 +72,10 @@ public class GreetingController {
dataType = "string",
paramType = "header"))
@GetMapping
public Collection<Greeting> getGreetings() {
public List<Greeting> getGreetings() {
logger.info("> getGreetings");

final Collection<Greeting> greetings = greetingService.findAll();
final List<Greeting> greetings = greetingService.findAll();

logger.info("< getGreetings");
return greetings;
Expand All @@ -92,8 +91,7 @@ public Collection<Greeting> getGreetings() {
* </p>
*
* @param id A Long URL path variable containing the Greeting primary key identifier.
* @return A ResponseEntity containing a single Greeting object, if found, and a HTTP status code as described in
* the method comment.
* @return A Greeting object, if found, and a HTTP status code as described in the method comment.
*/
@ApiOperation(value = "${GreetingController.getGreeting.title}",
notes = "${GreetingController.getGreeting.notes}",
Expand All @@ -107,14 +105,10 @@ public Collection<Greeting> getGreetings() {
public Greeting getGreeting(@ApiParam("Greeting ID") @PathVariable final Long id) {
logger.info("> getGreeting");

final Greeting greeting = greetingService.findOne(id);
if (greeting == null) {
logger.info("< getGreeting");
throw new NoResultException("Greeting not found.");
}
final Optional<Greeting> greetingOptional = greetingService.findOne(id);

logger.info("< getGreeting");
return greeting;
return greetingOptional.get();
}

/**
Expand All @@ -124,12 +118,11 @@ public Greeting getGreeting(@ApiParam("Greeting ID") @PathVariable final Long id
* </p>
* <p>
* If created successfully, the persisted Greeting is returned as JSON with HTTP status 201. If not created
* successfully, the service returns an empty response body with HTTP status 500.
* successfully, the service returns an ExceptionDetail response body with HTTP status 400 or 500.
* </p>
*
* @param greeting The Greeting object to be created.
* @return A ResponseEntity containing a single Greeting object, if created successfully, and a HTTP status code as
* described in the method comment.
* @return A Greeting object, if created successfully, and a HTTP status code as described in the method comment.
*/
@ApiOperation(value = "${GreetingController.createGreeting.title}",
notes = "${GreetingController.createGreeting.notes}",
Expand Down Expand Up @@ -158,13 +151,12 @@ public Greeting createGreeting(@RequestBody final Greeting greeting) {
* </p>
* <p>
* If updated successfully, the persisted Greeting is returned as JSON with HTTP status 200. If not found, the
* service returns an empty response body and HTTP status 404. If not updated successfully, the service returns an
* empty response body with HTTP status 500.
* service returns an ExceptionDetail response body and HTTP status 404. If not updated successfully, the service
* returns an empty response body with HTTP status 400 or 500.
* </p>
*
* @param greeting The Greeting object to be updated.
* @return A ResponseEntity containing a single Greeting object, if updated successfully, and a HTTP status code as
* described in the method comment.
* @return A Greeting object, if updated successfully, and a HTTP status code as described in the method comment.
*/
@ApiOperation(value = "${GreetingController.updateGreeting.title}",
notes = "${GreetingController.updateGreeting.notes}",
Expand Down Expand Up @@ -194,7 +186,7 @@ public Greeting updateGreeting(@ApiParam("Greeting ID") @PathVariable("id") fina
* </p>
* <p>
* If deleted successfully, the service returns an empty response body with HTTP status 204. If not deleted
* successfully, the service returns an empty response body with HTTP status 500.
* successfully, the service returns an ExceptionDetail response body with HTTP status 500.
* </p>
*
* @param id A Long URL path variable containing the Greeting primary key identifier.
Expand Down Expand Up @@ -223,14 +215,13 @@ public void deleteGreeting(@ApiParam("Greeting ID") @PathVariable("id") final Lo
* </p>
* <p>
* If found, the Greeting is returned as JSON with HTTP status 200 and sent via Email. If not found, the service
* returns an empty response body with HTTP status 404.
* returns an Exception response body with HTTP status 404.
* </p>
*
* @param id A Long URL path variable containing the Greeting primary key identifier.
* @param waitForAsyncResult A boolean indicating if the web service should wait for the asynchronous email
* transmission.
* @return A ResponseEntity containing a single Greeting object, if found, and a HTTP status code as described in
* the method comment.
* @return A Greeting object, if found, and a HTTP status code as described in the method comment.
*/
@ApiOperation(value = "${GreetingController.sendGreeting.title}",
notes = "${GreetingController.sendGreeting.notes}",
Expand All @@ -250,11 +241,7 @@ public Greeting sendGreeting(@ApiParam("Greeting ID") @PathVariable("id") final
Greeting greeting;

try {
greeting = greetingService.findOne(id);
if (greeting == null) {
logger.info("< sendGreeting");
throw new NoResultException("Greeting not found.");
}
greeting = greetingService.findOne(id).get();

if (waitForAsyncResult) {
final Future<Boolean> asyncResponse = emailService.sendAsyncWithResult(greeting);
Expand Down
Loading

0 comments on commit 1632ba2

Please sign in to comment.