Commit ba653b86 authored by Kevin Kaminski's avatar Kevin Kaminski

Working app - just need to add Address nested document functionality, which may or may not happen

parents
#Tue Apr 06 12:54:51 PDT 2021
gradle.version=6.7
# Default ignored files
/shelf/
/workspace.xml
mongodemo
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="1.8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="/usr/local/Cellar/gradle/4.3.1/libexec" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenRepo" />
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
<remote-repository>
<option name="id" value="maven" />
<option name="name" value="maven" />
<option name="url" value="https://repo.spring.io/milestone" />
</remote-repository>
<remote-repository>
<option name="id" value="maven2" />
<option name="name" value="maven2" />
<option name="url" value="https://oss.sonatype.org/content/repositories/releases" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
?
settings.gradle,0/5/05efc8b1657769a27696d478ded1e95f38737233
<
build.gradle,f/0/f07866736216be0ee2aba49e392191aeae700a35
\ No newline at end of file
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:2.1.2.RELEASE")
compile("org.springframework.boot:spring-boot-starter-actuator:2.1.2.RELEASE")
compile('org.springframework.cloud:spring-cloud-starter:2.1.2.RELEASE')
compile('org.apache.commons:commons-lang3:3.8')
compile('org.apache.commons:commons-io:1.3.2')
compile('org.apache.httpcomponents:httpclient:4.5.3')
compile('net.logstash.logback:logstash-logback-encoder:4.7')
compile('ch.qos.logback:logback-core:1.1.8')
compile('org.projectlombok:lombok:1.16.10')
compile("org.springframework.data:spring-data-mongodb:2.1.0.RELEASE")
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}
test {
useJUnitPlatform()
}
\ No newline at end of file
server.port=9090
\ No newline at end of file
com/nisum/demo/mongo/MongoDBDemoApplication.java
com.nisum.demo.mongo.MongoDBDemoApplication
com/nisum/demo/mongo/model/UserResponse.java
com.nisum.demo.mongo.model.UserResponse
com/nisum/demo/mongo/repository/UserRepository.java
com.nisum.demo.mongo.repository.UserRepository
com/nisum/demo/mongo/configuration/MongoConfig.java
com.nisum.demo.mongo.configuration.MongoConfig
com/nisum/demo/mongo/model/Address.java
com.nisum.demo.mongo.model.Address
com/nisum/demo/mongo/repository/model/Address.java
com.nisum.demo.mongo.repository.model.Address
com/nisum/demo/mongo/model/UserRequest.java
com.nisum.demo.mongo.model.UserRequest
com/nisum/demo/mongo/repository/model/User.java
com.nisum.demo.mongo.repository.model.User
com/nisum/demo/mongo/model/UserData.java
com.nisum.demo.mongo.model.UserData
com/nisum/demo/mongo/controller/MongoDBDemoController.java
com.nisum.demo.mongo.controller.MongoDBDemoController
com/nisum/demo/mongo/service/MongoDBDemoService.java
com.nisum.demo.mongo.service.MongoDBDemoService
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'mongodemo'
package com.nisum.demo.mongo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@SpringBootApplication
@ComponentScan( {"com.nisum.demo.mongo"})
@EnableMongoRepositories(basePackages = "com.nisum.demo.mongo.repository")
public class MongoDBDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MongoDBDemoApplication.class, args);
}
}
package com.nisum.demo.mongo.configuration;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.util.Collection;
import java.util.Collections;
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
@Override
protected String getDatabaseName() {
return "mongodbdemo";
}
@Override
public MongoClient mongoClient() {
ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/mongodbdemo");
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
return MongoClients.create(mongoClientSettings);
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoClient(), "mongodbdemo");
}
}
\ No newline at end of file
package com.nisum.demo.mongo.controller;
import com.nisum.demo.mongo.model.UserRequest;
import com.nisum.demo.mongo.model.UserResponse;
import com.nisum.demo.mongo.repository.model.User;
import com.nisum.demo.mongo.service.MongoDBDemoService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class MongoDBDemoController {
private MongoDBDemoService mongoDBDemoService;
public MongoDBDemoController(MongoDBDemoService mongoDBDemoService) {
this.mongoDBDemoService = mongoDBDemoService;
}
@GetMapping(value = "/user/search/all", produces = {"application/json"})
ResponseEntity<UserResponse> searchAllUsers() {
UserResponse response = mongoDBDemoService.getAllUserData();
return new ResponseEntity<>(response, HttpStatus.OK);
}
@GetMapping(value = "/user/search", produces = {"application/json"})
ResponseEntity<UserResponse> searchUserById(@RequestParam(required = false) String byUserId,
@RequestParam(required = false) String byUserFirstName) throws Exception {
UserResponse response = mongoDBDemoService.getUserData(byUserId, byUserFirstName);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@PostMapping(value = "/user/add", consumes = {"application/json"}, produces = {"application/json"})
ResponseEntity<UserResponse> addUser(@RequestBody UserRequest user) {
mongoDBDemoService.addUser(user);
return new ResponseEntity<UserResponse>(HttpStatus.OK);
}
@PostMapping(value = "/user/update", consumes = {"application/json"}, produces = {"application/json"})
ResponseEntity<UserResponse> updateUser(@RequestBody UserRequest user) throws Exception {
mongoDBDemoService.updateUser(user);
return new ResponseEntity<UserResponse>(HttpStatus.OK);
}
@DeleteMapping(value = "/user", produces = {"application/json"})
ResponseEntity<UserResponse> deleteUserById(@RequestParam String byUserId) {
mongoDBDemoService.deleteUserById(byUserId);
return new ResponseEntity<>(HttpStatus.OK);
}
@DeleteMapping(value = "/user/delete/all", produces = {"application/json"})
ResponseEntity<UserResponse> deleteAll() {
mongoDBDemoService.deleteAll();
return new ResponseEntity<>(HttpStatus.OK);
}
}
package com.nisum.demo.mongo.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Address {
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@JsonProperty
private String address1;
@JsonProperty
private String city;
@JsonProperty
private String state;
}
package com.nisum.demo.mongo.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.nisum.demo.mongo.repository.model.Address;
public class UserData {
@JsonProperty
private String id;
@JsonProperty
private String userId;
@JsonProperty
private String userFirstName;
@JsonProperty
private String userLastName;
@JsonProperty
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserFirstName(String userFirstName) {
this.userFirstName = userFirstName;
}
public void setUserLastName(String userLastName) {
this.userLastName = userLastName;
}
public String getUserId() {
return this.userId;
}
public String getUserFirstName() {
return this.userFirstName;
}
public String getUserLastName() {
return this.userLastName;
}
}
package com.nisum.demo.mongo.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.nisum.demo.mongo.repository.model.Address;
public class UserRequest {
@JsonProperty
private String userId;
@JsonProperty
private String userFirstName;
@JsonProperty
private String userLastName;
@JsonProperty
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserFirstName(String userFirstName) {
this.userFirstName = userFirstName;
}
public void setUserLastName(String userLastName) {
this.userLastName = userLastName;
}
public String getUserId() {
return this.userId;
}
public String getUserFirstName() {
return this.userFirstName;
}
public String getUserLastName() {
return this.userLastName;
}
}
package com.nisum.demo.mongo.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
public class UserResponse {
@JsonProperty
private List<UserData> users;
public void setUsers(List<UserData> users) {
this.users = users;
}
public List<UserData> getUsers() {
return users;
}
}
package com.nisum.demo.mongo.repository;
import com.nisum.demo.mongo.repository.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import java.util.List;
public interface UserRepository extends MongoRepository<User, String> {
List<User> findByUserId(String userId);
void deleteByUserId(String userId);
@Query("{'userFirstName' : ?0}")
List<User> findByUserFirstName(String userFirstName);
}
package com.nisum.demo.mongo.repository.model;
public class Address {
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
private String address1;
private String city;
private String state;
}
package com.nisum.demo.mongo.repository.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "user")
public class User {
@Id
private String id;
@Indexed
private String userId;
private String userFirstName;
private String userLastName;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserFirstName(String userFirstName) {
this.userFirstName = userFirstName;
}
public void setUserLastName(String userLastName) {
this.userLastName = userLastName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return this.userId;
}
public String getUserFirstName() {
return this.userFirstName;
}
public String getUserLastName() {
return this.userLastName;
}
}
package com.nisum.demo.mongo.service;
import com.nisum.demo.mongo.model.UserData;
import com.nisum.demo.mongo.model.UserRequest;
import com.nisum.demo.mongo.model.UserResponse;
import com.nisum.demo.mongo.repository.UserRepository;
import com.nisum.demo.mongo.repository.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Service
public class MongoDBDemoService {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private UserRepository userRepository;
public UserResponse getAllUserData() {
UserResponse response = new UserResponse();
List<UserData> users = new ArrayList<>();
userRepository.findAll().forEach( u -> {
UserData uData = new UserData();
uData.setId(u.getId());
uData.setUserId(u.getUserId());
uData.setUserFirstName(u.getUserFirstName());
uData.setUserLastName(u.getUserLastName());
uData.setAddress(u.getAddress());
users.add(uData);
});
response.setUsers(users);
return response;
}
public UserResponse getUserData(String userId, String userName) throws Exception {
List<User> userList = null;
if (StringUtils.isNotEmpty(userId)) {
userList = userRepository.findByUserId(userId);
} else if (StringUtils.isNotEmpty(userName)) {
userList = userRepository.findByUserFirstName(userName);
} else {
throw new Exception("Insufficient input");
}
UserResponse response = new UserResponse();
List<UserData> users = new ArrayList<>();
userList.forEach( u -> {
UserData uData = new UserData();
uData.setId(u.getId());
uData.setUserId(u.getUserId());
uData.setUserFirstName(u.getUserFirstName());
uData.setUserLastName(u.getUserLastName());
users.add(uData);
});
response.setUsers(users);
return response;
}
public void deleteUserById(String userId) {
userRepository.deleteByUserId(userId);
}
public void deleteAll() {
userRepository.deleteAll();
}
public void addUser(UserRequest user) {
User newUser = new User();
newUser.setUserId(user.getUserId());
newUser.setUserFirstName(user.getUserFirstName());
newUser.setUserLastName(user.getUserLastName());
userRepository.save(newUser);
}
public void updateUser(UserRequest userReq) throws Exception {
List<User> userList = userRepository.findByUserId(userReq.getUserId());
if (userList == null) {
throw new Exception("No Users found");
}
List<User> updatedList = new ArrayList<>();
userList.forEach(u -> {
User user = new User();
user.setId(u.getId());
user.setUserId(u.getUserId());
user.setUserFirstName(userReq.getUserFirstName());
user.setUserLastName(userReq.getUserLastName());
user.setAddress(userReq.getAddress());
updatedList.add(user);
});
userRepository.saveAll(updatedList);
}
}
server.port=9090
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment