Skip to content

Commit 351d459

Browse files
committed
Adding all the java classes
1 parent 53467b3 commit 351d459

File tree

6 files changed

+320
-0
lines changed

6 files changed

+320
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package modisefileupload.java.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.ComponentScan;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.context.annotation.Import;
7+
import org.springframework.context.annotation.PropertySource;
8+
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
9+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
10+
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
11+
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
12+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
13+
import org.springframework.web.servlet.view.InternalResourceViewResolver;
14+
15+
import modisefileupload.java.config.ApplicationContext;
16+
17+
@EnableWebMvc
18+
@Configuration
19+
@ComponentScan(basePackages={"modisefileupload.java"})
20+
@Import({ApplicationContext.class})
21+
@PropertySource("/WEB-INF/database/application.properties")
22+
public class WebConfig extends WebMvcConfigurerAdapter {
23+
24+
@Override
25+
public void addViewControllers(ViewControllerRegistry registry) {
26+
27+
registry.addViewController("/").setViewName("index");
28+
}
29+
30+
@Override
31+
public void addResourceHandlers(ResourceHandlerRegistry registry) {
32+
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
33+
}
34+
35+
@Bean
36+
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer(){
37+
return new PropertySourcesPlaceholderConfigurer();
38+
}
39+
40+
@Bean
41+
public InternalResourceViewResolver internalResourceViewResolver(){
42+
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
43+
44+
resolver.setPrefix("/WEB-INF/views/");
45+
46+
resolver.setSuffix(".jsp");
47+
48+
return resolver;
49+
}
50+
}
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
package modisefileupload.java.controller;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.nio.file.Files;
6+
import java.nio.file.Path;
7+
import java.nio.file.Paths;
8+
import java.util.List;
9+
10+
import javax.servlet.http.HttpServletRequest;
11+
import javax.validation.Valid;
12+
13+
import org.slf4j.Logger;
14+
import org.slf4j.LoggerFactory;
15+
import org.springframework.beans.factory.annotation.Autowired;
16+
import org.springframework.stereotype.Controller;
17+
import org.springframework.ui.Model;
18+
import org.springframework.validation.BindingResult;
19+
import org.springframework.web.bind.annotation.ModelAttribute;
20+
import org.springframework.web.bind.annotation.PathVariable;
21+
import org.springframework.web.bind.annotation.RequestMapping;
22+
import org.springframework.web.bind.annotation.RequestMethod;
23+
import org.springframework.web.multipart.MultipartFile;
24+
import org.springframework.web.servlet.ModelAndView;
25+
26+
import modisefileupload.java.domain.User;
27+
import modisefileupload.java.service.UserService;
28+
29+
@Controller
30+
public class UserController {
31+
32+
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
33+
34+
@Autowired
35+
private UserService userService;
36+
37+
private Path path;
38+
39+
@RequestMapping(value = "/usersList")
40+
public ModelAndView listUsers() {
41+
List<User> users = userService.listAllUsers();
42+
LOGGER.debug("------------------------>" + users.size());
43+
return new ModelAndView("/usersList", "users", users);
44+
}
45+
46+
@RequestMapping(value = "/", method = RequestMethod.GET)
47+
public String home(Model model) {
48+
User user = new User();
49+
user.setAge(0);
50+
model.addAttribute(user);
51+
return "index";
52+
}
53+
54+
@RequestMapping(value = "/index/saveUser", method = RequestMethod.POST)
55+
public String saveUser(@Valid @ModelAttribute("user") User user, BindingResult result, HttpServletRequest request) {
56+
57+
if (result.hasErrors()) {
58+
return "/index";
59+
}
60+
61+
//save user to database
62+
userService.saveUser(user);
63+
64+
// get the provided image from the form
65+
MultipartFile userImage = user.getUserImage();
66+
67+
// get root directory to store the image
68+
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
69+
70+
// change any provided image type to png
71+
// path = Paths.get(rootDirectory + "/WEB-INF/resources/images" +
72+
// product.getProductId() + ".png");
73+
path = Paths.get("/home/mrmodise/SpringWorkspace/modise-file-upload/src/main/webapp/WEB-INF/resources/uploaded-images/"
74+
+ user.getUserId() + ".png");
75+
76+
// check whether image exists or not
77+
if (userImage != null && !userImage.isEmpty()) {
78+
try {
79+
// convert the image type to png
80+
userImage.transferTo(new File(path.toString()));
81+
} catch (IllegalStateException | IOException e) {
82+
// oops! something did not work as expected
83+
e.printStackTrace();
84+
throw new RuntimeException("Saving User image was not successful", e);
85+
}
86+
}
87+
88+
return "redirect:/?success=1";
89+
}
90+
91+
/**
92+
* deleting the user information requires that we delete the image they uploaded
93+
* the code below takes the preceding thoughts into care
94+
* @param id
95+
* @param request
96+
* @return
97+
*/
98+
@RequestMapping(value="/index/deleteUser/{id}")
99+
public String deleteUser(@PathVariable long id, HttpServletRequest request){
100+
// get root directory to store the image
101+
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
102+
103+
// change any provided image type to png
104+
// path = Paths.get(rootDirectory + "/WEB-INF/resources/images" +
105+
// product.getProductId() + ".png");
106+
path = Paths
107+
.get("/home/mrmodise/SpringWorkspace/modise-file-upload/src/main/webapp/WEB-INF/resources/uploaded-images/" + id + ".png");
108+
109+
if(Files.exists(path)){
110+
try {
111+
Files.delete(path);
112+
} catch (IOException e) {
113+
// TODO Auto-generated catch block
114+
e.printStackTrace();
115+
}
116+
}
117+
118+
userService.deleteUser(id);
119+
return "redirect:/usersList?delete=1";
120+
}
121+
122+
123+
124+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package modisefileupload.java.dao;
2+
3+
import org.springframework.data.repository.CrudRepository;
4+
import org.springframework.stereotype.Repository;
5+
6+
import modisefileupload.java.domain.User;
7+
8+
@Repository
9+
public interface UserDAO extends CrudRepository<User, Long>{
10+
//no need to implement extra methods, will use the default save method provided
11+
//by the CrudRepository class
12+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package modisefileupload.java.domain;
2+
3+
import javax.persistence.Column;
4+
import javax.persistence.Entity;
5+
import javax.persistence.GeneratedValue;
6+
import javax.persistence.GenerationType;
7+
import javax.persistence.Id;
8+
import javax.persistence.Table;
9+
import javax.persistence.Transient;
10+
import javax.validation.constraints.Min;
11+
import javax.validation.constraints.NotNull;
12+
13+
import org.hibernate.validator.constraints.NotEmpty;
14+
import org.springframework.web.multipart.MultipartFile;
15+
/**
16+
* In this class we will turn all the Class attributes into database table components
17+
* adding data validations
18+
* @author mrmodise
19+
*
20+
*/
21+
@Entity
22+
@Table(name="user")
23+
public class User {
24+
@Id
25+
@GeneratedValue(strategy = GenerationType.AUTO)
26+
@Column(name="userId",unique=true, nullable=false)
27+
private Long userId;
28+
29+
@Column(name="firstName", nullable=false)
30+
@NotEmpty(message="The first name must be captured")
31+
private String firstName;
32+
33+
@Column(name="lastName", nullable=false)
34+
@NotEmpty(message="The last name must be captured")
35+
private String lastName;
36+
37+
@Column(name="address", nullable=false)
38+
@NotEmpty(message="The address details must be captured")
39+
private String address;
40+
41+
@Column(name="age", nullable=false)
42+
@Min(value=0, message="Age cannot be less than 1")
43+
@NotNull(message="The age must be captured")
44+
private int age;
45+
46+
@Transient
47+
private MultipartFile userImage;
48+
49+
public Long getUserId() {
50+
return userId;
51+
}
52+
public void setUserId(Long userId) {
53+
this.userId = userId;
54+
}
55+
public String getFirstName() {
56+
return firstName;
57+
}
58+
public void setFirstName(String firstName) {
59+
this.firstName = firstName;
60+
}
61+
public String getLastName() {
62+
return lastName;
63+
}
64+
public void setLastName(String lastName) {
65+
this.lastName = lastName;
66+
}
67+
public String getAddress() {
68+
return address;
69+
}
70+
public void setAddress(String address) {
71+
this.address = address;
72+
}
73+
public int getAge() {
74+
return age;
75+
}
76+
public void setAge(int age) {
77+
this.age = age;
78+
}
79+
public MultipartFile getUserImage() {
80+
return userImage;
81+
}
82+
public void setUserImage(MultipartFile userImage) {
83+
this.userImage = userImage;
84+
}
85+
86+
87+
88+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package modisefileupload.java.service;
2+
3+
import java.util.List;
4+
5+
import modisefileupload.java.domain.User;
6+
7+
public interface UserService {
8+
//needed for saving data to the database
9+
void saveUser(User user);
10+
List<User> listAllUsers();
11+
void deleteUser(long id);
12+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package modisefileupload.java.service.impl;
2+
3+
import java.util.List;
4+
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
7+
import modisefileupload.java.dao.UserDAO;
8+
import modisefileupload.java.domain.User;
9+
import modisefileupload.java.service.UserService;
10+
11+
public class UserServiceImpl implements UserService {
12+
13+
@Autowired
14+
private UserDAO userDao;
15+
16+
@Override
17+
public void saveUser(User user) {
18+
//using the CrudRepository we can easily save the user data to the database
19+
//no need to implemenent our own save method
20+
userDao.save(user);
21+
}
22+
23+
@Override
24+
public List<User> listAllUsers() {
25+
//again we use the default method of CrudRepository to get all users
26+
return (List<User>) userDao.findAll();
27+
}
28+
29+
@Override
30+
public void deleteUser(long id) {
31+
userDao.delete(id);
32+
}
33+
34+
}

0 commit comments

Comments
 (0)