Commit 58ae30a7 authored by Thayaanathan E.V's avatar Thayaanathan E.V

Commit 01

parent d07d8804
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
This diff is collapsed.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. 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,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.swmrs</groupId>
<artifactId>SWMRS</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>SWMRS</name>
<description>Smart Water Meter Reading System</description>
<properties>
<java.version>1.8</java.version>
<spring-security-oauth2.version>2.3.5.RELEASE</spring-security-oauth2.version>
<spring-security-jwt.version>1.0.9.RELEASE</spring-security-jwt.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Security OAuth2 and JWT -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring-security-oauth2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>${spring-security-jwt.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--Mail-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.swmrs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
@EnableScheduling
public class SwmrsApplication {
public static void main(String[] args) {
SpringApplication.run(SwmrsApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
};
}
}
package com.swmrs.config;
import org.springframework.security.core.GrantedAuthority;
import java.io.Serializable;
public class CustomGrantedAuthority implements GrantedAuthority, Serializable {
private String name;
public CustomGrantedAuthority(String name) {
this.name = name;
}
@Override
public String getAuthority() {
return name;
}
}
\ No newline at end of file
package com.swmrs.config;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Set;
@SuppressWarnings("serial")
public class CustomUserDetails implements UserDetails {
private String userName;
private String password;
private Set<GrantedAuthority> grantedAuthorities;
public CustomUserDetails() {
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return grantedAuthorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return userName;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Set<GrantedAuthority> getGrantedAuthorities() {
return grantedAuthorities;
}
public void setGrantedAuthorities(Set<GrantedAuthority> grantedAuthorities) {
this.grantedAuthorities = grantedAuthorities;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.swmrs.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Value("${security.jwt.client-id}")
private String clientId;
@Value("${security.jwt.client-secret}")
private String clientSecret;
@Value("${security.jwt.grant-type}")
private String grantType;
@Value("${security.jwt.scope-read}")
private String scopeRead;
@Value("${security.jwt.scope-write}")
private String scopeWrite = "write";
@Autowired
UserDetailsService userDetailsService;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
// Configure the token store and authentication manager
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//@formatter:off
endpoints
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter()) // added for JWT
.authenticationManager(authenticationManager).userDetailsService(userDetailsService);
//@formatter:on
}
// Configure a client store. In-memory for simplicity, but consider other
// options for real apps.
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//@formatter:off
clients
.inMemory()
.withClient(clientId)
.secret(clientSecret)// have to explore the usage of password encoder
.authorizedGrantTypes("authorization_code", "implicit", "password", "client_credentials", "refresh_token")
.scopes(scopeRead,scopeWrite)
.redirectUris("http://localhost:9191/x")//not know the exact usage refer read me.
.accessTokenValiditySeconds(86400); // 24 hours
//@formatter:on
}
// A token store bean. JWT token store
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter()); // For JWT. Use in-memory, jdbc, or other if not JWT
}
// Token converter. Needed for JWT
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123"); // symmetric key
return converter;
}
// Token services. Needed for JWT
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
}
package com.swmrs.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
//@formatter:off
http
.requestMatchers()
.and()
.authorizeRequests()
.antMatchers("/log").authenticated()
.anyRequest().permitAll();
//@formatter:on
}
}
package com.swmrs.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@SuppressWarnings("deprecation") // For NoOpPasswordEncoder
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS);
}
//for accepting a text password which is saved as encrypted in db
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
// Using NoOpPasswordEncoder for simplicity's sake
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
// @Bean
// public PasswordEncoder pass(){
// return new BCryptPasswordEncoder();
// }
}
package com.swmrs.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SpringFoxConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
\ No newline at end of file
package com.swmrs.config;
import com.swmrs.enums.UserState;
import com.swmrs.model.UserCredential;
import com.swmrs.repo.UserCredentialRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.Set;
@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserCredentialRepo userCredentialRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserCredential userCredential = userCredentialRepo.findByUsername(username);
//Only Active users can generate an access token.
if (userCredential != null&& (UserState.ACTIVE.equals(userCredential.getStatus()))) {
CustomUserDetails customUserDetails = new CustomUserDetails();
customUserDetails.setUserName(userCredential.getUsername());
customUserDetails.setPassword(userCredential.getPassword());
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
authorities.add(new CustomGrantedAuthority(userCredential.getRole().toString()));
customUserDetails.setGrantedAuthorities(authorities);
return customUserDetails;
}
throw new UsernameNotFoundException(username);
}
}
\ No newline at end of file
This diff is collapsed.
package com.swmrs.controller;
import com.swmrs.model.Consumer;
import com.swmrs.model.Payment;
import com.swmrs.objects.ReturnMessage;
import com.swmrs.repo.ConsumerRepo;
import com.swmrs.repo.PaymentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Timestamp;
import java.util.Date;
@RestController
public class PaymentController {
@Autowired
private PaymentRepo paymentRepo;
@Autowired
private ConsumerRepo consumerRepo;
@PostMapping(path = "/pay", produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CONSUMER')")
public ReturnMessage pay(@RequestParam String userId, @RequestParam Double payment, @RequestParam Date date){
try {
Payment paymentInfo = new Payment();
Consumer consumer = consumerRepo.findByUserId(userId);
Timestamp timestamp = new Timestamp(date.getTime());
double currentDue = consumer.getDueAmount()-payment;
paymentInfo.setUserId(userId);
paymentInfo.setPreviousDue(consumer.getDueAmount());
paymentInfo.setPaymentDate(timestamp);
paymentInfo.setPaymentAmount(payment);
paymentInfo.setCurrentOutstanding(currentDue);
consumer.setLastPayment(payment);
consumer.setLastPaymentDate(timestamp);
consumer.setDueAmount(currentDue);
paymentRepo.save(paymentInfo);
consumerRepo.save(consumer);
return new ReturnMessage("Your payment recorded!");
}
catch (Exception e){
return new ReturnMessage(e.getMessage());
}
}
@GetMapping(path = "/getPayment",produces = "application/json")
@PreAuthorize("hasAuthority('CONSUMER')")
public Iterable<Payment> getPayment(@RequestParam String userId){
return paymentRepo.findAllByUserId(userId);
}
@GetMapping(path = "/payments",produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN') ")
public Iterable<Payment> payments(){
return paymentRepo.findAll();
}
@GetMapping(path = "/hasDues",produces = "application/json")
// @PreAuthorize("hasAuthority('ADMIN') ")
public Iterable<Consumer> hasDues(){
return consumerRepo.hasDues();
}
@GetMapping(path = "/hasExcessBalance",produces = "application/json")
// @PreAuthorize("hasAuthority('ADMIN') ")
public Iterable<Consumer> hasExcessBalance(){
return consumerRepo.hasExcessBalance();
}
}
package com.swmrs.controller;
import com.swmrs.enums.Districts;
import com.swmrs.model.Consumer;
import com.swmrs.model.Usage;
import com.swmrs.objects.DistrictUsage;
import com.swmrs.objects.ReturnMessage;
import com.swmrs.objects.SmtpMailSender;
import com.swmrs.repo.ConsumerRepo;
import com.swmrs.repo.UsageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
public class UsageController {
@Autowired
private UsageRepo usageRepo;
@Autowired
private ConsumerRepo consumerRepo;
@Autowired
private SmtpMailSender smtpMailSender;
@PostMapping(path = "/addUsage", produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN')")
public ReturnMessage addUsage(@RequestParam String userId, @RequestParam Date timeStamp, @RequestParam int reading){
try{
System.out.println("time = " + timeStamp);
Usage usage = new Usage();
usage.setUserId(userId);
usage.setReading(reading);
usage.setTime(new Timestamp(timeStamp.getTime()));
usageRepo.save(usage);
return new ReturnMessage("Usage was successfully recorded");
}
catch (Exception e){
return new ReturnMessage(e.getMessage());
}
}
@GetMapping(path = "/payment-callback")
public void getPayent(@RequestBody RequestBody r){
System.out.println("r = " + r);
}
@GetMapping(path = "/usages",produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN')")
public Iterable<Usage> usages(){
return usageRepo.findAll();
}
@GetMapping(path = "/getUsageByUser",produces = "application/json")
@PreAuthorize("hasAuthority('CONSUMER')")
public Iterable<Usage> getUsageByUser(@RequestParam String userId){
return usageRepo.findAllByUserId(userId);
}
@GetMapping(path = "/usagesInInterval",produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN')")
public Iterable<Usage> usagesInInterval(@RequestParam Date startDate, @RequestParam Date endDate ){
return usageRepo.findUsageByInterval(new Timestamp(startDate.getTime()),new Timestamp(endDate.getTime()));
}
@GetMapping(path = "/getUsageInIntervalByUser",produces = "application/json")
@PreAuthorize("hasAuthority('CONSUMER')")
public Iterable<Usage> getUsageInIntervalByUser(@RequestParam String userId, @RequestParam Date startDate,
@RequestParam Date endDate ){
return usageRepo.findUserUsageByInterval(new Timestamp(startDate.getTime()),new Timestamp(endDate.getTime()),
userId);
}
@GetMapping(path = "/districtMonthlyUsage",produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CONSUMER')")
public List<DistrictUsage> districtMonthlyUsage(){
List<DistrictUsage> usageDetail = new ArrayList<DistrictUsage>();
for (Districts district: Districts.values()) {
long sum = 0;
Iterable<Consumer> consumers = consumerRepo.findByDistrict(district.toString());
for (Consumer consumer : consumers) {
Usage usage = usageRepo.findLastUsageByUserId(consumer.getUserId());
if(usage!=null) {
sum = sum + usage.getReading();
}
}
DistrictUsage districtUsage = new DistrictUsage();
districtUsage.setDistrict(district.toString());
districtUsage.setUsage(sum);
usageDetail.add(districtUsage);
}
return usageDetail;
}
@GetMapping("/sendMail")
@PreAuthorize("hasAuthority('ADMIN')")
public void sendMail() {
try {
smtpMailSender.send("kasthuriraajan94@gmail.com", "Test mail from Spring",
"<html>\n" +
" <head>\n" +
" <style>\n" +
" .colored {\n" +
" color: blue;\n" +
" }\n" +
" #body {\n" +
" font-size: 14px;\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <div id='body'>\n" +
" <p>Hi Pierce,</p>\n" +
" <p class='colored'>This text is blue.</p>\n" +
" <p>Jerry</p>\n" +
" </div>\n" +
" </body>\n" +
"</html>\n");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
package com.swmrs.controller;
import com.swmrs.enums.Districts;
import com.swmrs.enums.Tariff;
import com.swmrs.enums.UserRole;
import com.swmrs.enums.UserState;
import com.swmrs.model.Consumer;
import com.swmrs.model.UserCredential;
import com.swmrs.objects.ConsumerInfo;
import com.swmrs.objects.ReturnMessage;
import com.swmrs.objects.SmtpMailSender;
import com.swmrs.repo.ConsumerRepo;
import com.swmrs.repo.UserCredentialRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import java.sql.Timestamp;
import java.util.Date;
@RestController
public class UserController {
@Autowired
private UserCredentialRepo userCredentialRepo;
@Autowired
private ConsumerRepo consumerRepo;
@Autowired
private SmtpMailSender smtpMailSender;
@PostMapping(path = "/addUser", produces = "application/json")
// @PreAuthorize("hasAuthority('ADMIN')")
public ReturnMessage addUser(@RequestParam String username){
try {
UserCredential userCredential = new UserCredential();
userCredential.setUsername(username);
userCredential.setPassword(new BCryptPasswordEncoder().encode("SamplePassword"));
userCredential.setRole(UserRole.ADMIN);
userCredential.setStatus(UserState.ACTIVE);
userCredentialRepo.save(userCredential);
return new ReturnMessage("You have added user - "+username+ "-" + "successfully");
}
catch (Exception e){
return new ReturnMessage(e.getMessage());
}
}
@GetMapping(path = "/showUserCredential")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CONSUMER')")
public @ResponseBody
Iterable<UserCredential> showUserCredential()
{
return userCredentialRepo.findAll();
}
@GetMapping(path = "/getUserCredential",produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CONSUMER')")
public UserCredential getUserCredential(@RequestParam(value = "username") String username){
return userCredentialRepo.findByUsername(username);
}
@PostMapping(path = "/addConsumer", produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN')")
public ReturnMessage addConsumer(@RequestBody ConsumerInfo consumerInfo){
try {
Tariff tariff = Tariff.DOMESTIC_NON_SAMURDHI;
Consumer consumer = new Consumer(consumerInfo.getUserId(), consumerInfo.getFirstName(),
consumerInfo.getLastName(), consumerInfo.getEmail(), consumerInfo.getAddress(),
consumerInfo.getContactNo(), consumerInfo.getPostalCode(),consumerInfo.getConnectionType(),
consumerInfo.getDistrict());
consumer.setLastBilledDate(new Timestamp(new Date().getTime()));
UserCredential userCredential = new UserCredential();
userCredential.setUsername(consumerInfo.getUserId());
userCredential.setPassword(new BCryptPasswordEncoder().encode("SamplePassword"));
userCredential.setRole(UserRole.CONSUMER);
userCredential.setStatus(UserState.ACTIVE);
consumerRepo.save(consumer);
userCredentialRepo.save(userCredential);
try {
smtpMailSender.send(consumerInfo.getEmail(), "SWMRS Account Details",
"<html>\n" +
" <head>\n" +
" </head>\n" +
" <body>\n" +
" <div id='body'>\n" +
" <p>Hi "+consumerInfo.getFirstName()+",</p><br/>\n" +
" <p >Welcome to Smart Water Meter Reading System . We have created a user " +
"account for you. " +
"</p> <h3>User ID : \n" + consumerInfo.getUserId() +
" </h3> <h3> Password : SamplePassword </h3><br/> <p> You can use above credential to" +
" login to the system. You can change your password later yourself. If you find any " +
"difficulties, don't hesitate to contact administrators using this email or in any " +
"other mediums. </p> <p> Thank you </p> <br/> <p>Best Regards, </p> " +
"<p>Admin, </p><p>SWMRS</p>\n" +
" </div>\n" +
" </body>\n" +
"</html>\n");
} catch (MessagingException e) {
e.printStackTrace();
}
return new ReturnMessage("User "+consumerInfo.getUserId()+ "-" +consumerInfo.getFirstName()+
" was added successfully");
}
catch (Exception e){
return new ReturnMessage(e.getMessage());
}
}
@GetMapping(path = "/ConsumersList")
@PreAuthorize("hasAuthority('ADMIN')")
public @ResponseBody
Iterable<Consumer> consumersList()
{
return consumerRepo.findAll();
}
@GetMapping(path = "/getConsumer",produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CONSUMER')")
public Consumer getConsumer(@RequestParam(value = "userId") String userId){
return consumerRepo.findByUserId(userId);
}
@GetMapping(path = "/consumerTypes",produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CONSUMER')")
public Tariff[] consumerTypes() {
return Tariff.values();
}
@GetMapping(path = "/districts",produces = "application/json")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CONSUMER')")
public Districts[] districts() {
return Districts.values();
}
}
package com.swmrs.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.swmrs.enums.UserState;
import com.swmrs.model.UserCredential;
import com.swmrs.objects.LoginResponse;
import com.swmrs.objects.ReturnMessage;
import com.swmrs.repo.UserCredentialRepo;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
@RestController
public class UserCredentialController {
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
UserCredentialRepo userCredentialRepo;
@Value("${security.jwt.client-id}")
private String clientId;
@Value("${security.jwt.client-secret}")
private String clientSecret;
@Value("${security.jwt.grant-type}")
private String grantType;
@PostMapping(path = "/login")
public LoginResponse login(@RequestParam String username, @RequestParam String password) {
try {
if (userCredentialRepo.existsById(username)) {
UserCredential loginUser = userCredentialRepo.findByUsername(username);
if (loginUser.getStatus().equals(UserState.ACTIVE)) {
//get token
HttpPost getToken = new HttpPost("http://localhost:8083/oauth/token");
//Header for request
getToken.addHeader("content-type", "application/x-www-form-urlencoded");
//Parameters for request
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("username", username));
urlParameters.add(new BasicNameValuePair("password", password));
urlParameters.add(new BasicNameValuePair("grant_type", grantType));
try {
getToken.setEntity(new UrlEncodedFormEntity(urlParameters));
} catch (UnsupportedEncodingException e) {
return new LoginResponse("Something wrong in the parameter set-up of token request body",0);
}
//BasicAuth set up
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(clientId, clientSecret)
);
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
CloseableHttpResponse response = httpClient.execute(getToken);
//convert response entity as json
ObjectMapper mapper = new ObjectMapper();
JsonNode tokenDetails = mapper.readTree(EntityUtils.toString(response.getEntity()));
// assertNotNull(tokenDetails);
if (200 == response.getStatusLine().getStatusCode()) {
LoginResponse loginResponse = new LoginResponse(response.getStatusLine().getStatusCode(),
response.getStatusLine().toString(),
tokenDetails.get("access_token").asText(),
tokenDetails.get("token_type").asText(),
tokenDetails.get("refresh_token").asText(),
tokenDetails.get("expires_in").asInt(),
tokenDetails.get("scope").asText(),
tokenDetails.get("jti").asText(),1);
response.close();
httpClient.close();
return loginResponse;
} else {
LoginResponse loginResponse = new LoginResponse(response.getStatusLine().getStatusCode(),
response.getStatusLine().toString(),
tokenDetails.get("error").asText(),
tokenDetails.get("error_description").asText(),2);
response.close();
httpClient.close();
return loginResponse;
}
} catch (IOException e) {
return new LoginResponse(e.getMessage(),3);
}
}
else {
return new LoginResponse("User is not in active",4);
}
} else {
return new LoginResponse("User not exists",5);
}
} catch (Exception e) {
//need to write code for get error message for clientId, ClientSecret related errors.
return new LoginResponse(e.getMessage(),6);
}
}
@PostMapping(path = "/changePassword", produces = "application/json")
// @PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CONSUMER')")
private ReturnMessage changePassword(@RequestParam String username, @RequestParam String password,
@RequestParam String newPassword) {
try {
if (userCredentialRepo.existsById(username)) {
UserCredential user = userCredentialRepo.findByUsername(username);
if (new BCryptPasswordEncoder().matches(password, user.getPassword())) {
user.setPassword(new BCryptPasswordEncoder().encode(newPassword));
user.setStatus(UserState.ACTIVE);
userCredentialRepo.save(user);
return new ReturnMessage("You have changed your password successfully");
} else {
return new ReturnMessage("Password doesn't match");
}
} else {
return new ReturnMessage("User not exists!");
}
} catch (Exception e) {
return new ReturnMessage(e.getMessage());
}
}
}
package com.swmrs.enums;
public enum Districts {
Ampara,
Anuradhapura,
Badulla,
Batticaloa,
Colombo,
Galle,
Gampaha,
Hambantota,
Jaffna,
Kalutara,
Kandy,
Kegalle,
Kilinochchi,
Kurunegala,
Mannar,
Matale,
Matara,
Moneragala,
Mullaitivu,
NuwaraEliya,
Polonnaruwa,
Puttalam,
Ratnapura,
Trincomalee,
Vavuniya
}
package com.swmrs.enums;
public enum Tariff {
DOMESTIC_SAMURDHI,
DOMESTIC_NON_SAMURDHI,
DOMESTIC_OTHER,
// PUBLIC_STAND_POSTS_AND_GARDEN_TAPS,
SCHOOLS_AND_RELIGIOUS_INSTITUTIONS
// COMMERCIAL,
// GOVERNMENT_HOSPITALS,
// SME_INDUSTRIES,
// NON_SME_INDUSTRIES_AND_GOVERNMENT_INSTITUTIONS,
// EXPORT_PROCESSING_ZONES,
// SHIPPING,
// BULK_SUPPLY,
// COMMUNITY_BASED_ORGANIZATIONS,
// BOWSER_SUPPLY
}
package com.swmrs.enums;
public enum UserRole {
ADMIN, CONSUMER
}
package com.swmrs.enums;
public enum UserState {
ACTIVE,INACTIVE
}
package com.swmrs.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.sql.Timestamp;
@Entity
public class Bill {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(nullable = false, unique = true, updatable = false)
private int id;
@Column(length = 50, nullable = false)
private String userId;
@Column(nullable = false)
private Timestamp dateFrom;
@Column(nullable = false)
private Timestamp dateTo;
@Column(nullable = false)
private double previousDue;
@Column(nullable = false)
private int lastReading;
@Column(nullable = false)
private int currentReading;
@Column(nullable = false)
private int usage;
@Column(nullable = false)
private double usageCharge;
@Column(nullable = false)
private double serviceCharge;
@Column(nullable = false)
private double totalBeforeTax;
@Column(nullable = false)
private double vat;
@Column(nullable = false)
private double totalBillAmount;
@Column(nullable = false)
private double totalPayable;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Timestamp getDateFrom() {
return dateFrom;
}
public void setDateFrom(Timestamp dateFrom) {
this.dateFrom = dateFrom;
}
public Timestamp getDateTo() {
return dateTo;
}
public void setDateTo(Timestamp dateTo) {
this.dateTo = dateTo;
}
public double getPreviousDue() {
return previousDue;
}
public void setPreviousDue(double previousDue) {
this.previousDue = previousDue;
}
public int getLastReading() {
return lastReading;
}
public void setLastReading(int lastReading) {
this.lastReading = lastReading;
}
public int getCurrentReading() {
return currentReading;
}
public void setCurrentReading(int currentReading) {
this.currentReading = currentReading;
}
public int getUsage() {
return usage;
}
public void setUsage(int usage) {
this.usage = usage;
}
public double getUsageCharge() {
return usageCharge;
}
public void setUsageCharge(double usageCharge) {
this.usageCharge = usageCharge;
}
public double getServiceCharge() {
return serviceCharge;
}
public void setServiceCharge(double serviceCharge) {
this.serviceCharge = serviceCharge;
}
public double getTotalBeforeTax() {
return totalBeforeTax;
}
public void setTotalBeforeTax(double totalBeforeTax) {
this.totalBeforeTax = totalBeforeTax;
}
public double getVat() {
return vat;
}
public void setVat(double vat) {
this.vat = vat;
}
public double getTotalBillAmount() {
return totalBillAmount;
}
public void setTotalBillAmount(double totalBillAmount) {
this.totalBillAmount = totalBillAmount;
}
public double getTotalPayable() {
return totalPayable;
}
public void setTotalPayable(double totalPayable) {
this.totalPayable = totalPayable;
}
}
package com.swmrs.model;
import com.swmrs.enums.Tariff;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import java.sql.Timestamp;
@Entity
public class Consumer {
@Id
@Column(length = 50, nullable = false, unique = true)
private String userId;
@Column(length = 250, nullable = false)
private String firstName;
@Column(length = 250, nullable = false)
private String lastName;
@Column(length = 350, nullable = false, unique = true)
private String email;
@Column(length = 2000, nullable = false)
private String address;
@Column(length = 15, nullable = false)
private String contactNo;
@Column(length = 20, nullable = false)
private String postalCode;
@Column(length = 50, nullable = false)
private String district;
@Enumerated(EnumType.STRING)
@Column(length = 50, nullable = false)
private Tariff connectionType;
private double dueAmount;
private Timestamp lastBilledDate;
private int lastBilledReading;
private double lastPayment;
private Timestamp lastPaymentDate;
public Consumer() {
}
public Consumer(String userId, String firstName, String lastName, String email, String address, String contactNo,
String postalCode, Tariff connectionType, String district) {
this.userId = userId;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.address = address;
this.contactNo = contactNo;
this.postalCode = postalCode;
this.connectionType = connectionType;
this.district = district;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public Tariff getConnectionType() {
return connectionType;
}
public void setConnectionType(Tariff connectionType) {
this.connectionType = connectionType;
}
public double getDueAmount() {
return dueAmount;
}
public void setDueAmount(double dueAmount) {
this.dueAmount = dueAmount;
}
public double getLastPayment() {
return lastPayment;
}
public void setLastPayment(double lastPayment) {
this.lastPayment = lastPayment;
}
public Timestamp getLastBilledDate() {
return lastBilledDate;
}
public void setLastBilledDate(Timestamp lastBilledDate) {
this.lastBilledDate = lastBilledDate;
}
public int getLastBilledReading() {
return lastBilledReading;
}
public void setLastBilledReading(int lastBilledReading) {
this.lastBilledReading = lastBilledReading;
}
public Timestamp getLastPaymentDate() {
return lastPaymentDate;
}
public void setLastPaymentDate(Timestamp lastPaymentDate) {
this.lastPaymentDate = lastPaymentDate;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
}
package com.swmrs.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.sql.Timestamp;
@Entity
public class Notification {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(nullable = false, unique = true,updatable = false)
private int id;
@Column(length = 2000, nullable = false)
private String message;
@Column(nullable = false)
private Timestamp date;
public Notification() {
}
public Notification(String message, Timestamp date) {
this.message = message;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
}
package com.swmrs.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.sql.Timestamp;
@Entity
public class Payment {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(nullable = false, unique = true,updatable = false)
private int id;
@Column(length = 50, nullable = false)
private String userId;
@Column(nullable = false)
private Timestamp paymentDate;
@Column(nullable = false)
private double previousDue;
@Column(nullable = false)
private double paymentAmount;
@Column(nullable = false)
private double currentOutstanding;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Timestamp getPaymentDate() {
return paymentDate;
}
public void setPaymentDate(Timestamp paymentDate) {
this.paymentDate = paymentDate;
}
public double getPreviousDue() {
return previousDue;
}
public void setPreviousDue(double previousDue) {
this.previousDue = previousDue;
}
public double getPaymentAmount() {
return paymentAmount;
}
public void setPaymentAmount(double paymentAmount) {
this.paymentAmount = paymentAmount;
}
public double getCurrentOutstanding() {
return currentOutstanding;
}
public void setCurrentOutstanding(double currentOutstanding) {
this.currentOutstanding = currentOutstanding;
}
}
package com.swmrs.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.sql.Timestamp;
@Entity
public class Usage {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(nullable = false, unique = true,updatable = false)
private int id;
@Column(length = 50, nullable = false)
private String userId;
@Column(nullable = false)
private Timestamp time;
@Column(nullable = false)
private int reading;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public int getReading() {
return reading;
}
public void setReading(int reading) {
this.reading = reading;
}
}
package com.swmrs.model;
import com.swmrs.enums.UserRole;
import com.swmrs.enums.UserState;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
@Entity
public class UserCredential {
@Id
@Column(length = 350, nullable = false, unique = true)
private String username;
@Column(length = 250, nullable = false)
private String password;
@Enumerated(EnumType.STRING)
@Column(length = 25, nullable = false)
private UserRole role;
@Enumerated(EnumType.STRING)
@Column(length = 25, nullable = false)
private UserState status;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
public UserState getStatus() {
return status;
}
public void setStatus(UserState status) {
this.status = status;
}
}
package com.swmrs.objects;
import com.swmrs.enums.Tariff;
import java.sql.Timestamp;
import java.text.DecimalFormat;
public class Calculator {
private double [] DOMESTIC_SAMURDHI_CHARGE = {5,10,15,40,58,88,105,105,120,120,130,130,130,130,130,140};
private double [] DOMESTIC_NON_SAMURDHI_CHARGE = {8,11,20,40,58,88,105,105,120,120,130,130,130,130,130,140};
private double [] DOMESTIC_OTHER_CHARGE = {12,16,20,40,58,88,105,105,120,120,130,130,130,130,130,140};
private double [] SCHOOL_CHARGE = {6,6,6,6,6,6,6,6,16,16,16,16,16,16,16,16};
private double [] DOMESTIC_SAMURDHI_SERVICE_CHARGE = {50,50,50,80,100,200,400,400,650,650,1000,1000,1000,1000,1000,1600};
private double [] DOMESTIC_NON_SAMURDHI_SERVICE_CHARGE = {50,65,70,80,100,200,400,400,650,650,1000,1000,1000,1000,1000,1600};
private double [] DOMESTIC_OTHER_SERVICE_CHARGE = {50,65,70,80,100,200,400,400,650,650,1000,1000,1000,1000,1000,1600};
private double [] SCHOOL_SERVICE_CHARGE = {50,65,70,80,100,200,400,400,650,650,1000,1000,1000,1000,1000,1600};
private double VAT = 12;
public int getUnits(int lastReading, int currentReading){
if(lastReading>=0 && currentReading>=lastReading){
return (currentReading-lastReading);
}
else{
return -1;
}
}
public int getDays(Timestamp dateFrom, Timestamp dateTo){
long diff = dateTo.getTime()-dateFrom.getTime();
return (int) (diff/(1000*60*60*24));
}
public ChargeDetail getPayment(int units, int days, Tariff tariff){
ChargeDetail chargeDetail = new ChargeDetail();
DecimalFormat df = new DecimalFormat("#.##");
if((units>=0)&&(days>0)&&(tariff!=null)){
double [] unitCharge;
double [] serviceCharge;
double payment= 0;
switch (tariff){
case DOMESTIC_SAMURDHI:
unitCharge = DOMESTIC_SAMURDHI_CHARGE;
serviceCharge = DOMESTIC_SAMURDHI_SERVICE_CHARGE;
break;
case DOMESTIC_NON_SAMURDHI:
unitCharge = DOMESTIC_NON_SAMURDHI_CHARGE;
serviceCharge = DOMESTIC_NON_SAMURDHI_SERVICE_CHARGE;
break;
case DOMESTIC_OTHER:
unitCharge = DOMESTIC_OTHER_CHARGE;
serviceCharge = DOMESTIC_OTHER_SERVICE_CHARGE;
break;
default:
unitCharge = SCHOOL_CHARGE;
serviceCharge = SCHOOL_SERVICE_CHARGE;
break;
}
int reminder = units/5;
if(reminder>15){
reminder =15;
}
double calcUnit = (double)days/30;
for (int i=0;i<reminder;i++){
payment = payment + (unitCharge[i]* (calcUnit*5));
}
double remain = units-(calcUnit*reminder);
payment = payment + remain*unitCharge[reminder];
chargeDetail.setUsageCharge(Double.parseDouble(df.format(payment)));
chargeDetail.setServiceCharge(Double.parseDouble(df.format(serviceCharge[reminder])));
payment = payment +serviceCharge[reminder];
chargeDetail.setTotalBeforeTax(Double.parseDouble(df.format(payment)));
chargeDetail.setVat(VAT);
payment = payment+ ((payment*VAT)/100);
chargeDetail.setTotalBillAmount(Double.parseDouble(df.format(payment)));
return chargeDetail;
}
else {
chargeDetail.setTotalBillAmount(-1);
return chargeDetail;
}
}
}
package com.swmrs.objects;
public class ChargeDetail {
private double usageCharge;
private double serviceCharge;
private double totalBeforeTax;
private double vat;
private double totalBillAmount;
public double getUsageCharge() {
return usageCharge;
}
public void setUsageCharge(double usageCharge) {
this.usageCharge = usageCharge;
}
public double getServiceCharge() {
return serviceCharge;
}
public void setServiceCharge(double serviceCharge) {
this.serviceCharge = serviceCharge;
}
public double getTotalBeforeTax() {
return totalBeforeTax;
}
public void setTotalBeforeTax(double totalBeforeTax) {
this.totalBeforeTax = totalBeforeTax;
}
public double getVat() {
return vat;
}
public void setVat(double vat) {
this.vat = vat;
}
public double getTotalBillAmount() {
return totalBillAmount;
}
public void setTotalBillAmount(double totalBllAmount) {
this.totalBillAmount = totalBllAmount;
}
}
package com.swmrs.objects;
public class ConsumerDashboardCounts {
private long totalBills;
private double totalBilledAmount;
private long totalPayments;
private double totalPaymentAmount;
private long totalUnits;
public long getTotalBills() {
return totalBills;
}
public void setTotalBills(long totalBills) {
this.totalBills = totalBills;
}
public long getTotalPayments() {
return totalPayments;
}
public void setTotalPayments(long totalPayments) {
this.totalPayments = totalPayments;
}
public long getTotalUnits() {
return totalUnits;
}
public void setTotalUnits(long totalUnits) {
this.totalUnits = totalUnits;
}
public double getTotalBilledAmount() {
return totalBilledAmount;
}
public void setTotalBilledAmount(double totalBilledAmount) {
this.totalBilledAmount = totalBilledAmount;
}
public double getTotalPaymentAmount() {
return totalPaymentAmount;
}
public void setTotalPaymentAmount(double totalPaymentAmount) {
this.totalPaymentAmount = totalPaymentAmount;
}
}
package com.swmrs.objects;
import com.swmrs.enums.Tariff;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
public class ConsumerInfo {
private String userId;
private String firstName;
private String lastName;
@Enumerated(EnumType.STRING)
private Tariff ConnectionType;
private String contactNo;
private String email;
private String address;
private String postalCode;
private String district;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Tariff getConnectionType() {
return ConnectionType;
}
public void setConnectionType(Tariff connectionType) {
ConnectionType = connectionType;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
}
package com.swmrs.objects;
public class DashboardCounts {
private Long totalConsumers;
private Long totalBills;
private Double totalBilledAmount;
private Long totalPayments;
private Double totalPaymentAmount;
private Long totalUnits;
public Long getTotalConsumers() {
return totalConsumers;
}
public void setTotalConsumers(Long totalConsumers) {
this.totalConsumers = totalConsumers;
}
public Long getTotalBills() {
return totalBills;
}
public void setTotalBills(Long totalBills) {
this.totalBills = totalBills;
}
public Long getTotalPayments() {
return totalPayments;
}
public void setTotalPayments(Long totalPayments) {
this.totalPayments = totalPayments;
}
public Long getTotalUnits() {
return totalUnits;
}
public void setTotalUnits(Long totalUnits) {
this.totalUnits = totalUnits;
}
public Double getTotalBilledAmount() {
return totalBilledAmount;
}
public void setTotalBilledAmount(Double totalBilledAmount) {
this.totalBilledAmount = totalBilledAmount;
}
public Double getTotalPaymentAmount() {
return totalPaymentAmount;
}
public void setTotalPaymentAmount(Double totalPaymentAmount) {
this.totalPaymentAmount = totalPaymentAmount;
}
}
package com.swmrs.objects;
public class DistrictUsage {
private long usage;
private String district;
public long getUsage() {
return usage;
}
public void setUsage(long usage) {
this.usage = usage;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
}
package com.swmrs.objects;
public class LoginResponse {
private int statusCode;
private String statusLine;
private String access_token;
private String token_type;
private String refresh_token;
private int expires_in;
private String scope;
private String jti;
private String error;
private String error_description;
private String status;
private int status_id;
public LoginResponse(int statusCode, String statusLine, String access_token, String token_type,
String refresh_token, int expires_in, String scope, String jti, int status_id) {
this.statusCode = statusCode;
this.statusLine = statusLine;
this.access_token = access_token;
this.token_type = token_type;
this.refresh_token = refresh_token;
this.expires_in = expires_in;
this.scope = scope;
this.jti = jti;
this.status_id = status_id;
}
public LoginResponse(int statusCode, String statusLine, String error, String error_description, int status_id) {
this.statusCode = statusCode;
this.statusLine = statusLine;
this.error = error;
this.error_description = error_description;
this.status_id = status_id;
}
public LoginResponse(String status, int status_id) {
this.status = status;
this.status_id = status_id;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getStatusLine() {
return statusLine;
}
public void setStatusLine(String statusLine) {
this.statusLine = statusLine;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getJti() {
return jti;
}
public void setJti(String jti) {
this.jti = jti;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getError_description() {
return error_description;
}
public void setError_description(String error_description) {
this.error_description = error_description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getStatus_id() {
return status_id;
}
public void setStatus_id(int status_id) {
this.status_id = status_id;
}
}
package com.swmrs.objects;
public class ReturnMessage {
private String message;
public ReturnMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
package com.swmrs.objects;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.swmrs.model.Notification;
import com.swmrs.repo.NotificationRepo;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
@Component
public class Scheduler {
@Autowired
private NotificationRepo notificationRepo;
@Scheduled(cron = "0 0 0 1 * ?") //At 00:00:00am, on the 1st day, every month
public void cronJobSch() {
String msg = "";
HttpGet request = new HttpGet("http://localhost:8083/generateBill");
request.addHeader("content-type", "application/json");
request.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
".eyJleHAiOjE1OTI1NDg4MTksInVzZXJfbmFtZSI6IkpvaG4iLCJhdXRob3JpdGllcyI6WyJBRE1JTiJdLCJqdGkiOiI2MTNjNzdjYS1iMWRkLTRhMmYtYTkyYy1iNjVkOWRhNGRmMTkiLCJjbGllbnRfaWQiOiJ0ZXN0Q2xpZW50SWQiLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXX0.DQItrI-fJc-rkyRs07n4ZiVqzjiPQYzEv6adSCovyCY");
try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response =
httpClient.execute(request)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
// return it as a String
String result = EntityUtils.toString(entity);
//convert response entity as json
ObjectMapper mapper = new ObjectMapper();
JsonNode message = mapper.readTree(result);
msg = message.get("message").asText();
}
else {
msg = "Response Entity is null";
}
} catch (ClientProtocolException e) {
msg = e.getMessage().toString();
} catch (IOException e) {
msg = e.getMessage().toString();
}
Notification notification = new Notification(msg,new Timestamp(new Date().getTime()));
notificationRepo.save(notification);
}
}
package com.swmrs.objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Component
public class SmtpMailSender {
@Autowired
private JavaMailSender javaMailSender;
public void send(String to, String subject, String body) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper;
helper = new MimeMessageHelper(message, true); // true indicates
// multipart message
helper.setSubject(subject);
helper.setTo(to);
helper.setText(body, true); // true indicates html
// continue using helper object for more functionality like adding attachments, etc.
javaMailSender.send(message);
}
}
\ No newline at end of file
package com.swmrs.repo;
import com.swmrs.model.Bill;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface BillRepo extends CrudRepository<Bill, Integer> {
Bill findById(int billId);
Iterable<Bill> findAllByUserId( String userId);
@Query(value = "SELECT SUM(`usage`) from `bill`", nativeQuery = true)
Long findTotalUsage();
@Query(value = "SELECT SUM(`usage`) from `bill` where user_id=?1", nativeQuery = true)
Long findTotalUsageByUserId(String userId);
@Query(value = "SELECT COUNT(`id`) FROM `bill` WHERE user_id =?1", nativeQuery = true)
Long findCountByUserId(String userId);
@Query(value = "SELECT SUM(`total_bill_amount`) from `bill`", nativeQuery = true)
Double findTotalBilledAmount();
@Query(value = "SELECT SUM(`total_bill_amount`) from `bill` where user_id=?1", nativeQuery = true)
Double findTotalBilledAmountByUserId(String userId);
}
package com.swmrs.repo;
import com.swmrs.model.Consumer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Map;
public interface ConsumerRepo extends CrudRepository<Consumer, String> {
Consumer findByUserId(String userId);
Iterable<Consumer> findByDistrict(String district);
@Query(value = "SELECT `postal_code`, COUNT(*) AS `count` FROM `consumer`GROUP BY `postal_code`",nativeQuery = true)
List<Map<String, Long>> countPostalCodes();
@Query (value = "SELECT consumer.postal_code, SUM(bill.usage ) as `total_usage` FROM `consumer` JOIN `bill` WHERE" +
" consumer.user_id = bill.user_id GROUP BY consumer.postal_code", nativeQuery = true)
List<Map<String, Long>> totalUsagePostalCode();
@Query(value = "SELECT `connection_type`, COUNT(*) AS `count` FROM `consumer`GROUP BY `connection_type`",nativeQuery = true)
List<Map<String, Long>> countConnectionType();
@Query(value = "SELECT * FROM `consumer` WHERE `due_amount`<0",nativeQuery = true)
Iterable<Consumer> hasExcessBalance();
@Query(value = "SELECT * FROM `consumer` WHERE `due_amount`>0",nativeQuery = true)
Iterable<Consumer> hasDues();
}
package com.swmrs.repo;
import com.swmrs.model.Notification;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface NotificationRepo extends CrudRepository<Notification, Integer> {
Notification findById(int id);
@Query(value = "SELECT * FROM `notification` ORDER BY id DESC LIMIT 5", nativeQuery = true)
Iterable<Notification> latestNotification();
}
package com.swmrs.repo;
import com.swmrs.model.Payment;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface PaymentRepo extends CrudRepository<Payment, Integer> {
Payment findById(int paymentId);
Iterable<Payment> findAllByUserId( String userId);
@Query(value = "SELECT SUM(`payment_amount`) from `payment`", nativeQuery = true)
Double findTotalPayment();
@Query(value = "SELECT SUM(`payment_amount`) from `payment` where user_id=?1", nativeQuery = true)
Double findTotalPaymentByUserId(String userId);
@Query(value = "SELECT COUNT(`id`) from `payment` where user_id=?1", nativeQuery = true)
Long findCountByUserId(String userId);
}
package com.swmrs.repo;
import com.swmrs.model.Usage;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.sql.Timestamp;
public interface UsageRepo extends CrudRepository<Usage, Integer> {
Usage findById(int usageId);
Iterable<Usage> findAllByUserId( String userId);
@Query(value ="SELECT * FROM `usage` WHERE time >= ?1 && time<= ?2", nativeQuery = true)
Iterable<Usage> findUsageByInterval(Timestamp StartDate, Timestamp EndDate);
@Query(value ="SELECT * FROM `usage` WHERE time >= ?1 && time<= ?2 && user_id= ?3", nativeQuery = true)
Iterable<Usage> findUserUsageByInterval(Timestamp StartDate, Timestamp EndDate, String userId);
@Query(value = "SELECT * FROM `usage` where user_id=?1 ORDER BY id DESC LIMIT 1", nativeQuery = true)
Usage findLastUsageByUserId(String userId);
}
package com.swmrs.repo;
import com.swmrs.model.UserCredential;
import org.springframework.data.repository.CrudRepository;
public interface UserCredentialRepo extends CrudRepository<UserCredential, String> {
UserCredential findByUsername(String username);
}
server.port = 8083
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/swmrs?useUnicode=true&useJDBCCompliantTimezoneShift=true& \
useLegacyDatetimeCode=false&serverTimezone=UTC
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.datasource.username=root
spring.datasource.password=
security.jwt.client-id=testClientId
security.jwt.client-secret=testSecret
security.jwt.grant-type=password
security.jwt.scope-read=read
security.jwt.scope-write=write
spring.mail.host = smtp.gmail.com
spring.mail.username = smartmeter97@gmail.com
spring.mail.password = smartmeter123
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
package com.swmrs;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SwmrsApplicationTests {
@Test
void contextLoads() {
}
}
swmrs-web @ eeaa5418
Subproject commit eeaa54184bcb221d553e23a233d6774803681d42
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