Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // RegistrationController.java
- @RestController
- public class DayLeasingUserController {
- @RequestMapping(value = "/registration/landowner/fileupload", method = RequestMethod.POST)
- public ResponseEntity<HashMap<String, Boolean>> handleFileUpload(
- @RequestParam(value="email")String email,@RequestParam("fname")String fname,@RequestParam("lname")String lname,
- @RequestParam("city")String city,@RequestParam("phone1")String phone1,@RequestParam("phone2")String phone2,
- @RequestParam("phone3")String phone3,@RequestParam("streetAddressLine1")String streetAddressLine1,
- @RequestParam(value="streetAddressLine2",required = false)String streetAddressLine2,@RequestParam("stripeApiKey")String stripeApiKey,
- @RequestParam("zipcode")String zipCode,@RequestParam(value="businessName",required=false)String businessName,
- @RequestParam("file") MultipartFile[] files,@RequestParam("landOwnerEditProfile")boolean landOwnerEditProfile,Model model) throws IOException {
- // @RequestParam("file") String[] files,@RequestParam("landOwnerEditProfile")boolean landOwnerEditProfile,Model model) throws IOException {
- // @RequestParam("file") MultipartFile multipartRequest)throws IOException{
- HashMap<String, Boolean> hashMap = new HashMap<String, Boolean>();
- DayLeasingUserDTO dayleasinguserDto =new DayLeasingUserDTO();
- try {
- dayleasinguserDto.setEmailId(email);
- dayleasinguserDto.setFname(fname);
- dayleasinguserDto.setLname(lname);
- dayleasinguserDto.setCity(city);
- dayleasinguserDto.setPhone(phone1+phone2+phone3);
- dayleasinguserDto.setAddress1(streetAddressLine1);
- dayleasinguserDto.setAddress2(streetAddressLine2);
- dayleasinguserDto.setStripeApiKey(stripeApiKey);
- dayleasinguserDto.setZipCode(zipCode);
- dayleasinguserDto.setBusinessName(businessName);
- dayLeasingUserService.userUpdateOnUserName(dayleasinguserDto, email);
- if(landOwnerEditProfile) {
- dayLeasingUserService.deleteDocumentsByUserName(email);
- }
- /*for(String file : files) {
- userDocument.setFiledata(file.getBytes());
- userDocument.setFilename(file.toString());
- userDocument.setUsername(email);
- dayLeasingUserService.addDocument(userDocument);
- }*/
- for(MultipartFile file : files) {
- userDocument.setFiledata(file.getBytes());
- userDocument.setFilename(file.getOriginalFilename());
- userDocument.setUsername(email);
- dayLeasingUserService.addDocument(userDocument);
- }
- hashMap.put("status",true);
- boolean detailsUpdated = userDao.enableUserDetails(email);
- hashMap.put("detailsUpdated",detailsUpdated);
- // storageService.store(file);
- // model.addAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
- // files.add(file.getOriginalFilename());
- } catch (Exception e) {
- // dayLeasingUserService.userDeleteOnUserName(dayleasinguserDto, dayleasinguserDto.getEmailId());
- hashMap.put("status", false);
- }
- return new ResponseEntity<HashMap<String, Boolean>>(hashMap, HttpStatus.OK);
- }
- }
- // Configuration.java
- package com.dayLeasing.configuration;
- // TODO: Auto-generated Javadoc
- @EnableScheduling
- @PropertySource("classpath:application.properties")
- @EnableTransactionManagement
- public class Configuration {
- /** The Constant PROPERTY_NAME_DATABASE_DRIVER. */
- private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
- /** The Constant PROPERTY_NAME_DATABASE_PASSWORD. */
- private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
- /** The Constant PROPERTY_NAME_DATABASE_URL. */
- private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
- /** The Constant PROPERTY_NAME_DATABASE_USERNAME. */
- private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
- /** The Constant PROPERTY_NAME_HIBERNATE_DIALECT. */
- private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
- /** The Constant PROPERTY_NAME_HIBERNATE_SHOW_SQL. */
- private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
- // private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN
- // =
- // "entitymanager.packages.to.scan";
- /** The env. */
- @Resource
- private Environment env;
- /** The day leasing user service. */
- @Autowired
- DayLeasingUserService dayLeasingUserService;
- /** The mail util. */
- @Autowired
- MailUtil mailUtil;
- /** The property reservation service. */
- @Autowired
- public PropertyReservationService propertyReservationService;
- /*
- * @Override public void addResourceHandlers(ResourceHandlerRegistry
- * registry) {
- * registry.addResourceHandler("/resources/**").addResourceLocations
- * ("/resources/"); }
- */
- /*
- * @Bean public LocalContainerEntityManagerFactoryBean
- * entityManagerFactory() throws IllegalStateException,
- * PropertyVetoException { final LocalContainerEntityManagerFactoryBean em =
- * new LocalContainerEntityManagerFactoryBean();
- * em.setDataSource(dataSource()); em.setPackagesToScan(new String[] {
- * "com.gi.insite.persistence.model" }); final HibernateJpaVendorAdapter
- * vendorAdapter = new HibernateJpaVendorAdapter();
- * em.setJpaVendorAdapter(vendorAdapter);
- * em.setJpaProperties(additionalProperties()); return em; }
- */
- /*
- * @Bean(destroyMethod="") public DataSource dataSource() { final
- * JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
- * dsLookup.setResourceRef(true); DataSource dataSource =
- * dsLookup.getDataSource("java:comp/env/jdbc/DGSDB"); return dataSource; }
- */
- @Bean
- public DataSource dataSource() throws IllegalStateException,
- PropertyVetoException {
- ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
- comboPooledDataSource.setDriverClass(env
- .getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
- comboPooledDataSource.setJdbcUrl(env
- .getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
- comboPooledDataSource.setUser(env
- .getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
- comboPooledDataSource.setPassword(env
- .getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
- comboPooledDataSource.setInitialPoolSize(5);
- comboPooledDataSource.setMinPoolSize(5);
- comboPooledDataSource.setMaxPoolSize(50000);
- comboPooledDataSource.setAcquireIncrement(20);
- comboPooledDataSource.setMaxStatements(100);
- comboPooledDataSource.setAcquireRetryAttempts(100);
- comboPooledDataSource.setAcquireRetryDelay(10);
- comboPooledDataSource.setBreakAfterAcquireFailure(false);
- comboPooledDataSource.setMaxIdleTime(200);
- comboPooledDataSource.setMaxConnectionAge(30000);
- comboPooledDataSource.setMaxIdleTimeExcessConnections(3000);
- //comboPooledDataSource.setCheckoutTimeout(1000);
- //comboPooledDataSource.setIdleConnectionTestPeriod(100);
- comboPooledDataSource.setTestConnectionOnCheckout(true);
- comboPooledDataSource.setPreferredTestQuery("SELECT 1");
- comboPooledDataSource.setTestConnectionOnCheckin(true);
- return comboPooledDataSource;
- }
- @Bean(name = "sessionFactory1")
- public SessionFactory getSessionFactory(DataSource dataSource) {
- LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(
- dataSource);
- sessionBuilder.addProperties(hibernateProperties());
- sessionBuilder
- .scanPackages(new String[] { "com.dayLeasing.dao.model" });
- return sessionBuilder.buildSessionFactory();
- }
- /**
- * Hibernate properties.
- *
- * @return the properties
- */
- private Properties hibernateProperties() {
- Properties properties = new Properties();
- properties.put(PROPERTY_NAME_HIBERNATE_DIALECT,
- env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
- properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL,
- env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
- return properties;
- }
- /**
- * Transaction manager.
- *
- * @param sessionFactory
- * the session factory
- * @return the hibernate transaction manager
- */
- @Bean(name = "transactionManager")
- public HibernateTransactionManager transactionManager(
- SessionFactory sessionFactory) {
- HibernateTransactionManager transactionManager = new HibernateTransactionManager(
- sessionFactory);
- return transactionManager;
- }
- /**
- * Content negotiating view resolver.
- *
- * @param manager
- * the manager
- * @return the view resolver
- */
- @Bean
- public ViewResolver contentNegotiatingViewResolver(
- ContentNegotiationManager manager) {
- List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
- InternalResourceViewResolver r1 = new InternalResourceViewResolver();
- r1.setPrefix("/WEB-INF/pages/");
- r1.setSuffix(".jsp");
- r1.setViewClass(JstlView.class);
- resolvers.add(r1);
- JsonViewResolver r2 = new JsonViewResolver();
- resolvers.add(r2);
- ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
- resolver.setViewResolvers(resolvers);
- resolver.setContentNegotiationManager(manager);
- return resolver;
- }
- /**
- * Gets the multipart resolver.
- *
- * @return the multipart resolver
- */
- /*
- This part is added for multipartfile upload.
- */
- // @Bean(name = "multipartResolver")
- // public CommonsMultipartResolver getMultipartResolver() {
- // /* return new CommonsMultipartResolver(); */
- //
- // CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
- // multipartResolver.setMaxUploadSize(20971520); // 20MB
- // multipartResolver.setMaxInMemorySize(1048576); // 1MB
- // return multipartResolver;
- // }
- @Bean(name = "multipartResolver")
- public CommonsMultipartResolver multipartResolver() {
- CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
- multipartResolver.setMaxUploadSize(100000);
- return multipartResolver;
- }
- @Bean(name = "verifymail")
- public String getMailVerificationString(){
- Path path;
- try {
- path = Paths.get(getClass().getClassLoader()
- .getResource("Verify.txt").toURI());
- byte[] fileBytes = Files.readAllBytes(path);
- String data = new String(fileBytes);
- return data;
- } catch (URISyntaxException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- return "texttoreplacehere";
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- return "texttoreplacehere";
- }
- }
- /**
- * View resolver for returning JSON in a view-based system. Always returns a
- * {@link MappingJacksonJsonView}.
- */
- public class JsonViewResolver implements ViewResolver {
- /*
- * (non-Javadoc)
- *
- * @see
- * org.springframework.web.servlet.ViewResolver#resolveViewName(java
- * .lang.String, java.util.Locale)
- */
- @Override
- public View resolveViewName(String viewName, Locale locale)
- throws Exception {
- MappingJackson2JsonView view = new MappingJackson2JsonView();
- view.setPrettyPrint(true);
- return view;
- }
- /*
- * @Bean public ViewResolver jsonViewResolver() { return new
- * JsonViewResolver(); }
- */
- }
- /**
- * Property place holder configurer.
- *
- * @return the property sources placeholder configurer
- */
- @Bean
- public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
- return new PropertySourcesPlaceholderConfigurer();
- }
- /**
- * Locale resolver.
- *
- * @return the locale resolver
- */
- @Bean
- public LocaleResolver localeResolver() {
- final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
- cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
- return cookieLocaleResolver;
- }
- }
- }
- }
- // JWTLoginFilter.java
- package com.dayLeasing.configuration.security;
- import com.dayLeasing.dao.DayLeasingUserDao;
- import com.dayLeasing.dao.model.DayleasingUsers;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.security.authentication.AuthenticationManager;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
- import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
- import javax.servlet.FilterChain;
- import javax.servlet.ServletException;
- import javax.servlet.ServletInputStream;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.util.Collections;
- import java.util.Enumeration;
- import java.util.Map;
- // TODO: Auto-generated Javadoc
- public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
- static final String ORIGIN = "Origin";
- public JWTLoginFilter(String url, AuthenticationManager authManager) {
- super(new AntPathRequestMatcher(url));
- setAuthenticationManager(authManager);
- }
- @Override
- public Authentication attemptAuthentication(HttpServletRequest req,
- HttpServletResponse res) throws AuthenticationException,
- IOException, ServletException {
- ServletInputStream inputStream = req.getInputStream();
- HttpServletRequest request = (HttpServletRequest) req;
- System.out.println("CORSFilter HTTP Request: " + request.getMethod());
- // Authorize (allow) all domains to consume the content
- ((HttpServletResponse) res).addHeader("Access-Control-Allow-Origin",
- "*");
- ((HttpServletResponse) res).addHeader("Access-Control-Allow-Methods",
- "GET, OPTIONS, HEAD, PUT, POST,DELETE");
- ((HttpServletResponse) res).addHeader("Access-Control-Allow-Headers",
- request.getHeader("Access-Control-Request-Headers"));
- HttpServletResponse resp = (HttpServletResponse) res;
- // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per
- // CORS handshake
- if (request.getMethod().equals("OPTIONS")) {
- resp.setStatus(HttpServletResponse.SC_ACCEPTED);
- return null;
- }
- // pass the request along the filter chain
- Enumeration<String> headerNames = req.getHeaderNames();
- String string = inputStream.toString();
- Map<String, String[]> parameter = req.getParameterMap();
- AccountCredentials creds;
- try {
- creds = new ObjectMapper().readValue(req.getInputStream(),
- AccountCredentials.class);
- return getAuthenticationManager().authenticate(
- new UsernamePasswordAuthenticationToken(
- creds.getUsername(), creds.getPassword(),
- Collections.emptyList()));
- } catch (Exception e) {
- resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
- return null;
- }
- }
- /*
- * (non-Javadoc)
- * @see org.springframework.security.web.authentication.
- * AbstractAuthenticationProcessingFilter#
- * successfulAuthentication(javax.servlet.http.HttpServletRequest,
- * javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain,
- * org.springframework.security.core.Authentication)
- */
- @Override
- protected void successfulAuthentication(HttpServletRequest req,
- HttpServletResponse res, FilterChain chain, Authentication auth)
- throws IOException, ServletException {
- TokenAuthenticationService.addAuthentication(res, auth.getName(),
- auth.getCredentials(), auth.getAuthorities());
- }
- }
- // JWTAuthenticationFilter.java
- package com.dayLeasing.configuration.security;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.web.filter.GenericFilterBean;
- import org.springframework.security.core.Authentication;
- import javax.servlet.FilterChain;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.util.Enumeration;
- // TODO: Auto-generated Javadoc
- public class JWTAuthenticationFilter extends GenericFilterBean {
- /*
- * (non-Javadoc)
- * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
- * javax.servlet.ServletResponse, javax.servlet.FilterChain)
- */
- @Override
- public void doFilter(ServletRequest req, ServletResponse res,
- FilterChain filterChain) throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) req;
- System.out.println("CORSFilter HTTP Request: " + request.getMethod());
- // Authorize (allow) all domains to consume the content
- ((HttpServletResponse) res).addHeader("Access-Control-Allow-Origin",
- "*");
- ((HttpServletResponse) res).addHeader("Access-Control-Allow-Methods",
- "GET, OPTIONS, HEAD, PUT, POST,DELETE");
- ((HttpServletResponse) res).addHeader("Access-Control-Allow-Headers",
- request.getHeader("Access-Control-Request-Headers"));
- HttpServletResponse resp = (HttpServletResponse) res;
- // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per
- // CORS handshake
- if (request.getMethod().equals("OPTIONS")) {
- resp.setStatus(HttpServletResponse.SC_ACCEPTED);
- return;
- }
- // Authentication authentication2 =
- // SecurityContextHolder.getContext().getAuthentication();
- else {
- Authentication authentication = TokenAuthenticationService
- .getAuthentication((HttpServletRequest) request);
- SecurityContextHolder.getContext()
- .setAuthentication(authentication);
- }
- filterChain.doFilter(req, res);
- }
- }
- // SecurityApplicationInitializer.java
- package com.dayLeasing.configuration.security;
- import javax.servlet.ServletContext;
- import org.springframework.core.annotation.Order;
- import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
- import org.springframework.web.multipart.support.MultipartFilter;
- public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
- @Override
- @Order
- protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
- insertFilters(servletContext, new MultipartFilter());
- }
- }
- // WebSecurityConfig.java
- package com.dayLeasing.configuration.security;
- // TODO: Auto-generated Javadoc
- @Configuration
- @EnableWebSecurity
- public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
- /** The user details service. */
- @Autowired
- @Qualifier("userDetailsService")
- UserDetailsService userDetailsService;
- /*
- * (non-Javadoc)
- * @see
- * org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
- * #configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
- */
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf()
- .disable()
- .authorizeRequests()
- .antMatchers("/")
- .permitAll()
- .antMatchers("/registration/**")
- .permitAll()
- .antMatchers("/landOwners/**")
- .permitAll()
- .antMatchers("/town/**")
- .permitAll()
- .antMatchers("/check")
- .permitAll()
- .antMatchers("/sendVerification")
- .permitAll()
- .antMatchers(HttpMethod.POST,"/login")
- .permitAll()
- .antMatchers(HttpMethod.GET,"/hunter/**")
- .permitAll()
- .antMatchers(HttpMethod.POST,"/hunter/reservation")
- .permitAll()
- .antMatchers("/admin/**")
- .hasAuthority("ADMIN")
- .antMatchers("/user/**")
- .hasAuthority("USER")
- .antMatchers("/hunter/**")
- .hasAuthority("HUNTER")
- .anyRequest()
- .authenticated()
- .and()
- // We filter the api/login requests
- .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
- UsernamePasswordAuthenticationFilter.class)
- // And filter other requests to check the presence of JWT in header
- .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
- }
- @Override
- public void configure(WebSecurity web) throws Exception {
- web.ignoring().antMatchers("/resources/**", "/v2/api-docs", "/configuration/ui",
- "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**",
- "/images/**"); // #3
- }
- /*
- * (non-Javadoc)
- * @see
- * org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
- * #configure(org.springframework.security.config.annotation.authentication.builders.
- * AuthenticationManagerBuilder)
- */
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- // Create a default account to test
- auth.userDetailsService(userDetailsService);
- }
- /**
- * Password encoder.
- *
- * @return the password encoder
- */
- @Bean
- public PasswordEncoder passwordEncoder() {
- PasswordEncoder encoder = new BCryptPasswordEncoder();
- return encoder;
- }
- }
- [1]: https://i.stack.imgur.com/fHZ2g.png
Add Comment
Please, Sign In to add comment