├── stocktrading ├── src │ ├── main │ │ ├── resources │ │ │ ├── admin.txt │ │ │ ├── .DS_Store │ │ │ ├── static │ │ │ │ ├── buy.png │ │ │ │ ├── hold.png │ │ │ │ ├── sell.png │ │ │ │ └── symbols.txt │ │ │ ├── application.properties │ │ │ └── templates │ │ │ │ ├── landing-page.html │ │ │ │ ├── account-statement.html │ │ │ │ ├── login-form.html │ │ │ │ ├── navbar.html │ │ │ │ ├── dashboard-transaction.html │ │ │ │ ├── admin-update.html │ │ │ │ ├── admin-verify.html │ │ │ │ ├── register-form.html │ │ │ │ ├── stock-forecast.html │ │ │ │ ├── stock-watchlist.html │ │ │ │ ├── user-dashboard.html │ │ │ │ ├── stock-analysis.html │ │ │ │ ├── profile-update.html │ │ │ │ ├── user-account.html │ │ │ │ └── user-transaction.html │ │ ├── .DS_Store │ │ └── java │ │ │ ├── .DS_Store │ │ │ └── com │ │ │ ├── .DS_Store │ │ │ └── neu │ │ │ ├── .DS_Store │ │ │ └── edu │ │ │ ├── .DS_Store │ │ │ └── stocktrading │ │ │ ├── DemoApplication.java │ │ │ ├── config │ │ │ └── AppConfig.java │ │ │ ├── service │ │ │ ├── WatchListService.java │ │ │ ├── UserAccountService.java │ │ │ ├── AdminService.java │ │ │ ├── UserAuthService.java │ │ │ ├── UserDashboardService.java │ │ │ ├── ForecastService.java │ │ │ ├── StockTradeService.java │ │ │ ├── StockAnalysisService.java │ │ │ └── HomePageService.java │ │ │ ├── model │ │ │ ├── LoginForm.java │ │ │ ├── WatchList.java │ │ │ ├── Transaction.java │ │ │ ├── UserBankDetails.java │ │ │ ├── Trade.java │ │ │ ├── Stock.java │ │ │ └── User.java │ │ │ ├── util │ │ │ ├── HeaderInterceptorUtil.java │ │ │ ├── SessionManagementUtil.java │ │ │ ├── FileReaderUtil.java │ │ │ └── GeneratePdfUtil.java │ │ │ ├── dao │ │ │ ├── UserAuthDAO.java │ │ │ ├── AdminDAO.java │ │ │ ├── UserAccountDAO.java │ │ │ ├── WatchListDAO.java │ │ │ ├── StockAnalysisDAO.java │ │ │ ├── ForecastDAO.java │ │ │ └── HomePageDAO.java │ │ │ ├── validator │ │ │ └── RegisterUserValidator.java │ │ │ └── controller │ │ │ ├── StockAnalysisController.java │ │ │ ├── WatchListController.java │ │ │ ├── ForecastController.java │ │ │ ├── AdminController.java │ │ │ ├── UserDashboardController.java │ │ │ ├── HomePageController.java │ │ │ ├── UserAccountController.java │ │ │ ├── UserAuthController.java │ │ │ └── StockTradeController.java │ ├── .DS_Store │ └── test │ │ └── java │ │ └── com │ │ └── neu │ │ └── edu │ │ └── stocktrading │ │ ├── DemoApplicationTests.java │ │ └── service │ │ └── BCryptTest.java ├── .DS_Store ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ ├── maven-wrapper.properties │ │ └── MavenWrapperDownloader.java ├── .gitignore ├── .project.xml ├── .classpath.xml ├── pom.xml └── mvnw.cmd ├── .DS_Store └── README.md /stocktrading/src/main/resources/admin.txt: -------------------------------------------------------------------------------- 1 | 6.9 -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/.DS_Store -------------------------------------------------------------------------------- /stocktrading/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/.DS_Store -------------------------------------------------------------------------------- /stocktrading/src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/.DS_Store -------------------------------------------------------------------------------- /stocktrading/src/main/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/.DS_Store -------------------------------------------------------------------------------- /stocktrading/src/main/java/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/java/.DS_Store -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/java/com/.DS_Store -------------------------------------------------------------------------------- /stocktrading/src/main/resources/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/resources/.DS_Store -------------------------------------------------------------------------------- /stocktrading/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/java/com/neu/.DS_Store -------------------------------------------------------------------------------- /stocktrading/src/main/resources/static/buy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/resources/static/buy.png -------------------------------------------------------------------------------- /stocktrading/src/main/resources/static/hold.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/resources/static/hold.png -------------------------------------------------------------------------------- /stocktrading/src/main/resources/static/sell.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/resources/static/sell.png -------------------------------------------------------------------------------- /stocktrading/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip 2 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitalisalvi/Stock-Trading-application/HEAD/stocktrading/src/main/java/com/neu/edu/.DS_Store -------------------------------------------------------------------------------- /stocktrading/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | /target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | /build/ 27 | 28 | ### VS Code ### 29 | .vscode/ 30 | -------------------------------------------------------------------------------- /stocktrading/src/test/java/com/neu/edu/stocktrading/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class DemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /stocktrading/src/test/java/com/neu/edu/stocktrading/service/BCryptTest.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | import org.mindrot.jbcrypt.BCrypt; 6 | 7 | public class BCryptTest { 8 | 9 | @Test 10 | public void generateEncryptedPasswordTest() 11 | { 12 | String actualEncryptedPass = BCrypt.hashpw("Pass@123", BCrypt.gensalt()); 13 | Assert.assertTrue(BCrypt.checkpw("Pass@123", actualEncryptedPass)); 14 | } 15 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.web.client.RestTemplate; 7 | 8 | @SpringBootApplication 9 | public class DemoApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(DemoApplication.class, args); 13 | } 14 | 15 | @Bean 16 | public RestTemplate restTemplate() { 17 | return new RestTemplate(); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /stocktrading/.project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | stocktrading 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.config; 2 | 3 | import com.neu.edu.stocktrading.util.HeaderInterceptorUtil; 4 | 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | @Configuration 10 | public class AppConfig implements WebMvcConfigurer 11 | { 12 | @Override 13 | public void addInterceptors(InterceptorRegistry registry) 14 | { 15 | registry.addInterceptor(new HeaderInterceptorUtil()); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/WatchListService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import java.util.Set; 4 | 5 | import com.neu.edu.stocktrading.dao.WatchListDAO; 6 | import com.neu.edu.stocktrading.model.Stock; 7 | import com.neu.edu.stocktrading.model.User; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Service; 11 | 12 | @Service 13 | public class WatchListService { 14 | @Autowired 15 | private WatchListDAO watchListDAO; 16 | 17 | public User getProfileAttributes(String email) { 18 | return this.watchListDAO.getProfileAttributes(email); 19 | } 20 | 21 | public boolean addStockToWatchList(User user, String stockSymbol) { 22 | return this.watchListDAO.addStockToWatchList(user, stockSymbol); 23 | } 24 | 25 | public Set retrieveWatchList(User user) 26 | { 27 | return this.watchListDAO.retrieveWatchList(user); 28 | } 29 | 30 | 31 | 32 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/UserAccountService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import com.neu.edu.stocktrading.dao.UserAccountDAO; 4 | import com.neu.edu.stocktrading.model.User; 5 | import com.neu.edu.stocktrading.model.UserBankDetails; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | public class UserAccountService 12 | { 13 | @Autowired 14 | private UserAccountDAO userAccountDAO; 15 | 16 | public User getProfileAttributes (String email) 17 | { 18 | return this.userAccountDAO.getProfileAttributes(email); 19 | } 20 | 21 | public User updateProfile (String email , String phoneNumber) 22 | { 23 | return this.userAccountDAO.updateProfileAttributes(email , phoneNumber); 24 | } 25 | 26 | public User updateBankDetails (User user, UserBankDetails userbank) 27 | { 28 | return this.userAccountDAO.updateBankDetails(user , userbank); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/model/LoginForm.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.model; 2 | 3 | import org.hibernate.validator.constraints.NotEmpty; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class LoginForm 8 | { 9 | public LoginForm(){ 10 | 11 | } 12 | @NotEmpty 13 | private String email ; 14 | 15 | @NotEmpty 16 | private String password; 17 | 18 | 19 | 20 | public String getEmail() { 21 | return this.email; 22 | } 23 | 24 | public void setEmail(String email) { 25 | this.email = email; 26 | } 27 | 28 | public String getPassword() { 29 | return this.password; 30 | } 31 | 32 | public void setPassword(String password) { 33 | this.password = password; 34 | } 35 | 36 | 37 | @Override 38 | public String toString() { 39 | return "{" + 40 | ", email='" + getEmail() + "'" + 41 | ", password='" + getPassword() + "'" + 42 | "}"; 43 | } 44 | 45 | 46 | 47 | 48 | 49 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/util/HeaderInterceptorUtil.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.util; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 9 | 10 | public class HeaderInterceptorUtil extends HandlerInterceptorAdapter 11 | { 12 | private static Logger log = LoggerFactory.getLogger(HeaderInterceptorUtil.class); 13 | 14 | @Override 15 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 16 | 17 | log.info("[" + request.getRequestURI() + "]" + "[" + request.getMethod() 18 | + "]" ); 19 | response.setHeader("Cache-Control","no-cache"); 20 | response.setHeader("Cache-Control","no-store"); 21 | response.setHeader("Pragma","no-cache"); 22 | response.setDateHeader ("Expires",0); 23 | 24 | return true; 25 | } 26 | 27 | 28 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | ## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) 2 | spring.datasource.url = jdbc:mysql://localhost:3306/webtools_db?useSSL=false&serverTimezone=UTC 3 | spring.datasource.username = root 4 | spring.datasource.password = P@ssw0rd 5 | 6 | 7 | ## Hibernate Properties 8 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 9 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect 10 | spring.jpa.properties.hibernate.globally_quoted_identifiers=true 11 | spring.jpa.show-sql=true 12 | spring.jpa.properties.hibernate.format_sql=true 13 | 14 | 15 | # Hibernate ddl auto (create, create-drop, validate, update) 16 | spring.jpa.hibernate.ddl-auto = update 17 | 18 | ## MULTIPART (MultipartProperties) 19 | # Enable multipart uploads 20 | spring.http.multipart.enabled=true 21 | # Threshold after which files are written to disk. 22 | spring.http.multipart.file-size-threshold=2KB 23 | # Max file size. 24 | spring.http.multipart.max-file-size=200MB 25 | # Max Request Size 26 | spring.http.multipart.max-request-size=215MB 27 | 28 | admin.email=stocktrader6250@gmail.com 29 | admin.password=Pass@123 -------------------------------------------------------------------------------- /stocktrading/src/main/resources/static/symbols.txt: -------------------------------------------------------------------------------- 1 | AMZN //logo.clearbit.com/spotify.com 2 | GOOG 3 | AAPL 4 | NFLX 5 | TSLA 6 | FB 7 | CSCO 8 | ORCL 9 | INTC 10 | QCOM 11 | EBAY 12 | DELL 13 | COST 14 | MSFT 15 | TWTR 16 | AABA 17 | SNAP 18 | AMD 19 | ATVI 20 | ZNGA 21 | WDC 22 | BKNG 23 | 24 | 25 | AMZN,GOOG,AAPL,GOOG,NFLX,TSLA,FB,CSCO,ORCL,INTC,QCOM,EBAY,DELL,COST,MSFT,TWTR,AABA,SNAP,AMD,ATVI,ZNGA,WDC,BKNG 26 | https://marketdata.websol.barchart.com/getQuote.json?apikey=b0ccbbb0dae9d39ce81f65718f0ecd10&symbols=AMZN,GOOG,AAPL,NFLX,TSLA,FB,CSCO,ORCL,INTC,QCOM,EBAY,DELL,COST,MSFT,TWTR,AABA,SNAP,AMD,ATVI,ZNGA,WDC,BKNG&fields=fiftyTwoWkHigh%2CfiftyTwoWkHighDate%2CfiftyTwoWkLow%2CfiftyTwoWkLowDate 27 | 28 | VZ,HPQ,SNE,W,BRK-A,BABA,JNJ,JPM,XOM,BAC,WMT,WFC,V,PG,BUD,T,UNH,HD,C 29 | https://marketdata.websol.barchart.com/getQuote.json?apikey=b0ccbbb0dae9d39ce81f65718f0ecd10&symbols=VZ,HPQ,SNE,W,BRK-A,BABA,JNJ,JPM,XOM,BAC,WMT,WFC,V,PG,BUD,T,UNH,HD,C&fields=fiftyTwoWkHigh%2CfiftyTwoWkHighDate%2CfiftyTwoWkLow%2CfiftyTwoWkLowDate 30 | 31 | FINAL: 32 | https://marketdata.websol.barchart.com/getQuote.json?apikey=b0ccbbb0dae9d39ce81f65718f0ecd10&symbols=AMZN,GOOG,AAPL,NFLX,TSLA,FB,CSCO,ORCL,INTC,QCOM,EBAY,DELL,COST,MSFT,TWTR,AABA,SNAP,AMD,ATVI,ZNGA,WDC,BKNG,VZ,HPQ,SNE,W,BRK-A,BABA,JNJ,JPM,XOM,BAC,WMT,WFC,V,PG,BUD,T,UNH,HD,C&fields=fiftyTwoWkHigh%2CfiftyTwoWkHighDate%2CfiftyTwoWkLow%2CfiftyTwoWkLowDate 33 | https://www.worldtradingdata.com/api/v1/forex?base=USD&sort=newest&api_token=uRqeU8C651htqmF8iI5N6VvSBEIpTiQ5xvvKkz9Slsm1D9jFvIGdG97m0RpF 34 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/util/SessionManagementUtil.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.util; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpSession; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | public class SessionManagementUtil 12 | { 13 | private static final Logger logger = LoggerFactory.getLogger(SessionManagementUtil.class); 14 | 15 | public Boolean doesSessionExist(HttpServletRequest request) 16 | { 17 | logger.debug("doesSessionExist::INSIDE"); 18 | if (request.getSession(false) != null) 19 | { 20 | logger.debug("Session exists"); 21 | 22 | if (request.getSession().getAttribute("user") != null) 23 | { 24 | logger.debug("User exists"); 25 | return true; 26 | } 27 | else 28 | { 29 | logger.debug("User does not exists"); 30 | return false; 31 | } 32 | } 33 | 34 | logger.debug("doesSessionExist::FALSE"); 35 | return false; 36 | } 37 | 38 | public HttpSession createNewSessionForUser(HttpServletRequest request, String email) 39 | { 40 | logger.debug("createNewSessionForUser::INSIDE::"+email); 41 | if (!doesSessionExist(request)) 42 | { 43 | HttpSession session = request.getSession(); 44 | session.setAttribute("user", email); 45 | return session; 46 | } 47 | else 48 | { 49 | logger.debug("createNewSessionForUser::Return current session::"); 50 | return request.getSession(); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/landing-page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | Stock Trading 24 | 25 | 26 | 27 | 28 | 29 |
30 |
31 |
32 |
33 |
34 |

Online Stock Trading

35 |

Create account, link bank account to profile

36 |

Add stocks to watch list

37 |

Buy and sell stocks

38 |
39 | 40 | 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Stock Trading Application
2 | ## Final Project - Web Development Tools and Methods ( INFO 6250 )
3 | 4 | ### Project Description 5 | Online Stock Trader lets you trade, invest, track and review stocks using a single account. 6 | Live streaming quotes of stocks and currencies allow you to keep up to date with the fast 7 | pace of trading world. It lets you trade across exchanges. Get personalized recommendation 8 | based on your spending habits and portfolio. Track stocks using customized watch-list 9 | 10 | ### Technologies Used 11 | #### Spring Boot 12 | 1. Spring Core – Dependency Injection and Inversion of Control 13 | 2. Web MVC architectural pattern 14 | 3. AJAX – service side scripting 15 | 4. Validation – Validator 16 | 5. Interceptor – Disabling caching using Http Headers and Logging 17 | 6. Password Hashing using j-BCrypt 18 | 7. JSON Binding 19 | 8. Rest Template 20 | 9. Apache Common Email 21 | 10. Pdf Generator 22 | 11. Java 8 Stream API 23 | 12. jUnit testing 24 | 13. Server – Embedded Tomcat Server 25 | 14. Maven Plugin and dependencies 26 | 15. Logging – slf4j 27 | 16. Session Management using Session Object 28 | 17. File Reader and Writer 29 | #### Hibernate 30 | 1. Entity Manager 31 | 2. Relationship Mapping 32 | 3. Hibernate Validator 33 | 4. Criteria Query 34 | #### Thyme-leaf 35 | 1. JQuery 36 | 2. JavaScript 37 | 3. Boot-Strap 38 | 4. CSS3 39 | 5. HTML5 40 | #### API 41 | 1. Bar-chart on Demand API: https://www.barchart.com/ondemand/api 42 | 2. World Trading Data: https://www.worldtradingdata.com/ 43 | 3. Investors Exchange (IEX): https://iextrading.com/ 44 | 45 | ### Run the application 46 | Go to stocktrader root folder 47 | Run the following command: 'mvn spring-boot:run' 48 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/util/FileReaderUtil.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.util; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.FileNotFoundException; 6 | import java.io.FileReader; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | 10 | public class FileReaderUtil { 11 | public static String readServiceChargeValue() { 12 | String expected_value = ""; 13 | String file = "src/main/resources/admin.txt"; 14 | 15 | BufferedReader reader = null; 16 | try { 17 | reader = new BufferedReader(new FileReader(file)); 18 | } catch (FileNotFoundException e) { 19 | e.printStackTrace(); 20 | reader = null; 21 | } 22 | 23 | if (reader != null) 24 | { 25 | try { 26 | expected_value = reader.readLine(); 27 | } catch (IOException e) 28 | { 29 | expected_value = "10"; 30 | e.printStackTrace(); 31 | } finally { 32 | try { 33 | reader.close(); 34 | } catch (IOException e) 35 | { 36 | expected_value = "10"; 37 | e.printStackTrace(); 38 | } 39 | } 40 | 41 | } 42 | return expected_value; 43 | } 44 | 45 | public static void writeServiceChargeValue (String val) 46 | { 47 | try (FileWriter writer = new FileWriter("src/main/resources/admin.txt"); 48 | BufferedWriter bw = new BufferedWriter(writer)) { 49 | 50 | bw.write(val); 51 | 52 | } catch (IOException e) { 53 | System.err.format("IOException: %s%n", e); 54 | } 55 | } 56 | 57 | 58 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/dao/UserAuthDAO.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.dao; 2 | 3 | import javax.persistence.EntityManager; 4 | import javax.persistence.NoResultException; 5 | import javax.persistence.NonUniqueResultException; 6 | import javax.persistence.PersistenceContext; 7 | import javax.persistence.Query; 8 | import javax.persistence.TypedQuery; 9 | import javax.transaction.Transactional; 10 | 11 | import com.neu.edu.stocktrading.model.User; 12 | 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.stereotype.Component; 16 | 17 | @Component 18 | public class UserAuthDAO 19 | { 20 | private static final Logger logger = LoggerFactory.getLogger(UserAuthDAO.class); 21 | 22 | @PersistenceContext 23 | private EntityManager entityManager; 24 | 25 | @Transactional 26 | public User saveUser(User user) 27 | { 28 | logger.info("Saving user object to database"); 29 | return this.entityManager.merge(user); 30 | } 31 | 32 | public int checkIfUserExists(String email) 33 | { 34 | logger.info("Checking if user exists"); 35 | int result = 0; 36 | try { 37 | Query query = this.entityManager.createQuery("SELECT COUNT(u) FROM User u WHERE u.email = ?1"); 38 | query.setParameter(1, email); 39 | query.setMaxResults(1); 40 | Long resultInLong = (Long) query.getSingleResult(); 41 | result = Math.toIntExact(resultInLong); 42 | } catch (Exception e) { 43 | logger.error(e.toString()); 44 | result = 0; 45 | } 46 | 47 | return result; 48 | } 49 | 50 | public User getProfileAttributes(String email) { 51 | logger.info("Getting user from email : " + email); 52 | TypedQuery query = this.entityManager.createQuery("SELECT u from User u where u.email = ?1", User.class); 53 | query.setParameter(1, email); 54 | query.setMaxResults(1); 55 | return query.getSingleResult(); 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/dao/AdminDAO.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.dao; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.PersistenceContext; 8 | import javax.persistence.TypedQuery; 9 | 10 | import javax.transaction.Transactional; 11 | 12 | import com.neu.edu.stocktrading.model.User; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.stereotype.Component; 17 | 18 | @Component 19 | public class AdminDAO 20 | { 21 | @PersistenceContext 22 | private EntityManager entityManager; 23 | 24 | private static final Logger logger = LoggerFactory.getLogger(AdminDAO.class); 25 | 26 | 27 | 28 | public List getUnverifiedUsers () 29 | { 30 | return this.getUsers(); 31 | 32 | } 33 | 34 | private void flushAndClear() { 35 | this.entityManager.flush(); 36 | this.entityManager.clear(); 37 | } 38 | 39 | public List getUsers() 40 | { 41 | List result = new ArrayList(); 42 | try { 43 | TypedQuery query = this.entityManager.createQuery("SELECT a from User a where a.verified = FALSE",User.class); 44 | result= query.getResultList(); 45 | } catch (Exception e) { 46 | } 47 | return result; 48 | } 49 | 50 | public User getProfileAttributes (String email) 51 | { 52 | logger.info("Getting user from email : " + email); 53 | TypedQuery query = this.entityManager.createQuery("SELECT u from User u where u.email = ?1", User.class); 54 | query.setParameter(1, email); 55 | return query.getSingleResult(); 56 | } 57 | 58 | @Transactional 59 | public void verifyUsers (String email) 60 | { 61 | User u = getProfileAttributes(email); 62 | u.setVerified(true); 63 | flushAndClear(); 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/validator/RegisterUserValidator.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.validator; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | import com.neu.edu.stocktrading.model.User; 7 | 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.validation.Errors; 10 | import org.springframework.validation.ValidationUtils; 11 | import org.springframework.validation.Validator; 12 | 13 | @Component 14 | public class RegisterUserValidator implements Validator { 15 | 16 | @Override 17 | public boolean supports(Class clazz) 18 | { 19 | return User.class.isAssignableFrom(clazz); 20 | } 21 | 22 | @Override 23 | public void validate(Object target, Errors errors) 24 | { 25 | User login = (User) (target); 26 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email.required", "Email is required."); 27 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.password.required", "Password is required."); 28 | 29 | if (errors.hasErrors()) 30 | { 31 | return; 32 | } 33 | 34 | boolean verifyPass = this.verifyPassword(login.getPassword()); 35 | if (!verifyPass) 36 | { 37 | errors.rejectValue("password", "error.password.required", "Password should minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character"); 38 | } 39 | 40 | } 41 | 42 | public boolean verifyPassword(String password) 43 | { 44 | boolean isPassword = false; 45 | 46 | //Checks if password contains minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character 47 | Pattern passwordPattern = Pattern.compile("^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\\d]){1,})(?=(.*[\\W_]){1,})(?!.*\\s).{8,}$"); 48 | 49 | Matcher m = passwordPattern.matcher(password); 50 | isPassword = m.find(); 51 | 52 | return isPassword; 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /stocktrading/.classpath.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/dao/UserAccountDAO.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.dao; 2 | 3 | import javax.persistence.EntityManager; 4 | import javax.persistence.PersistenceContext; 5 | import javax.persistence.TypedQuery; 6 | import javax.transaction.Transactional; 7 | 8 | import com.neu.edu.stocktrading.model.User; 9 | import com.neu.edu.stocktrading.model.UserBankDetails; 10 | 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.stereotype.Component; 14 | 15 | @Component 16 | public class UserAccountDAO { 17 | 18 | @PersistenceContext 19 | private EntityManager entityManager; 20 | 21 | private static final Logger logger = LoggerFactory.getLogger(UserAccountDAO.class); 22 | 23 | public User getProfileAttributes(String email) { 24 | logger.info("Getting user from email : " + email); 25 | TypedQuery query = this.entityManager.createQuery("SELECT u from User u where u.email = ?1", User.class); 26 | query.setParameter(1, email); 27 | return query.getSingleResult(); 28 | } 29 | 30 | @Transactional 31 | public User updateProfileAttributes(String email , String phoneNumber) { 32 | logger.info("Updating user using new user object::"+phoneNumber); 33 | User getUserFromEmail = getProfileAttributes(email); 34 | logger.info("updated id::"+getUserFromEmail.getId()); 35 | getUserFromEmail = this.entityManager.find(User.class, getUserFromEmail.getId()); 36 | 37 | getUserFromEmail.setPhoneNumber(phoneNumber); 38 | 39 | flushAndClear(); 40 | return getUserFromEmail; 41 | 42 | } 43 | 44 | @Transactional 45 | public User updateBankDetails(User user, UserBankDetails userBank) 46 | { 47 | logger.info("updateBankDetails::"+userBank.getAccountNumber()); 48 | userBank = this.saveUserBank(userBank); 49 | user.setUserBankDetails(userBank); 50 | flushAndClear(); 51 | return user; 52 | 53 | } 54 | 55 | @Transactional 56 | public UserBankDetails saveUserBank(UserBankDetails userBank) 57 | { 58 | logger.info("Saving userbank object to database"); 59 | return this.entityManager.merge(userBank); 60 | } 61 | 62 | private void flushAndClear() { 63 | this.entityManager.flush(); 64 | this.entityManager.clear(); 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/model/WatchList.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.model; 2 | 3 | import java.util.Map; 4 | 5 | import javax.persistence.CollectionTable; 6 | import javax.persistence.Column; 7 | import javax.persistence.ElementCollection; 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.GeneratedValue; 11 | import javax.persistence.GenerationType; 12 | import javax.persistence.Id; 13 | import javax.persistence.MapKeyColumn; 14 | import javax.persistence.OneToOne; 15 | import javax.persistence.PrimaryKeyJoinColumn; 16 | import javax.persistence.Table; 17 | 18 | @Entity 19 | @Table(name = "watchlist") 20 | public class WatchList { 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private long id; 24 | 25 | @ElementCollection (fetch = FetchType.EAGER) 26 | @MapKeyColumn(name = "stock_id") 27 | @Column(name = "amount") 28 | @CollectionTable(name = "trade_stock") 29 | private Map stockToAmount ; 30 | 31 | @OneToOne(fetch = FetchType.EAGER) 32 | @PrimaryKeyJoinColumn 33 | private User user; 34 | 35 | @Column 36 | private String stocks; 37 | 38 | public long getId() { 39 | return this.id; 40 | } 41 | 42 | public void setId(long id) { 43 | this.id = id; 44 | } 45 | 46 | public User getUser() { 47 | return this.user; 48 | } 49 | 50 | public void setUser(User user) { 51 | this.user = user; 52 | } 53 | 54 | /** 55 | * @return the stocks 56 | */ 57 | public String getStocks() { 58 | return stocks; 59 | } 60 | 61 | /** 62 | * @param stocks the stocks to set 63 | */ 64 | public void setStocks(String stocks) { 65 | this.stocks = stocks; 66 | } 67 | 68 | /** 69 | * @return the stockToAmount 70 | */ 71 | public Map getStockToAmount() { 72 | return stockToAmount; 73 | } 74 | 75 | /** 76 | * @param stockToAmount the stockToAmount to set 77 | */ 78 | public void setStockToAmount(Map stockToAmount) { 79 | this.stockToAmount = stockToAmount; 80 | } 81 | 82 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/AdminService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import java.util.List; 4 | 5 | import com.neu.edu.stocktrading.dao.AdminDAO; 6 | import com.neu.edu.stocktrading.model.User; 7 | import com.neu.edu.stocktrading.util.FileReaderUtil; 8 | 9 | import org.apache.commons.mail.DefaultAuthenticator; 10 | import org.apache.commons.mail.Email; 11 | import org.apache.commons.mail.EmailException; 12 | import org.apache.commons.mail.SimpleEmail; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.stereotype.Service; 17 | 18 | @Service 19 | public class AdminService 20 | { 21 | @Autowired 22 | private AdminDAO adminDAO; 23 | 24 | private static final Logger logger = LoggerFactory.getLogger(AdminDAO.class); 25 | 26 | public void updateServiceCharge (String val) 27 | { 28 | FileReaderUtil.writeServiceChargeValue(val); 29 | } 30 | 31 | public List getUnverifiedUsers () 32 | { 33 | return this.adminDAO.getUnverifiedUsers(); 34 | } 35 | 36 | public boolean sendEmail (String[] emails) 37 | { 38 | for (String em : emails) 39 | { 40 | try { 41 | sendEmail(em); 42 | this.adminDAO.verifyUsers(em); 43 | } catch (Exception e) 44 | { 45 | logger.error(e.toString()); 46 | return false; 47 | } 48 | } 49 | 50 | for (String em : emails) 51 | { 52 | User u = this.adminDAO.getProfileAttributes(em); 53 | logger.info("verification status::"+u.isVerified()); 54 | 55 | } 56 | return true; 57 | 58 | 59 | } 60 | 61 | private void sendEmail (String emailId) throws EmailException 62 | { 63 | Email email =new SimpleEmail(); 64 | email.setHostName("smtp.googlemail.com"); 65 | // email.setSmtpPort(465); 66 | email.setSmtpPort(587); 67 | 68 | email.setAuthenticator(new DefaultAuthenticator("stocktrader6250@gmail.com", "Pass@123")); 69 | email.setSSLOnConnect(true); 70 | email.setFrom("stocktrader6250@gmail.com"); 71 | email.setSubject("Thank you for signing up on Stock Trading "); 72 | email.setMsg("This email is being sent you to notify that your account has now been verified"); 73 | email.addTo(emailId); 74 | email.send(); 75 | } 76 | 77 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/model/Transaction.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.model; 2 | 3 | import java.util.Date; 4 | import java.util.Set; 5 | 6 | import javax.persistence.CascadeType; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.GeneratedValue; 11 | import javax.persistence.GenerationType; 12 | import javax.persistence.Id; 13 | import javax.persistence.JoinColumn; 14 | import javax.persistence.ManyToOne; 15 | import javax.persistence.OneToMany; 16 | import javax.persistence.Table; 17 | import javax.persistence.Temporal; 18 | import javax.persistence.TemporalType; 19 | 20 | @Entity 21 | @Table(name = "transaction") 22 | public class Transaction 23 | { 24 | public Transaction() 25 | { 26 | 27 | } 28 | 29 | @Id 30 | @GeneratedValue (strategy = GenerationType.IDENTITY) 31 | private long id; 32 | 33 | @Column 34 | @Temporal(TemporalType.DATE) 35 | private Date timestampdate; 36 | 37 | @Column 38 | private double totalPrice; 39 | 40 | @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER, mappedBy = "transaction") 41 | private Set allTrades; 42 | 43 | @ManyToOne (cascade = CascadeType.ALL) 44 | @JoinColumn(name="user_id", nullable=false) 45 | private User user; 46 | 47 | 48 | public long getId() { 49 | return this.id; 50 | } 51 | 52 | public void setId(long id) { 53 | this.id = id; 54 | } 55 | 56 | public Date getTimestampdate() { 57 | return this.timestampdate; 58 | } 59 | 60 | public void setTimestampdate(Date timestampdate) { 61 | this.timestampdate = timestampdate; 62 | } 63 | 64 | public double getTotalPrice() { 65 | return this.totalPrice; 66 | } 67 | 68 | public void setTotalPrice(double totalPrice) { 69 | this.totalPrice = totalPrice; 70 | } 71 | 72 | public Set getAllTrades() { 73 | return this.allTrades; 74 | } 75 | 76 | public void setAllTrades(Set allTrades) { 77 | this.allTrades = allTrades; 78 | } 79 | 80 | public User getUser() { 81 | return this.user; 82 | } 83 | 84 | public void setUser(User user) { 85 | this.user = user; 86 | } 87 | 88 | @Override 89 | public String toString() { 90 | return "{" + 91 | " id='" + getId() + "'" + 92 | ", timestampdate='" + getTimestampdate() + "'" + 93 | ", totalPrice='" + getTotalPrice() + "'" + 94 | "}"; 95 | } 96 | 97 | 98 | 99 | 100 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/StockAnalysisController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | import com.neu.edu.stocktrading.model.Stock; 10 | import com.neu.edu.stocktrading.model.User; 11 | import com.neu.edu.stocktrading.service.StockAnalysisService; 12 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.web.bind.annotation.GetMapping; 19 | import org.springframework.web.servlet.ModelAndView; 20 | 21 | @Controller 22 | public class StockAnalysisController 23 | { 24 | @Autowired 25 | private StockAnalysisService stockAnalysisService; 26 | 27 | @Autowired 28 | private SessionManagementUtil sessionMgmtUtils; 29 | 30 | private static final Logger logger = LoggerFactory.getLogger(StockAnalysisController.class); 31 | 32 | @GetMapping(value = "/analysis.htm" ) 33 | public ModelAndView buildUserPortfolio (HttpServletRequest request ) 34 | { 35 | logger.info("buildUserPortfolio::"); 36 | 37 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 38 | { 39 | logger.info("Please login to access this page"); 40 | ModelAndView mv = new ModelAndView("login-form"); 41 | mv.addObject("user", new User()); 42 | mv.addObject("errorMessage", "Please login to access this page"); 43 | return mv; 44 | 45 | } 46 | 47 | String email = (String) request.getSession().getAttribute("user"); 48 | User user = this.stockAnalysisService.getProfileAttributes(email); 49 | 50 | Map> stockList = this.stockAnalysisService.retrieveSellList(user); 51 | List sellStocks = (List) stockList.get("Sell"); 52 | List sellAmount = (List) stockList.get("Amount"); 53 | 54 | List potentialBuyList = this.stockAnalysisService.getPotentialBuyFromWatchlist(user, sellStocks); 55 | 56 | Map> results = new HashMap>(); 57 | 58 | if (sellStocks.size()!=0) { 59 | results =this.stockAnalysisService.buildPortfolio(potentialBuyList, sellStocks, sellAmount); 60 | } 61 | 62 | ModelAndView mv = new ModelAndView(); 63 | mv.addObject("analysisMap", results); 64 | mv.setViewName("stock-analysis"); 65 | return mv; 66 | } 67 | 68 | 69 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/UserAuthService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import java.io.IOException; 4 | 5 | 6 | import com.neu.edu.stocktrading.dao.UserAuthDAO; 7 | import com.neu.edu.stocktrading.model.LoginForm; 8 | import com.neu.edu.stocktrading.model.User; 9 | 10 | import org.mindrot.jbcrypt.BCrypt; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.beans.factory.annotation.Value; 15 | import org.springframework.stereotype.Service; 16 | 17 | @Service 18 | public class UserAuthService { 19 | private static final Logger logger = LoggerFactory.getLogger(UserAuthService.class); 20 | 21 | @Autowired 22 | private UserAuthDAO userAuthDAO; 23 | 24 | @Value("${admin.email}") 25 | private String adminEmail; 26 | 27 | @Value("${admin.password}") 28 | private String adminPassword; 29 | 30 | public boolean registerUser(User user) throws IllegalStateException, IOException 31 | { 32 | user.setPassword(BCrypt.hashpw( user.getPassword(), BCrypt.gensalt())); 33 | this.userAuthDAO.saveUser(user); 34 | return true; 35 | } 36 | 37 | public boolean checkIfUserRegistered (User user) 38 | { 39 | logger.info("Checking if user exists ::" + user.getEmail()); 40 | int result = this.userAuthDAO.checkIfUserExists(user.getEmail()); 41 | if (result >0) { 42 | return true; 43 | } 44 | else 45 | return false; 46 | 47 | } 48 | 49 | public Boolean authenticate(LoginForm u) 50 | { 51 | logger.info("Checking if user exists on the basis of email::" + u.getEmail()); 52 | 53 | User user = null; 54 | try { 55 | user = this.userAuthDAO.getProfileAttributes(u.getEmail()); 56 | } catch (Exception e) { 57 | logger.error(e.toString()); 58 | user = null; 59 | } 60 | 61 | if (user == null) { 62 | return false; 63 | } else { 64 | Boolean pwdCheck = false; 65 | 66 | if (BCrypt.checkpw(u.getPassword(), user.getPassword())) { 67 | pwdCheck = true; 68 | } 69 | return pwdCheck; 70 | 71 | } 72 | 73 | } 74 | 75 | public boolean isAdmin (LoginForm loginForm) 76 | { 77 | if (loginForm.getEmail().equals(adminEmail)) 78 | { 79 | if (loginForm.getPassword().equals(adminPassword)) 80 | { 81 | return true; 82 | } 83 | else 84 | return false; 85 | } 86 | else 87 | return false; 88 | 89 | } 90 | 91 | public boolean isUserVerified (LoginForm loginForm) 92 | { 93 | User user = this.userAuthDAO.getProfileAttributes(loginForm.getEmail()); 94 | if ( user.isVerified()) 95 | { 96 | return true; 97 | } 98 | else 99 | { 100 | return false; 101 | } 102 | 103 | } 104 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/model/UserBankDetails.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.model; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.FetchType; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.OneToOne; 10 | import javax.persistence.PrimaryKeyJoinColumn; 11 | import javax.persistence.Table; 12 | 13 | @Entity 14 | @Table(name = "userbank") 15 | public class UserBankDetails 16 | { 17 | @Id 18 | @GeneratedValue (strategy = GenerationType.IDENTITY) 19 | private long id; 20 | 21 | @Column 22 | private long accountNumber; 23 | 24 | @Column 25 | private String accountType; 26 | 27 | @Column 28 | private String bankName; 29 | 30 | @OneToOne(fetch = FetchType.EAGER) 31 | @PrimaryKeyJoinColumn 32 | private User user; 33 | 34 | @Column 35 | private double totalAmountSpent = 0.0; 36 | 37 | 38 | public long getId() { 39 | return this.id; 40 | } 41 | 42 | public void setId(long id) { 43 | this.id = id; 44 | } 45 | 46 | public long getAccountNumber() { 47 | return this.accountNumber; 48 | } 49 | 50 | public void setAccountNumber(long accountNumber) { 51 | this.accountNumber = accountNumber; 52 | } 53 | 54 | public String getAccountType() { 55 | return this.accountType; 56 | } 57 | 58 | public void setAccountType(String accountType) { 59 | this.accountType = accountType; 60 | } 61 | 62 | public String getBankName() { 63 | return this.bankName; 64 | } 65 | 66 | public void setBankName(String bankName) { 67 | this.bankName = bankName; 68 | } 69 | 70 | public User getUser() { 71 | return this.user; 72 | } 73 | 74 | public void setUser(User user) { 75 | this.user = user; 76 | } 77 | 78 | public double getTotalAmountSpent() { 79 | return this.totalAmountSpent; 80 | } 81 | 82 | public void setTotalAmountSpent(double totalAmountSpent) { 83 | this.totalAmountSpent = totalAmountSpent; 84 | } 85 | 86 | @Override 87 | public String toString() { 88 | return "{" + 89 | " id='" + getId() + "'" + 90 | ", accountNumber='" + getAccountNumber() + "'" + 91 | ", accountType='" + getAccountType() + "'" + 92 | ", bankName='" + getBankName() + "'" + 93 | // ", user='" + getUser() + "'" + 94 | ", totalAmountSpent='" + getTotalAmountSpent() + "'" + 95 | "}"; 96 | } 97 | 98 | 99 | 100 | 101 | 102 | 103 | } 104 | -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/account-statement.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | Account Statement 24 | 25 | 26 | 27 |
28 |
29 |
30 |
31 |
32 |
33 |

My Account Statement Summary

34 |
35 | 36 |
37 |
38 | No transactions made yet ! 39 |
40 |
41 |
42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 |
IdDateAmount
61 | Download Account Statement 62 |
63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 |
71 |
72 | 73 | 74 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/UserDashboardService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import java.util.HashSet; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Set; 7 | import java.util.regex.Pattern; 8 | 9 | import com.neu.edu.stocktrading.dao.UserDashboardDAO; 10 | import com.neu.edu.stocktrading.model.Stock; 11 | import com.neu.edu.stocktrading.model.Trade; 12 | import com.neu.edu.stocktrading.model.Transaction; 13 | import com.neu.edu.stocktrading.model.User; 14 | 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.stereotype.Service; 19 | 20 | @Service 21 | public class UserDashboardService 22 | { 23 | @Autowired 24 | private UserDashboardDAO userDashboardDAO; 25 | 26 | private static final Logger logger = LoggerFactory.getLogger(UserDashboardService.class); 27 | 28 | public User getProfileAttributes(String email) { 29 | return this.userDashboardDAO.getProfileAttributes(email); 30 | } 31 | 32 | public Map> retrieveSellList ( User user) 33 | { 34 | return this.userDashboardDAO.retrieveSellList(user); 35 | } 36 | 37 | public Transaction completeTransaction (User user ,String[] selling ) 38 | { 39 | Transaction currenTransaction = this.userDashboardDAO.createTransaction(user); 40 | if (selling !=null) 41 | { 42 | Set sellTradesSet = new HashSet(); 43 | for (int i = 0; i < selling.length; i++) 44 | { 45 | String temp[] = selling[i].split(Pattern.quote("!")); 46 | Stock s = this.userDashboardDAO.checkIfStockExists(temp[0]); 47 | Trade sellTrade = this.userDashboardDAO.createSellTrade (user , s , temp[1] , currenTransaction); 48 | sellTradesSet.add(sellTrade); 49 | } 50 | this.userDashboardDAO.updateSellMap (user , sellTradesSet); 51 | this.userDashboardDAO.updateSellTransactions(sellTradesSet, user); 52 | 53 | } 54 | 55 | return currenTransaction; 56 | } 57 | 58 | public List getSellTradesUsingCurrentTransaction (User user , Transaction transaction) 59 | { 60 | Transaction h = this.userDashboardDAO.getLatestTransaction(user.getEmail()); 61 | logger.info("Fetching latest transaction from user::"+h.getId()); 62 | List sellTrades = this.userDashboardDAO.getTradesUsingTransaction (h.getId() , "Sell"); 63 | return sellTrades; 64 | 65 | } 66 | 67 | public double getTotalPrice (List trades) 68 | { 69 | double result =0.0; 70 | for (Trade tr: trades) 71 | { 72 | result = result + (tr.getIndividualPrice() * tr.getQuantity()); 73 | } 74 | return result; 75 | } 76 | 77 | 78 | 79 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/WatchListController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | 9 | import com.neu.edu.stocktrading.model.Stock; 10 | import com.neu.edu.stocktrading.model.User; 11 | import com.neu.edu.stocktrading.service.WatchListService; 12 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.http.MediaType; 18 | import org.springframework.http.ResponseEntity; 19 | import org.springframework.stereotype.Controller; 20 | import org.springframework.web.bind.annotation.GetMapping; 21 | import org.springframework.web.bind.annotation.PostMapping; 22 | import org.springframework.web.bind.annotation.RequestBody; 23 | import org.springframework.web.servlet.ModelAndView; 24 | 25 | @Controller 26 | public class WatchListController 27 | { 28 | private static final Logger logger = LoggerFactory.getLogger(WatchListController.class); 29 | 30 | 31 | @Autowired 32 | private WatchListService watchListService; 33 | 34 | @Autowired 35 | private SessionManagementUtil sessionMgmtUtils; 36 | 37 | @PostMapping(value = "/watchlist.htm" , consumes = MediaType.APPLICATION_JSON_VALUE) 38 | public ResponseEntity addToWatchList (HttpServletRequest request , @RequestBody HashMap stockSymbol) 39 | { 40 | logger.info("addToWatchList::"+stockSymbol.get("symbol")); 41 | String email = (String) request.getSession().getAttribute("user"); 42 | User user = this.watchListService.getProfileAttributes(email); 43 | 44 | 45 | boolean result = this.watchListService.addStockToWatchList (user , stockSymbol.get("symbol")); 46 | Map res = new HashMap(); 47 | res.put("result", "Success"); 48 | return ResponseEntity.ok(res); 49 | } 50 | 51 | @GetMapping(value = "/watchlist.htm" ) 52 | public ModelAndView retrieveWatchList (HttpServletRequest request ) 53 | { 54 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 55 | { 56 | logger.info("Please login to access this page"); 57 | ModelAndView mv = new ModelAndView("login-form"); 58 | mv.addObject("user", new User()); 59 | mv.addObject("errorMessage", "Please login to access this page"); 60 | return mv; 61 | 62 | } 63 | 64 | String email = (String) request.getSession().getAttribute("user"); 65 | User user = this.watchListService.getProfileAttributes(email); 66 | 67 | 68 | Set stockList= this.watchListService.retrieveWatchList (user); 69 | logger.info("Returned stocklist from watch::"+stockList.size()); 70 | 71 | ModelAndView mv = new ModelAndView("stock-watchlist"); 72 | mv.addObject("stockList", stockList); 73 | return mv; 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/login-form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Login Page 12 | 13 | 14 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 |
24 |
25 | 26 |

User Login

27 | 28 |
29 |
31 | 32 |
33 | 34 |
35 | 36 | 37 | 38 | 40 | 41 |
42 | 43 |
44 | 45 | 46 | 47 | 49 | 50 |
51 | 52 | 53 | 54 | 55 |
56 |
57 | 58 |
59 |
60 | 61 | 62 | 63 | 64 | 65 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/util/GeneratePdfUtil.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.util; 2 | 3 | import java.util.List; 4 | import com.itextpdf.text.Document; 5 | import com.itextpdf.text.DocumentException; 6 | import com.itextpdf.text.Element; 7 | import com.itextpdf.text.Font; 8 | import com.itextpdf.text.FontFactory; 9 | import com.itextpdf.text.Phrase; 10 | import com.itextpdf.text.pdf.PdfPCell; 11 | import com.itextpdf.text.pdf.PdfPTable; 12 | import com.itextpdf.text.pdf.PdfWriter; 13 | import java.io.ByteArrayInputStream; 14 | import java.io.ByteArrayOutputStream; 15 | 16 | 17 | import com.neu.edu.stocktrading.model.Transaction; 18 | 19 | public class GeneratePdfUtil { 20 | 21 | public static ByteArrayInputStream transactionReport(List transactionList) 22 | { 23 | 24 | Document document = new Document(); 25 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 26 | 27 | try 28 | { 29 | PdfPTable table = new PdfPTable(3); 30 | table.setWidthPercentage(60); 31 | table.setWidths(new int[]{1, 3, 3}); 32 | 33 | Font headFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD); 34 | 35 | PdfPCell hcell; 36 | hcell = new PdfPCell(new Phrase("Id", headFont)); 37 | hcell.setHorizontalAlignment(Element.ALIGN_CENTER); 38 | table.addCell(hcell); 39 | 40 | hcell = new PdfPCell(new Phrase("Date", headFont)); 41 | hcell.setHorizontalAlignment(Element.ALIGN_CENTER); 42 | table.addCell(hcell); 43 | 44 | hcell = new PdfPCell(new Phrase("Amount", headFont)); 45 | hcell.setHorizontalAlignment(Element.ALIGN_CENTER); 46 | table.addCell(hcell); 47 | 48 | for (Transaction t : transactionList) 49 | { 50 | 51 | PdfPCell cell; 52 | 53 | cell = new PdfPCell(new Phrase( Integer.toString(new java.util.Random().nextInt(10000)) )); 54 | cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 55 | cell.setHorizontalAlignment(Element.ALIGN_CENTER); 56 | table.addCell(cell); 57 | 58 | cell = new PdfPCell(new Phrase( t.getTimestampdate().toString() )); 59 | cell.setPaddingLeft(5); 60 | cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 61 | cell.setHorizontalAlignment(Element.ALIGN_LEFT); 62 | table.addCell(cell); 63 | 64 | cell = new PdfPCell(new Phrase(String.valueOf( Double.toString(t.getTotalPrice()) ))); 65 | cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 66 | cell.setHorizontalAlignment(Element.ALIGN_RIGHT); 67 | cell.setPaddingRight(5); 68 | table.addCell(cell); 69 | } 70 | 71 | PdfWriter.getInstance(document, out); 72 | document.open(); 73 | document.add(table); 74 | 75 | document.close(); 76 | 77 | } catch (DocumentException ex) 78 | { 79 | ex.printStackTrace(); 80 | } 81 | 82 | return new ByteArrayInputStream(out.toByteArray()); 83 | } 84 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/model/Trade.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.model; 2 | 3 | import javax.persistence.CascadeType; 4 | import javax.persistence.Column; 5 | import javax.persistence.Entity; 6 | import javax.persistence.FetchType; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.ManyToOne; 11 | import javax.persistence.OneToOne; 12 | import javax.persistence.Table; 13 | 14 | @Entity 15 | @Table(name = "trade") 16 | public class Trade 17 | { 18 | @Id 19 | @GeneratedValue (strategy = GenerationType.IDENTITY) 20 | private long id; 21 | 22 | @OneToOne(optional = true, fetch = FetchType.EAGER) 23 | private Stock stock; 24 | 25 | @Column 26 | private double individualPrice; 27 | 28 | @Column 29 | private String transId; 30 | 31 | @Column 32 | private int quantity; 33 | 34 | @Column 35 | private String buySell; 36 | 37 | 38 | @ManyToOne(fetch = FetchType.EAGER , cascade=CascadeType.ALL) 39 | private Transaction transaction; 40 | 41 | 42 | 43 | 44 | 45 | public int getQuantity() { 46 | return this.quantity; 47 | } 48 | 49 | public void setQuantity(int quantity) { 50 | this.quantity = quantity; 51 | } 52 | 53 | public String getBuySell() { 54 | return this.buySell; 55 | } 56 | 57 | public void setBuySell(String buySell) { 58 | this.buySell = buySell; 59 | } 60 | 61 | /** 62 | * @return the id 63 | */ 64 | public long getId() { 65 | return id; 66 | } 67 | 68 | /** 69 | * @param id the id to set 70 | */ 71 | public void setId(long id) { 72 | this.id = id; 73 | } 74 | 75 | /** 76 | * @return the stock 77 | */ 78 | public Stock getStock() { 79 | return stock; 80 | } 81 | 82 | /** 83 | * @param stock the stock to set 84 | */ 85 | public void setStock(Stock stock) { 86 | this.stock = stock; 87 | } 88 | 89 | /** 90 | * @return the transaction 91 | */ 92 | public Transaction getTransaction() { 93 | return transaction; 94 | } 95 | 96 | /** 97 | * @param transaction the transaction to set 98 | */ 99 | public void setTransaction(Transaction transaction) { 100 | this.transaction = transaction; 101 | } 102 | 103 | /** 104 | * @return the individualPrice 105 | */ 106 | public double getIndividualPrice() { 107 | return individualPrice; 108 | } 109 | 110 | /** 111 | * @param individualPrice the individualPrice to set 112 | */ 113 | public void setIndividualPrice(double individualPrice) { 114 | this.individualPrice = individualPrice; 115 | } 116 | 117 | /** 118 | * @return the transId 119 | */ 120 | public String getTransId() { 121 | return transId; 122 | } 123 | 124 | /** 125 | * @param transId the transId to set 126 | */ 127 | public void setTransId(String transId) { 128 | this.transId = transId; 129 | } 130 | 131 | 132 | 133 | 134 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/ForecastController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | import com.neu.edu.stocktrading.model.Stock; 11 | import com.neu.edu.stocktrading.model.User; 12 | import com.neu.edu.stocktrading.service.ForecastService; 13 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 14 | 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.http.MediaType; 19 | import org.springframework.http.ResponseEntity; 20 | import org.springframework.stereotype.Controller; 21 | import org.springframework.web.bind.annotation.GetMapping; 22 | import org.springframework.web.bind.annotation.PostMapping; 23 | import org.springframework.web.bind.annotation.RequestBody; 24 | import org.springframework.web.servlet.ModelAndView; 25 | 26 | @Controller 27 | public class ForecastController 28 | { 29 | private static final Logger logger = LoggerFactory.getLogger(ForecastController.class); 30 | 31 | @Autowired 32 | private ForecastService forecastService; 33 | 34 | @Autowired 35 | private SessionManagementUtil sessionMgmtUtils; 36 | 37 | @GetMapping(value = "/forecast.htm" ) 38 | public ModelAndView getRecommendations (HttpServletRequest request ) 39 | { 40 | logger.info("getRecommendations::"); 41 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 42 | { 43 | logger.info("Please login to access this page"); 44 | ModelAndView mv = new ModelAndView("login-form"); 45 | mv.addObject("user", new User()); 46 | mv.addObject("errorMessage", "Please login to access this page"); 47 | return mv; 48 | 49 | } 50 | 51 | String email = (String) request.getSession().getAttribute("user"); 52 | User user = this.forecastService.getProfileAttributes(email); 53 | 54 | Map> stockList = this.forecastService.retrieveSellList(user); 55 | List sellStocks = (List) stockList.get("Sell"); 56 | 57 | List recos = new ArrayList(); 58 | 59 | if (sellStocks.size()!=0) 60 | { 61 | recos =this.forecastService.getRemmendations(sellStocks); 62 | recos = this.forecastService.removeDuplicates(recos); 63 | } 64 | 65 | ModelAndView mv = new ModelAndView(); 66 | mv.addObject("stockList", recos); 67 | mv.setViewName("stock-forecast"); 68 | return mv; 69 | } 70 | 71 | @PostMapping(value = "/forecast.htm" , consumes = MediaType.APPLICATION_JSON_VALUE) 72 | public ResponseEntity addToWatchList (HttpServletRequest request , @RequestBody HashMap stockSymbol) 73 | { 74 | logger.info("addToWatchList::"+stockSymbol.get("symbol")); 75 | String email = (String) request.getSession().getAttribute("user"); 76 | User user = this.forecastService.getProfileAttributes(email); 77 | 78 | 79 | boolean result = this.forecastService.addStockToWatchList (user , stockSymbol.get("symbol")); 80 | Map res = new HashMap(); 81 | res.put("result", "Success"); 82 | return ResponseEntity.ok(res); 83 | } 84 | 85 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/ForecastService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import com.neu.edu.stocktrading.dao.ForecastDAO; 8 | import com.neu.edu.stocktrading.model.Stock; 9 | import com.neu.edu.stocktrading.model.User; 10 | 11 | import org.json.JSONArray; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.stereotype.Service; 16 | import org.springframework.web.client.RestTemplate; 17 | 18 | @Service 19 | public class ForecastService { 20 | private static final Logger logger = LoggerFactory.getLogger(ForecastDAO.class); 21 | 22 | @Autowired 23 | private ForecastDAO forecastDAO; 24 | 25 | @Autowired 26 | private RestTemplate restTemplate; 27 | 28 | 29 | public User getProfileAttributes (String email) 30 | { 31 | return this.forecastDAO.getProfileAttributes(email); 32 | } 33 | 34 | public List getRemmendations(List sellingList) { 35 | 36 | List stocks = new ArrayList(); 37 | 38 | List symList = new ArrayList(); 39 | 40 | for (Stock s : sellingList) 41 | { 42 | String symbol = s.getStockSymbol(); 43 | String uri = "https://api.iextrading.com/1.0/stock/" + symbol + "/peers"; 44 | String result = this.restTemplate.getForObject(uri, String.class); 45 | 46 | if (result !=null) 47 | { 48 | try { 49 | JSONArray json = new JSONArray(result); 50 | for (int i = 0; i < json.length(); i++) 51 | { 52 | symList.add(json.getString(i)); 53 | } 54 | 55 | } catch (Exception e) { 56 | logger.error(e.toString()); 57 | } 58 | } 59 | } 60 | 61 | logger.info("Done adding recommended stocks from api"); 62 | 63 | for (String sym : symList) 64 | { 65 | Stock temp = null; 66 | try { 67 | temp = this.forecastDAO.checkIfStockExists(sym); 68 | } catch (Exception e) 69 | { 70 | temp = null; 71 | } 72 | 73 | if (temp !=null) 74 | { 75 | stocks.add(temp); 76 | } 77 | 78 | } 79 | 80 | logger.info("Recommendation list::"+ stocks.size()); 81 | 82 | return stocks; 83 | 84 | } 85 | 86 | public Map> retrieveSellList ( User user) 87 | { 88 | return this.forecastDAO.retrieveSellList(user); 89 | } 90 | 91 | public boolean addStockToWatchList(User user, String stockSymbol) { 92 | return this.forecastDAO.addStockToWatchList(user, stockSymbol); 93 | } 94 | 95 | public ArrayList removeDuplicates(List list) 96 | { 97 | 98 | ArrayList newList = new ArrayList(); 99 | 100 | for (Stock element : list) { 101 | 102 | if (!newList.contains(element)) 103 | { 104 | newList.add(element); 105 | } 106 | } 107 | 108 | return newList; 109 | } 110 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/navbar.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 82 | 83 |
84 | 85 |
-------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/model/Stock.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.model; 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 | 10 | @Entity 11 | @Table(name = "stock") 12 | public class Stock 13 | { 14 | @Id 15 | @GeneratedValue (strategy = GenerationType.IDENTITY) 16 | private long id; 17 | 18 | @Column 19 | private String stockName; 20 | 21 | @Column 22 | private String stockSymbol; 23 | 24 | @Column 25 | private double currentPrice; 26 | 27 | @Column 28 | private String change; 29 | 30 | @Column 31 | private double buyingPrice; 32 | 33 | @Column 34 | private double sellingPrice; 35 | 36 | @Column 37 | private double high52; 38 | 39 | @Column 40 | private double low52; 41 | 42 | @Column 43 | private String marketType; 44 | 45 | 46 | public long getId() { 47 | return this.id; 48 | } 49 | 50 | public void setId(long id) { 51 | this.id = id; 52 | } 53 | 54 | public String getStockName() { 55 | return this.stockName; 56 | } 57 | 58 | public void setStockName(String stockName) { 59 | this.stockName = stockName; 60 | } 61 | 62 | public String getStockSymbol() { 63 | return this.stockSymbol; 64 | } 65 | 66 | public void setStockSymbol(String stockSymbol) { 67 | this.stockSymbol = stockSymbol; 68 | } 69 | 70 | public double getCurrentPrice() { 71 | return this.currentPrice; 72 | } 73 | 74 | public void setCurrentPrice(double currentPrice) { 75 | this.currentPrice = currentPrice; 76 | } 77 | 78 | public String getChange() { 79 | return this.change; 80 | } 81 | 82 | public void setChange(String change) { 83 | this.change = change; 84 | } 85 | 86 | 87 | 88 | public double getBuyingPrice() { 89 | return this.buyingPrice; 90 | } 91 | 92 | public void setBuyingPrice(double buyingPrice) { 93 | this.buyingPrice = buyingPrice; 94 | } 95 | 96 | public double getSellingPrice() { 97 | return this.sellingPrice; 98 | } 99 | 100 | public void setSellingPrice(double sellingPrice) { 101 | this.sellingPrice = sellingPrice; 102 | } 103 | 104 | public double getHigh52() { 105 | return this.high52; 106 | } 107 | 108 | public void setHigh52(double high52) { 109 | this.high52 = high52; 110 | } 111 | 112 | public double getLow52() { 113 | return this.low52; 114 | } 115 | 116 | public void setLow52(double low52) { 117 | this.low52 = low52; 118 | } 119 | 120 | public String getMarketType() { 121 | return this.marketType; 122 | } 123 | 124 | public void setMarketType(String marketType) { 125 | this.marketType = marketType; 126 | } 127 | 128 | @Override 129 | public String toString() { 130 | return "{" + 131 | " id='" + getId() + "'" + 132 | ", stockName='" + getStockName() + "'" + 133 | ", stockSymbol='" + getStockSymbol() + "'" + 134 | ", currentPrice='" + getCurrentPrice() + "'" + 135 | ", change='" + getChange() + "'" + 136 | ", buyingPrice='" + getBuyingPrice() + "'" + 137 | ", sellingPrice='" + getSellingPrice() + "'" + 138 | ", high52='" + getHigh52() + "'" + 139 | ", low52='" + getLow52() + "'" + 140 | ", marketType='" + getMarketType() + "'" + 141 | "}"; 142 | } 143 | 144 | 145 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/AdminController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | 8 | import com.neu.edu.stocktrading.model.User; 9 | import com.neu.edu.stocktrading.service.AdminService; 10 | import com.neu.edu.stocktrading.util.FileReaderUtil; 11 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 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.web.bind.annotation.GetMapping; 18 | import org.springframework.web.bind.annotation.ModelAttribute; 19 | import org.springframework.web.bind.annotation.PostMapping; 20 | import org.springframework.web.servlet.ModelAndView; 21 | 22 | 23 | @Controller 24 | public class AdminController 25 | { 26 | private static final Logger logger = LoggerFactory.getLogger(AdminController.class); 27 | 28 | @Autowired 29 | private AdminService adminService; 30 | 31 | @Autowired 32 | private SessionManagementUtil sessionMgmtUtils; 33 | 34 | 35 | @GetMapping (value = "/admin/modify.htm") 36 | public ModelAndView updateServiceCharge (HttpServletRequest request ) 37 | { 38 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 39 | { 40 | logger.info("Admin page"); 41 | ModelAndView mv = new ModelAndView("login-form"); 42 | mv.addObject("user", new User()); 43 | mv.addObject("errorMessage", "You are unauthorized to view this page"); 44 | return mv; 45 | } 46 | 47 | ModelAndView mv = new ModelAndView("admin-update"); 48 | mv.addObject("errorMessage", "Current Service Charge: " + FileReaderUtil.readServiceChargeValue()); 49 | return mv; 50 | } 51 | 52 | @PostMapping (value = "/admin/modify.htm") 53 | public ModelAndView updateServiceChargePost (HttpServletRequest request , @ModelAttribute("serviceCharge") String val) 54 | { 55 | this.adminService.updateServiceCharge(val); 56 | 57 | ModelAndView mv = new ModelAndView(); 58 | mv.addObject("errorMessage", "Service Charge successfully updated"); 59 | mv.setViewName("admin-update"); 60 | return mv; 61 | } 62 | 63 | @GetMapping(value="/admin/verify.htm") 64 | public ModelAndView verifyUsers(HttpServletRequest request) 65 | { 66 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 67 | { 68 | logger.info("Admin page"); 69 | ModelAndView mv = new ModelAndView("login-form"); 70 | mv.addObject("user", new User()); 71 | mv.addObject("errorMessage", "You are unauthorized to view this page"); 72 | return mv; 73 | } 74 | 75 | List userList = this.adminService.getUnverifiedUsers(); 76 | ModelAndView mv = new ModelAndView(); 77 | mv.addObject("userList", userList); 78 | mv.setViewName("admin-verify"); 79 | return mv; 80 | } 81 | 82 | @PostMapping(value="/admin/verify.htm") 83 | public ModelAndView sendEmail(HttpServletRequest request) 84 | { 85 | String[] emails = request.getParameterValues("checkedRows"); 86 | boolean result =this.adminService.sendEmail (emails); 87 | ModelAndView mv = new ModelAndView(); 88 | if (result) 89 | mv.addObject("successMessage", "Selected users successfully verified"); 90 | else 91 | mv.addObject("errorMessage", "Selected users could not be verified"); 92 | 93 | 94 | mv.setViewName("admin-verify"); 95 | mv.addObject("userList", new ArrayList()); 96 | return mv; 97 | } 98 | 99 | 100 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/UserDashboardController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Random; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | import com.neu.edu.stocktrading.model.Trade; 11 | import com.neu.edu.stocktrading.model.Transaction; 12 | import com.neu.edu.stocktrading.model.User; 13 | import com.neu.edu.stocktrading.service.UserDashboardService; 14 | import com.neu.edu.stocktrading.util.FileReaderUtil; 15 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 16 | 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.stereotype.Controller; 21 | import org.springframework.web.bind.annotation.GetMapping; 22 | import org.springframework.web.bind.annotation.PostMapping; 23 | import org.springframework.web.servlet.ModelAndView; 24 | 25 | @Controller 26 | public class UserDashboardController 27 | { 28 | private static final Logger logger = LoggerFactory.getLogger(UserDashboardController.class); 29 | 30 | @Autowired 31 | private UserDashboardService userDashboardService; 32 | 33 | @Autowired 34 | private SessionManagementUtil sessionMgmtUtils; 35 | 36 | @GetMapping(value = "/dashboard.htm" ) 37 | public ModelAndView retrieveWatchList (HttpServletRequest request ) 38 | { 39 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 40 | { 41 | logger.info("Please login to access this page"); 42 | ModelAndView mv = new ModelAndView("login-form"); 43 | mv.addObject("user", new User()); 44 | mv.addObject("errorMessage", "Please login to access this page"); 45 | return mv; 46 | 47 | } 48 | 49 | String email = (String) request.getSession().getAttribute("user"); 50 | User user = this.userDashboardService.getProfileAttributes(email); 51 | 52 | Map> stockList = this.userDashboardService.retrieveSellList(user); 53 | ModelAndView mv = new ModelAndView(); 54 | mv.addObject("stockList", stockList); 55 | mv.setViewName("user-dashboard"); 56 | return mv; 57 | } 58 | 59 | @PostMapping(value = "/dashboard/sell.htm" ) 60 | public ModelAndView sellShares (HttpServletRequest request ) 61 | { 62 | logger.info("sellShares::"); 63 | String email = (String) request.getSession().getAttribute("user"); 64 | User user = this.userDashboardService.getProfileAttributes(email); 65 | 66 | String[] selling = request.getParameterValues("checkedRows"); 67 | 68 | Map> stockList = (Map>) request.getSession() 69 | .getAttribute("stockList"); 70 | 71 | ModelAndView mv = new ModelAndView(); 72 | mv.setViewName("dashboard-transaction"); 73 | 74 | mv.addObject("transactionBuyId", new Random().nextInt(1000000)); 75 | mv.addObject("transactionSellId", new Random().nextInt(1000000)); 76 | 77 | Transaction t = this.userDashboardService.completeTransaction(user, selling); 78 | logger.info("showTradeTransaction::"+t.getId()); 79 | 80 | List currentSellTrades = new ArrayList(); 81 | currentSellTrades = this.userDashboardService.getSellTradesUsingCurrentTransaction (user , t); 82 | 83 | mv.addObject("tradeSellList", currentSellTrades); 84 | 85 | 86 | Double serviceCharge = Double.parseDouble( FileReaderUtil.readServiceChargeValue() ); 87 | Double sellTax = (serviceCharge/100 * this.userDashboardService.getTotalPrice(currentSellTrades)); 88 | mv.addObject("serviceSellTax", sellTax); 89 | 90 | mv.addObject("totalSellPrice", this.userDashboardService.getTotalPrice(currentSellTrades) + sellTax ); 91 | 92 | return mv; 93 | } 94 | 95 | 96 | 97 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/dao/WatchListDAO.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.dao; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | import javax.persistence.EntityManager; 7 | import javax.persistence.NoResultException; 8 | import javax.persistence.PersistenceContext; 9 | import javax.persistence.TypedQuery; 10 | import javax.transaction.Transactional; 11 | 12 | import com.neu.edu.stocktrading.model.Stock; 13 | import com.neu.edu.stocktrading.model.User; 14 | import com.neu.edu.stocktrading.model.WatchList; 15 | 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.springframework.stereotype.Component; 19 | 20 | @Component 21 | public class WatchListDAO 22 | { 23 | @PersistenceContext 24 | private EntityManager entityManager; 25 | 26 | private static final Logger logger = LoggerFactory.getLogger(WatchListDAO.class); 27 | 28 | public User getProfileAttributes(String email) { 29 | logger.info("Getting user from email : " + email); 30 | TypedQuery query = this.entityManager.createQuery("SELECT u from User u where u.email = ?1", User.class); 31 | query.setParameter(1, email); 32 | query.setMaxResults(1); 33 | return query.getSingleResult(); 34 | } 35 | 36 | @Transactional 37 | public boolean addStockToWatchList(User user, String stockSymbol) 38 | { 39 | logger.info("addStockToWatchList::"+stockSymbol); 40 | logger.info("addStockToWatchList::"+user.getFirstName()); 41 | Stock st = null; 42 | try { 43 | st=checkIfStockExists(stockSymbol); 44 | } catch (Exception e) { 45 | st=null; 46 | } 47 | 48 | if (st!=null) 49 | { 50 | WatchList wt = user.getWatchList(); 51 | 52 | if (wt ==null) 53 | { 54 | wt = new WatchList(); 55 | } 56 | logger.info("addStockToWatchList::"+wt.toString()); 57 | String hs = wt.getStocks(); 58 | if (hs ==null || hs.isEmpty()) 59 | { 60 | hs="" + st.getStockSymbol(); 61 | } 62 | else 63 | hs = hs + "|" + st.getStockSymbol(); 64 | 65 | wt.setStocks(hs); 66 | user.setWatchList(wt); 67 | logger.info("addStockToWatchList::"+user.getWatchList().toString()); 68 | flushAndClear(); 69 | } 70 | 71 | logger.info("addStockToWatchList::done updating"); 72 | return true; 73 | 74 | } 75 | 76 | public Stock checkIfStockExists(String symbol) throws NoResultException { 77 | logger.info("Getting stock data from database for user "); 78 | TypedQuery query = this.entityManager.createQuery("SELECT c from Stock c where c.stockSymbol = ?1", 79 | Stock.class); 80 | query.setParameter(1, symbol); 81 | query.setMaxResults(1); 82 | return query.getSingleResult(); 83 | } 84 | 85 | private void flushAndClear() { 86 | this.entityManager.flush(); 87 | this.entityManager.clear(); 88 | } 89 | 90 | public Set retrieveWatchList (User user) 91 | { 92 | logger.info("retrieveWatchList::"+user.getEmail()); 93 | Set stockList = new HashSet(); 94 | 95 | WatchList wt = user.getWatchList(); 96 | if (wt ==null) 97 | { 98 | return new HashSet(); 99 | } 100 | 101 | String stocks = wt.getStocks(); 102 | String[] pipe_split = stocks.split("\\|"); 103 | 104 | for (String st : pipe_split) 105 | { 106 | Stock s =null; 107 | try { 108 | s = checkIfStockExists(st); 109 | } catch (Exception e) { 110 | s=null; 111 | } 112 | 113 | if (s!=null) 114 | stockList.add(s); 115 | } 116 | logger.info("retrieveWatchList::size::"+stockList.size()); 117 | return stockList; 118 | 119 | } 120 | 121 | 122 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/dashboard-transaction.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | Transaction Summary 24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
32 |
33 |
34 |
35 |
36 |
Congratulations, your transaction was successfully completed !
37 |
38 | 39 |
40 |
41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 69 | 71 | 72 | 73 | 74 | 75 | 76 | 79 | 81 | 82 | 83 |
Transaction ID:
Stock NameQuantityPrice per stockPrice
67 | Service Charge 68 | 70 |
77 | Total 78 | 80 |
84 |
85 | 86 |

Thank you for your business!  87 |

88 | 89 | 90 | 91 |
92 |
93 | 94 | 95 | -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/admin-update.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | My Profile 12 | 13 | 14 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 |
24 | 25 | 26 |
27 | 57 |
58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 |
76 | 77 | 78 | 79 | 80 | 81 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/admin-verify.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | Verify Users 24 | 30 | 44 | 49 | 50 | 51 | 52 | 53 | 54 |
55 |
56 |
57 |
58 |
59 |
60 |

Verify Users

61 |
62 |
63 |
64 | 65 | 70 |
71 | 72 | 73 | 74 |
75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 |
VerifyEmailUser Name
92 |
93 | 94 |
95 | 96 | 97 |
98 | 99 | 100 | 101 | 102 | 103 |
104 |
105 | 106 | 107 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/dao/StockAnalysisDAO.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.dao; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import javax.persistence.EntityManager; 10 | import javax.persistence.NoResultException; 11 | import javax.persistence.PersistenceContext; 12 | import javax.persistence.TypedQuery; 13 | 14 | import com.neu.edu.stocktrading.model.Stock; 15 | import com.neu.edu.stocktrading.model.User; 16 | import com.neu.edu.stocktrading.model.WatchList; 17 | 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | import org.springframework.stereotype.Component; 21 | 22 | @Component 23 | public class StockAnalysisDAO { 24 | @PersistenceContext 25 | private EntityManager entityManager; 26 | 27 | private static final Logger logger = LoggerFactory.getLogger(StockAnalysisDAO.class); 28 | 29 | public User getProfileAttributes(String email) { 30 | logger.info("Getting user from email : " + email); 31 | TypedQuery query = this.entityManager.createQuery("SELECT u from User u where u.email = ?1", User.class); 32 | query.setParameter(1, email); 33 | return query.getSingleResult(); 34 | } 35 | 36 | public Map> retrieveSellList(User user) { 37 | 38 | List sellingList = new ArrayList(); 39 | List sellingListAmount = new ArrayList(); 40 | 41 | User u = getProfileAttributes(user.getEmail()); 42 | WatchList wt = u.getWatchList(); 43 | 44 | if (wt != null) { 45 | logger.info("watchlist id:::" + wt.getId()); 46 | 47 | Map map = wt.getStockToAmount(); 48 | logger.info("map::" + map); 49 | Iterator it = map.entrySet().iterator(); 50 | while (it.hasNext()) { 51 | Map.Entry pair = (Map.Entry) it.next(); 52 | if ((int) pair.getValue() > 0) { 53 | Integer stockKey = (Integer) pair.getKey(); 54 | Stock s = this.getStockFromId(Integer.toUnsignedLong((int) pair.getKey())); 55 | logger.info("unsold shares::" + s.getStockName()); 56 | sellingList.add(s); 57 | sellingListAmount.add((int) pair.getValue()); 58 | } 59 | } 60 | 61 | } 62 | 63 | Map> userStockList = new HashMap>(); 64 | userStockList.put("Sell", sellingList); 65 | userStockList.put("Amount", sellingListAmount); 66 | 67 | return userStockList; 68 | 69 | } 70 | 71 | public Stock getStockFromId(long id) throws NoResultException { 72 | logger.info("Getting stock data from database for ID "); 73 | TypedQuery query = this.entityManager.createQuery("SELECT c from Stock c where c.id = ?1", Stock.class); 74 | query.setParameter(1, id); 75 | query.setMaxResults(1); 76 | return query.getSingleResult(); 77 | } 78 | 79 | public List getWatchlistStocks(User user) 80 | { 81 | logger.info("getWatchlistStocks::" + user.getEmail()); 82 | WatchList wt = user.getWatchList(); 83 | 84 | List watchListStocks = new ArrayList(); 85 | 86 | if (wt != null) 87 | { 88 | logger.info("watchlist id:::" + wt.getId()); 89 | 90 | Map map = wt.getStockToAmount(); 91 | logger.info("watchlist map::" + map); 92 | Iterator it = map.entrySet().iterator(); 93 | while (it.hasNext()) 94 | { 95 | Map.Entry pair = (Map.Entry) it.next(); 96 | Integer stockKey = (Integer) pair.getKey(); 97 | Stock s = this.getStockFromId(Integer.toUnsignedLong((int) pair.getKey())); 98 | watchListStocks.add(s); 99 | } 100 | 101 | } 102 | logger.info("getWatchlistStocks::watchListStocks" + watchListStocks.size()); 103 | 104 | return watchListStocks; 105 | 106 | } 107 | 108 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/register-form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Registration Page 12 | 13 | 14 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 |
24 |
25 | 26 |

New User Registration

27 | 28 |
29 |
31 | 32 |
33 | 34 |
35 | 36 | 37 | 38 | 40 | 41 |
42 | 43 |
44 | 45 | 46 | 47 | 49 | 50 |
51 | 52 |
53 | 54 | 55 | 56 | 58 | 59 |
60 | 61 |
62 | 63 | 64 | 65 | 67 | 68 |
69 | 70 | 71 | 72 | 73 |
74 |
75 | 76 |
77 |
78 | 79 | 80 | 81 | 82 | 83 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /stocktrading/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.4.RELEASE 9 | 10 | 11 | com.neu.edu 12 | stocktrading 13 | 0.0.1-SNAPSHOT 14 | demo 15 | Web Tools final project 16 | 17 | 18 | 11 19 | 20 | 21 | 22 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | 32 | mysql 33 | mysql-connector-java 34 | runtime 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-test 39 | test 40 | 41 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-data-jpa 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-thymeleaf 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-devtools 57 | true 58 | 59 | 60 | 61 | org.projectlombok 62 | lombok 63 | 1.18.6 64 | provided 65 | 66 | 67 | 68 | mysql 69 | mysql-connector-java 70 | 71 | 72 | 73 | org.mindrot 74 | jbcrypt 75 | 0.4 76 | 77 | 78 | 79 | 80 | com.googlecode.json-simple 81 | json-simple 82 | 1.1 83 | 84 | 85 | 86 | 87 | org.apache.commons 88 | commons-email 89 | 1.5 90 | 91 | 92 | 93 | 94 | com.lowagie 95 | itext 96 | 97 | 4.2.2 98 | 99 | 100 | 101 | net.sf.json-lib 102 | json-lib 103 | 2.4 104 | jdk15 105 | 106 | 107 | 108 | 109 | org.json 110 | json 111 | 20180813 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | org.springframework.boot 123 | spring-boot-maven-plugin 124 | 125 | 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/StockTradeService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import java.util.HashSet; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Set; 7 | import java.util.regex.Pattern; 8 | 9 | 10 | import com.neu.edu.stocktrading.dao.StockTradeDAO; 11 | import com.neu.edu.stocktrading.model.Stock; 12 | import com.neu.edu.stocktrading.model.Trade; 13 | import com.neu.edu.stocktrading.model.Transaction; 14 | import com.neu.edu.stocktrading.model.User; 15 | 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.stereotype.Service; 20 | 21 | @Service 22 | public class StockTradeService 23 | { 24 | @Autowired 25 | private StockTradeDAO stockTradeDAO; 26 | 27 | private static final Logger logger = LoggerFactory.getLogger(StockTradeService.class); 28 | 29 | public User getProfileAttributes(String email) { 30 | return this.stockTradeDAO.getProfileAttributes(email); 31 | } 32 | 33 | public Map> retrieveBuyList ( User user, String[] stockSymbols) 34 | { 35 | return this.stockTradeDAO.retrieveBuyList(user, stockSymbols); 36 | } 37 | 38 | public Transaction completeTransaction (User user, String[] quantities , List stockBuying ,String[] selling ) 39 | { 40 | Transaction currenTransaction = this.stockTradeDAO.createTransaction(user); 41 | if (selling !=null) 42 | { 43 | Set sellTradesSet = new HashSet(); 44 | for (int i = 0; i < selling.length; i++) 45 | { 46 | String temp[] = selling[i].split(Pattern.quote("!")); 47 | Stock s = this.stockTradeDAO.checkIfStockExists(temp[0]); 48 | Trade sellTrade = this.stockTradeDAO.createSellTrade (user , s , temp[1] , currenTransaction); 49 | sellTradesSet.add(sellTrade); 50 | } 51 | this.stockTradeDAO.updateSellMap (user , sellTradesSet); 52 | this.stockTradeDAO.updateSellTransactions(sellTradesSet, user); 53 | 54 | } 55 | 56 | 57 | Set buyTradesSet = new HashSet(); 58 | for (int i = 0; i < stockBuying.size(); i++) 59 | { 60 | Stock s = (Stock) stockBuying.get(i); 61 | Trade buyTrade = this.stockTradeDAO.createBuyTrade (user , s , quantities[i] , currenTransaction ); 62 | buyTradesSet.add(buyTrade); 63 | } 64 | this.stockTradeDAO.updateBuyMap (user , buyTradesSet); 65 | this.stockTradeDAO.updateBuyTransactions(buyTradesSet, user); 66 | 67 | //Transaction currenTransaction = this.stockTradeDAO.getLatestNotNullTransaction(user.getEmail()); 68 | 69 | return currenTransaction; 70 | } 71 | 72 | public List getBuyTradesUsingCurrentTransaction (User user , Transaction transaction) 73 | { 74 | Transaction h = this.stockTradeDAO.getLatestTransaction(user.getEmail()); 75 | logger.info("Fetching latest transaction from user::"+h.getId()); 76 | List buyTrades = this.stockTradeDAO.getTradesUsingTransaction (h.getId() , "Buy"); 77 | return buyTrades; 78 | 79 | } 80 | 81 | public List getSellTradesUsingCurrentTransaction (User user , Transaction transaction) 82 | { 83 | Transaction h = this.stockTradeDAO.getLatestTransaction(user.getEmail()); 84 | logger.info("Fetching latest transaction from user::"+h.getId()); 85 | List sellTrades = this.stockTradeDAO.getTradesUsingTransaction (h.getId() , "Sell"); 86 | return sellTrades; 87 | 88 | } 89 | 90 | 91 | public double getTotalPrice (List trades) 92 | { 93 | double result =0.0; 94 | for (Trade tr: trades) 95 | { 96 | result = result + (tr.getIndividualPrice() * tr.getQuantity()); 97 | } 98 | return result; 99 | } 100 | 101 | 102 | public List getAllTransactions (String email) 103 | { 104 | return this.stockTradeDAO.getAllTransactions (email); 105 | } 106 | 107 | public boolean checkIfAccountAttached (User user) 108 | { 109 | return this.stockTradeDAO.checkIfAccountAttached(user); 110 | } 111 | 112 | 113 | 114 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/dao/ForecastDAO.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.dao; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import javax.persistence.EntityManager; 10 | import javax.persistence.NoResultException; 11 | import javax.persistence.PersistenceContext; 12 | import javax.persistence.TypedQuery; 13 | import javax.transaction.Transactional; 14 | 15 | import com.neu.edu.stocktrading.model.Stock; 16 | import com.neu.edu.stocktrading.model.User; 17 | import com.neu.edu.stocktrading.model.WatchList; 18 | 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.stereotype.Component; 22 | 23 | @Component 24 | public class ForecastDAO { 25 | 26 | @PersistenceContext 27 | private EntityManager entityManager; 28 | 29 | private static final Logger logger = LoggerFactory.getLogger(ForecastDAO.class); 30 | 31 | public User getProfileAttributes(String email) 32 | { 33 | logger.info("Getting user from email : " + email); 34 | TypedQuery query = this.entityManager.createQuery("SELECT u from User u where u.email = ?1", User.class); 35 | query.setParameter(1, email); 36 | return query.getSingleResult(); 37 | } 38 | 39 | public Map> retrieveSellList(User user) { 40 | 41 | List sellingList = new ArrayList(); 42 | List sellingListAmount = new ArrayList(); 43 | 44 | User u = getProfileAttributes(user.getEmail()); 45 | WatchList wt = u.getWatchList(); 46 | 47 | if (wt != null) { 48 | logger.info("watchlist id:::" + wt.getId()); 49 | 50 | Map map = wt.getStockToAmount(); 51 | logger.info("map::" + map); 52 | Iterator it = map.entrySet().iterator(); 53 | while (it.hasNext()) { 54 | Map.Entry pair = (Map.Entry) it.next(); 55 | if ((int) pair.getValue() > 0) { 56 | Integer stockKey = (Integer) pair.getKey(); 57 | Stock s = this.getStockFromId(Integer.toUnsignedLong((int) pair.getKey())); 58 | logger.info("unsold shares::" + s.getStockName()); 59 | sellingList.add(s); 60 | sellingListAmount.add((int) pair.getValue()); 61 | } 62 | } 63 | 64 | } 65 | 66 | Map> userStockList = new HashMap>(); 67 | userStockList.put("Sell", sellingList); 68 | userStockList.put("Amount", sellingListAmount); 69 | 70 | return userStockList; 71 | 72 | } 73 | 74 | public Stock getStockFromId(long id) throws NoResultException { 75 | logger.info("Getting stock data from database for ID "); 76 | TypedQuery query = this.entityManager.createQuery("SELECT c from Stock c where c.id = ?1", Stock.class); 77 | query.setParameter(1, id); 78 | query.setMaxResults(1); 79 | return query.getSingleResult(); 80 | } 81 | 82 | public Stock checkIfStockExists(String symbol) throws NoResultException { 83 | logger.info("Getting user data from database for user "); 84 | TypedQuery query = this.entityManager.createQuery("SELECT c from Stock c where c.stockSymbol = ?1", 85 | Stock.class); 86 | query.setParameter(1, symbol); 87 | query.setMaxResults(1); 88 | return query.getSingleResult(); 89 | } 90 | 91 | @Transactional 92 | public boolean addStockToWatchList(User user, String stockSymbol) { 93 | logger.info("addStockToWatchList::" + stockSymbol); 94 | logger.info("addStockToWatchList::" + user.getFirstName()); 95 | Stock st = null; 96 | try { 97 | st = checkIfStockExists(stockSymbol); 98 | } catch (Exception e) { 99 | st = null; 100 | } 101 | 102 | if (st != null) { 103 | WatchList wt = user.getWatchList(); 104 | 105 | if (wt == null) { 106 | wt = new WatchList(); 107 | } 108 | logger.info("addStockToWatchList::" + wt.toString()); 109 | String hs = wt.getStocks(); 110 | if (hs == null || hs.isEmpty()) { 111 | hs = "" + st.getStockSymbol(); 112 | } else 113 | hs = hs + "|" + st.getStockSymbol(); 114 | 115 | wt.setStocks(hs); 116 | user.setWatchList(wt); 117 | logger.info("addStockToWatchList::" + user.getWatchList().toString()); 118 | flushAndClear(); 119 | } 120 | 121 | logger.info("addStockToWatchList::done updating"); 122 | return true; 123 | 124 | } 125 | 126 | private void flushAndClear() { 127 | this.entityManager.flush(); 128 | this.entityManager.clear(); 129 | } 130 | 131 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/stock-forecast.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | Recommendations 24 | 25 | 50 | 51 | 52 | 53 | 54 | 55 |
56 |
57 |
58 |
59 |
60 |
61 |

Recommendations based on your portfolio

62 |
63 | 64 |
65 |
66 | No recommendations ! Please start trading to get recommendations 67 |
68 |
69 |
70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 98 | 99 | 100 | 101 |
Stock NameStock SymbolCurrent PriceChangeBuying PriceSelling PriceAdd to Watchlist
92 |
93 | 96 |
97 |
102 | 103 | 104 | 105 |
106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 |
114 |
115 | 116 | 117 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/HomePageController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | import com.neu.edu.stocktrading.model.StockAPIBean; 11 | import com.neu.edu.stocktrading.service.HomePageService; 12 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.web.bind.annotation.GetMapping; 19 | import org.springframework.web.servlet.ModelAndView; 20 | 21 | @Controller 22 | public class HomePageController { 23 | private static final Logger logger = LoggerFactory.getLogger(HomePageController.class); 24 | 25 | @Autowired 26 | private HomePageService homePageService; 27 | 28 | @Autowired 29 | private SessionManagementUtil sessionMgmtUtils; 30 | 31 | @GetMapping(value = "/") 32 | public ModelAndView home(HttpServletRequest request) 33 | { 34 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 35 | { 36 | logger.info("Session does not exist. Redirect to login page"); 37 | ModelAndView mv = new ModelAndView("landing-page"); 38 | return mv; 39 | } 40 | 41 | try { 42 | 43 | if (request.getSession().getAttribute("isAdmin").equals("Yes")) 44 | { 45 | List stocks = this.homePageService.getTopStocks(); 46 | ModelAndView mv = new ModelAndView("admin-home"); 47 | mv.addObject("stocks", stocks); 48 | 49 | ArrayList logos = new ArrayList(); 50 | logos.add("//logo.clearbit.com/amazon.com"); 51 | logos.add("//logo.clearbit.com/google.com"); 52 | logos.add("//logo.clearbit.com/apple.com"); 53 | logos.add("//logo.clearbit.com/netflix.com"); 54 | 55 | logos.add("//logo.clearbit.com/tesla.com"); 56 | logos.add("//logo.clearbit.com/facebook.com"); 57 | logos.add("//logo.clearbit.com/cisco.com?size=120"); 58 | logos.add("//logo.clearbit.com/oracle.com"); 59 | 60 | logos.add("//logo.clearbit.com/intel.com"); 61 | logos.add("//logo.clearbit.com/qualcomm.com"); 62 | logos.add("//logo.clearbit.com/ebay.com"); 63 | logos.add("//logo.clearbit.com/dell.com?size=100"); 64 | mv.addObject("logos", logos); 65 | 66 | Map currencies = new HashMap (); 67 | currencies = this.homePageService.getTopCurrencies(); 68 | mv.addObject("currencies", currencies); 69 | 70 | 71 | return mv; 72 | 73 | } 74 | 75 | } 76 | 77 | catch (Exception e) { 78 | logger.error(e.toString()); 79 | } 80 | 81 | 82 | 83 | List stocks = this.homePageService.getTopStocks(); 84 | ModelAndView mv = new ModelAndView("home"); 85 | mv.addObject("stocks", stocks); 86 | 87 | ArrayList logos = new ArrayList(); 88 | logos.add("//logo.clearbit.com/amazon.com"); 89 | logos.add("//logo.clearbit.com/google.com"); 90 | logos.add("//logo.clearbit.com/apple.com"); 91 | logos.add("//logo.clearbit.com/netflix.com"); 92 | 93 | logos.add("//logo.clearbit.com/tesla.com"); 94 | logos.add("//logo.clearbit.com/facebook.com"); 95 | logos.add("//logo.clearbit.com/cisco.com?size=120"); 96 | logos.add("//logo.clearbit.com/oracle.com"); 97 | 98 | logos.add("//logo.clearbit.com/intel.com"); 99 | logos.add("//logo.clearbit.com/qualcomm.com"); 100 | logos.add("//logo.clearbit.com/ebay.com"); 101 | logos.add("//logo.clearbit.com/dell.com?size=100"); 102 | mv.addObject("logos", logos); 103 | 104 | 105 | Map currencies = new HashMap (); 106 | currencies = this.homePageService.getTopCurrencies(); 107 | mv.addObject("currencies", currencies); 108 | 109 | return mv; 110 | } 111 | 112 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/stock-watchlist.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | Watch List 24 | 30 | 44 | 49 | 50 | 51 | 52 | 53 | 54 |
55 |
56 |
57 |
58 |
59 |
60 |

My Stock Watch List

61 |
62 | 63 |
64 |
65 | No items in watch list ! 66 |
67 |
68 |
69 | 70 |
71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 |
BuyStock NameStock SymbolCurrent PriceChangeMarket TypeBuying PriceSelling Price
98 |
99 | 100 |
101 | 102 | 103 |
104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 |
112 |
113 | 114 | 115 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/model/User.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.model; 2 | 3 | import java.util.Set; 4 | 5 | import javax.persistence.CascadeType; 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.FetchType; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.GenerationType; 11 | import javax.persistence.Id; 12 | import javax.persistence.OneToMany; 13 | import javax.persistence.OneToOne; 14 | import javax.persistence.Table; 15 | 16 | import org.hibernate.validator.constraints.Email; 17 | import org.hibernate.validator.constraints.NotEmpty; 18 | 19 | @Entity 20 | @Table(name = "user") 21 | public class User 22 | { 23 | public User(){ 24 | } 25 | 26 | @Id 27 | @GeneratedValue (strategy = GenerationType.IDENTITY) 28 | private long id; 29 | 30 | @Column(unique = true, nullable = false) 31 | @Email 32 | @NotEmpty 33 | private String email ; 34 | 35 | @Column(nullable = false) 36 | private String password; 37 | 38 | @Column(nullable = false) 39 | private String firstName ; 40 | 41 | @Column(nullable = false) 42 | private String lastName ; 43 | 44 | @Column 45 | private boolean verified ; 46 | 47 | 48 | @Column 49 | private String phoneNumber; 50 | 51 | @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 52 | private UserBankDetails userBankDetails; 53 | 54 | 55 | @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 56 | private WatchList watchList; 57 | 58 | @OneToMany(mappedBy="user" , fetch = FetchType.EAGER) 59 | private Set transactions; 60 | 61 | 62 | 63 | public long getId() { 64 | return this.id; 65 | } 66 | 67 | public void setId(long id) { 68 | this.id = id; 69 | } 70 | 71 | public String getEmail() { 72 | return this.email; 73 | } 74 | 75 | public void setEmail(String email) { 76 | this.email = email; 77 | } 78 | 79 | public String getPassword() { 80 | return this.password; 81 | } 82 | 83 | public void setPassword(String password) { 84 | this.password = password; 85 | } 86 | 87 | public String getFirstName() { 88 | return this.firstName; 89 | } 90 | 91 | public void setFirstName(String firstName) { 92 | this.firstName = firstName; 93 | } 94 | 95 | public String getLastName() { 96 | return this.lastName; 97 | } 98 | 99 | public void setLastName(String lastName) { 100 | this.lastName = lastName; 101 | } 102 | 103 | 104 | public String getPhoneNumber() { 105 | return this.phoneNumber; 106 | } 107 | 108 | public void setPhoneNumber(String phoneNumber) 109 | { 110 | this.phoneNumber = phoneNumber; 111 | } 112 | 113 | 114 | public UserBankDetails getUserBankDetails() { 115 | return this.userBankDetails; 116 | } 117 | 118 | public void setUserBankDetails(UserBankDetails userBankDetails) { 119 | this.userBankDetails = userBankDetails; 120 | } 121 | 122 | public Set getTransactions() { 123 | return this.transactions; 124 | } 125 | 126 | public void setTransactions(Set transactions) { 127 | this.transactions = transactions; 128 | } 129 | 130 | 131 | @Override 132 | public String toString() { 133 | return "{" + 134 | " id='" + getId() + "'" + 135 | ", email='" + getEmail() + "'" + 136 | ", password='" + getPassword() + "'" + 137 | ", firstName='" + getFirstName() + "'" + 138 | ", lastName='" + getLastName() + "'" + 139 | ", phoneNumber='" + getPhoneNumber() + "'" + 140 | ", transactions='" + getTransactions() + "'" + 141 | "}"; 142 | } 143 | 144 | /** 145 | * @return the watchList 146 | */ 147 | public WatchList getWatchList() { 148 | return watchList; 149 | } 150 | 151 | /** 152 | * @param watchList the watchList to set 153 | */ 154 | public void setWatchList(WatchList watchList) { 155 | this.watchList = watchList; 156 | } 157 | 158 | /** 159 | * @return the verified 160 | */ 161 | public boolean isVerified() { 162 | return verified; 163 | } 164 | 165 | /** 166 | * @param verified the verified to set 167 | */ 168 | public void setVerified(boolean verified) { 169 | this.verified = verified; 170 | } 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | } -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/UserAccountController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | import com.neu.edu.stocktrading.model.User; 9 | import com.neu.edu.stocktrading.model.UserBankDetails; 10 | import com.neu.edu.stocktrading.service.UserAccountService; 11 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 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.validation.BindingResult; 18 | import org.springframework.validation.annotation.Validated; 19 | import org.springframework.web.bind.annotation.GetMapping; 20 | import org.springframework.web.bind.annotation.ModelAttribute; 21 | import org.springframework.web.bind.annotation.PostMapping; 22 | import org.springframework.web.servlet.ModelAndView; 23 | 24 | @Controller 25 | public class UserAccountController 26 | { 27 | private static final Logger logger = LoggerFactory.getLogger(UserAccountController.class); 28 | 29 | @Autowired 30 | private SessionManagementUtil sessionMgmtUtils; 31 | 32 | @Autowired 33 | private UserAccountService userAccountService; 34 | 35 | 36 | @GetMapping(value = "/update/profile.htm") 37 | public ModelAndView updateProfilePage(HttpServletRequest request) 38 | { 39 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 40 | { 41 | logger.info("Please login to access this page"); 42 | ModelAndView mv = new ModelAndView("login-form"); 43 | mv.addObject("user", new User()); 44 | mv.addObject("errorMessage", "Please login to access this page"); 45 | return mv; 46 | 47 | } 48 | ModelAndView mv = new ModelAndView("profile-update"); 49 | String email = (String) request.getSession().getAttribute("user"); 50 | User user = this.userAccountService.getProfileAttributes(email); 51 | logger.info("updateProfilePage::"+user.toString()); 52 | mv.addObject("user", user); 53 | return mv; 54 | } 55 | 56 | 57 | @PostMapping(value = "/update/profile.htm") 58 | public ModelAndView updateProfile( HttpServletRequest request, 59 | HttpServletResponse response, @ModelAttribute("user") @Validated User user , BindingResult bindingResult) throws IllegalStateException, IOException { 60 | 61 | logger.info("Inside updateProfile::"+user.toString()); 62 | User updatedUser = this.userAccountService.updateProfile(user.getEmail() , user.getPhoneNumber()); 63 | 64 | ModelAndView mv = new ModelAndView("profile-update"); 65 | mv.addObject("user", updatedUser); 66 | mv.addObject("successMessage", "Profile updated successfully"); 67 | return mv; 68 | } 69 | 70 | @GetMapping(value = "/update/bankAccount.htm") 71 | public ModelAndView manageBankAccount(HttpServletRequest request) 72 | { 73 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 74 | { 75 | logger.info("Please login to access this page"); 76 | ModelAndView mv = new ModelAndView("login-form"); 77 | mv.addObject("user", new User()); 78 | mv.addObject("errorMessage", "Please login to access this page"); 79 | return mv; 80 | 81 | } 82 | ModelAndView mv = new ModelAndView("user-account"); 83 | 84 | String email = (String) request.getSession().getAttribute("user"); 85 | User user = this.userAccountService.getProfileAttributes(email); 86 | UserBankDetails userBank = user.getUserBankDetails(); 87 | if (userBank ==null) 88 | userBank = new UserBankDetails(); 89 | 90 | logger.info(userBank.toString()); 91 | mv.addObject("userBank", userBank); 92 | return mv; 93 | } 94 | 95 | @PostMapping(value = "/update/bankAccount.htm") 96 | public ModelAndView updateBankDetails( HttpServletRequest request, 97 | HttpServletResponse response, @ModelAttribute("userBank") @Validated UserBankDetails userbank , BindingResult bindingResult 98 | ) throws IllegalStateException, IOException { 99 | 100 | logger.info("Inside updateBankDetails::"+userbank.toString()); 101 | 102 | String email = (String) request.getSession().getAttribute("user"); 103 | User user = this.userAccountService.getProfileAttributes(email); 104 | 105 | logger.info(userbank.toString()); 106 | 107 | User updatedUser = this.userAccountService.updateBankDetails(user,userbank); 108 | 109 | ModelAndView mv = new ModelAndView("user-account"); 110 | mv.addObject("user", updatedUser); 111 | mv.addObject("successMessage", "Bank Account added successfully"); 112 | return mv; 113 | } 114 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/user-dashboard.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | Stock Portfolio 24 | 25 | 31 | 49 | 50 | 51 | 52 | 53 | 54 | 55 |
56 |
57 |
58 |
59 |
60 |
61 |

Stock Portfolio

62 |
63 |
64 |
65 |
66 | No stocks to sell ! 67 |
68 |
69 |
70 | 71 |
73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 |
Sell existing shares
SellStock NameStock SymbolCurrent PriceChangeMarket TypeSelling PriceAmount
92 |
103 |
104 | 105 | 106 |
107 |
108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 |
116 |
117 | 118 | 119 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/dao/HomePageDAO.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.dao; 2 | 3 | import javax.persistence.EntityManager; 4 | import javax.persistence.NoResultException; 5 | import javax.persistence.PersistenceContext; 6 | import javax.persistence.TypedQuery; 7 | import javax.transaction.Transactional; 8 | 9 | import com.neu.edu.stocktrading.model.Stock; 10 | import com.neu.edu.stocktrading.model.StockAPIBean; 11 | 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.stereotype.Component; 15 | 16 | @Component 17 | public class HomePageDAO { 18 | private static final Logger logger = LoggerFactory.getLogger(HomePageDAO.class); 19 | 20 | @PersistenceContext 21 | private EntityManager entityManager; 22 | 23 | 24 | @Transactional 25 | public void saveStock(StockAPIBean stock) 26 | { 27 | Stock st = new Stock(); 28 | st.setStockName(stock.getName()); 29 | st.setStockSymbol(stock.getSymbol()); 30 | st.setChange(stock.getPercentChange()); 31 | 32 | Double tempDouble = 0.0; 33 | if (stock.getLow() != null && !stock.getLow().equals("")) { 34 | st.setBuyingPrice(Double.parseDouble(stock.getLow())); 35 | } else 36 | st.setBuyingPrice(tempDouble); 37 | 38 | if (stock.getHigh() != null && !stock.getHigh().equals("")) { 39 | st.setSellingPrice(Double.parseDouble(stock.getHigh())); 40 | } else 41 | st.setSellingPrice(tempDouble); 42 | 43 | if (stock.getFiftyTwoWkHigh() != null && !stock.getFiftyTwoWkHigh().equals("")) { 44 | st.setHigh52(Double.parseDouble(stock.getFiftyTwoWkHigh())); 45 | } else 46 | st.setHigh52(tempDouble); 47 | 48 | if (stock.getFiftyTwoWkLow() != null && !stock.getFiftyTwoWkLow().equals("")) { 49 | st.setLow52(Double.parseDouble(stock.getFiftyTwoWkLow())); 50 | } else 51 | st.setLow52(tempDouble); 52 | 53 | if (stock.getLastPrice() != null && !stock.getLastPrice().equals("")) { 54 | st.setCurrentPrice(Double.parseDouble(stock.getLastPrice())); 55 | } else 56 | st.setCurrentPrice(tempDouble); 57 | 58 | st.setMarketType(stock.getExchange()); 59 | 60 | this.entityManager.merge(st); 61 | flushAndClear(); 62 | 63 | } 64 | 65 | @Transactional 66 | public void updateStock(StockAPIBean stock, Long id) 67 | { 68 | Stock st = this.entityManager.find(Stock.class, id); 69 | st.setStockName(stock.getName()); 70 | st.setStockSymbol(stock.getSymbol()); 71 | 72 | st.setChange(stock.getPercentChange()); 73 | 74 | Double tempDouble = 0.0; 75 | // if (stock.getLow() != null && !stock.getLow().equals("")) { 76 | // st.setBuyingPrice(Double.parseDouble(stock.getLow())); 77 | // } else 78 | // st.setBuyingPrice(tempDouble); 79 | 80 | // if (stock.getHigh() != null && !stock.getHigh().equals("")) { 81 | // st.setSellingPrice(Double.parseDouble(stock.getHigh())); 82 | // } else 83 | // st.setSellingPrice(tempDouble); 84 | 85 | 86 | if (stock.getLow() != null && !stock.getLow().equals("")) { 87 | st.setBuyingPrice(Double.parseDouble(stock.getLastPrice())); 88 | } else 89 | st.setBuyingPrice(tempDouble); 90 | 91 | if (stock.getHigh() != null && !stock.getHigh().equals("")) { 92 | st.setSellingPrice(Double.parseDouble(stock.getLastPrice())); 93 | } else 94 | st.setSellingPrice(tempDouble); 95 | 96 | if (stock.getFiftyTwoWkHigh() != null && !stock.getFiftyTwoWkHigh().equals("")) { 97 | st.setHigh52(Double.parseDouble(stock.getFiftyTwoWkHigh())); 98 | } else 99 | st.setHigh52(tempDouble); 100 | 101 | if (stock.getFiftyTwoWkLow() != null && !stock.getFiftyTwoWkLow().equals("")) { 102 | st.setLow52(Double.parseDouble(stock.getFiftyTwoWkLow())); 103 | } else 104 | st.setLow52(tempDouble); 105 | 106 | if (stock.getLastPrice() != null && !stock.getLastPrice().equals("")) { 107 | st.setCurrentPrice(Double.parseDouble(stock.getLastPrice())); 108 | } else 109 | st.setCurrentPrice(tempDouble); 110 | 111 | st.setMarketType(stock.getExchange()); 112 | flushAndClear(); 113 | 114 | } 115 | 116 | public Stock checkIfStockExists(String symbol) throws NoResultException 117 | { 118 | logger.info("Getting user data from database for user "); 119 | TypedQuery query = this.entityManager.createQuery("SELECT c from Stock c where c.stockSymbol = ?1", 120 | Stock.class); 121 | query.setParameter(1, symbol); 122 | query.setMaxResults(1); 123 | return query.getSingleResult(); 124 | } 125 | 126 | private void flushAndClear() { 127 | this.entityManager.flush(); 128 | this.entityManager.clear(); 129 | } 130 | 131 | } -------------------------------------------------------------------------------- /stocktrading/.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | https://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | import java.io.File; 21 | import java.io.FileInputStream; 22 | import java.io.FileOutputStream; 23 | import java.io.IOException; 24 | import java.net.URL; 25 | import java.nio.channels.Channels; 26 | import java.nio.channels.ReadableByteChannel; 27 | import java.util.Properties; 28 | 29 | public class MavenWrapperDownloader { 30 | 31 | /** 32 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 33 | */ 34 | private static final String DEFAULT_DOWNLOAD_URL = 35 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; 36 | 37 | /** 38 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 39 | * use instead of the default one. 40 | */ 41 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 42 | ".mvn/wrapper/maven-wrapper.properties"; 43 | 44 | /** 45 | * Path where the maven-wrapper.jar will be saved to. 46 | */ 47 | private static final String MAVEN_WRAPPER_JAR_PATH = 48 | ".mvn/wrapper/maven-wrapper.jar"; 49 | 50 | /** 51 | * Name of the property which should be used to override the default download url for the wrapper. 52 | */ 53 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 54 | 55 | public static void main(String args[]) { 56 | System.out.println("- Downloader started"); 57 | File baseDirectory = new File(args[0]); 58 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 59 | 60 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 61 | // wrapperUrl parameter. 62 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 63 | String url = DEFAULT_DOWNLOAD_URL; 64 | if(mavenWrapperPropertyFile.exists()) { 65 | FileInputStream mavenWrapperPropertyFileInputStream = null; 66 | try { 67 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 68 | Properties mavenWrapperProperties = new Properties(); 69 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 70 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 71 | } catch (IOException e) { 72 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 73 | } finally { 74 | try { 75 | if(mavenWrapperPropertyFileInputStream != null) { 76 | mavenWrapperPropertyFileInputStream.close(); 77 | } 78 | } catch (IOException e) { 79 | // Ignore ... 80 | } 81 | } 82 | } 83 | System.out.println("- Downloading from: : " + url); 84 | 85 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 86 | if(!outputFile.getParentFile().exists()) { 87 | if(!outputFile.getParentFile().mkdirs()) { 88 | System.out.println( 89 | "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 90 | } 91 | } 92 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 93 | try { 94 | downloadFileFromURL(url, outputFile); 95 | System.out.println("Done"); 96 | System.exit(0); 97 | } catch (Throwable e) { 98 | System.out.println("- Error downloading"); 99 | e.printStackTrace(); 100 | System.exit(1); 101 | } 102 | } 103 | 104 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 105 | URL website = new URL(urlString); 106 | ReadableByteChannel rbc; 107 | rbc = Channels.newChannel(website.openStream()); 108 | FileOutputStream fos = new FileOutputStream(destination); 109 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 110 | fos.close(); 111 | rbc.close(); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/stock-analysis.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | 24 | Stock Analysis 25 | 26 | 27 | 28 | 29 | 30 | 31 |
32 |
33 |
34 |
35 |
36 |
37 |

Stock Analysis based on Portfolio

38 |
39 | 40 |
41 |
Empty Portfolio ! Please start trading to get Portfolio Analysis
42 |
43 | 44 |
45 | 46 |
47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 |
Sell these Stocks
AnalysisStock NamePercent ChangeSelling Price
Sell
68 |
69 | 70 |

71 | 72 |
73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 |
Buy these Stocks
AnalysisStock NamePercent ChangeBuying Price
Buy
92 |
93 | 94 |

95 | 96 |
97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 |
Hold these Stocks
AnalysisStock NamePercent ChangeSelling Price
Buy
116 |
117 | 118 | 119 |
120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 |
129 |
130 | 131 | 132 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/StockAnalysisService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Random; 9 | import java.util.stream.Collectors; 10 | import java.util.stream.Stream; 11 | 12 | import com.neu.edu.stocktrading.dao.StockAnalysisDAO; 13 | import com.neu.edu.stocktrading.model.Stock; 14 | import com.neu.edu.stocktrading.model.User; 15 | 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.stereotype.Service; 20 | 21 | @Service 22 | public class StockAnalysisService { 23 | @Autowired 24 | private StockAnalysisDAO stockAnalysisDAO; 25 | 26 | private static final Logger logger = LoggerFactory.getLogger(StockAnalysisService.class); 27 | 28 | public User getProfileAttributes(String email) { 29 | return this.stockAnalysisDAO.getProfileAttributes(email); 30 | } 31 | 32 | public Map> retrieveSellList(User user) { 33 | return this.stockAnalysisDAO.retrieveSellList(user); 34 | } 35 | 36 | public ArrayList removeDuplicates(List list) { 37 | ArrayList newList = new ArrayList(); 38 | 39 | for (Stock element : list) { 40 | if (!newList.contains(element)) { 41 | newList.add(element); 42 | } 43 | } 44 | 45 | return newList; 46 | } 47 | 48 | public List getPotentialBuyFromWatchlist(User user, List sellStocks) { 49 | List watchlistStocks = this.stockAnalysisDAO.getWatchlistStocks(user); 50 | 51 | Iterator itr = watchlistStocks.iterator(); 52 | while (itr.hasNext()) { 53 | Stock s = (Stock) itr.next(); 54 | if (sellStocks.contains(s)) { 55 | itr.remove(); 56 | } 57 | } 58 | 59 | for (Stock s : watchlistStocks) { 60 | logger.info("potential buy list::" + s.getStockName()); 61 | } 62 | 63 | return watchlistStocks; 64 | } 65 | 66 | public Map> buildPortfolio(List potentialBuyList, List sellStocks, List sellAmount) 67 | { 68 | logger.info("buildPortfolio::INSIDE"); 69 | List combinedList = Stream.of(potentialBuyList, sellStocks).flatMap(x -> x.stream()) 70 | .collect(Collectors.toList()); 71 | 72 | logger.info("combinedList::"+combinedList.size()); 73 | 74 | 75 | int totalSumStocks = 0; 76 | for (Integer e : sellAmount) 77 | { 78 | totalSumStocks += e; 79 | } 80 | logger.info("Total number of existing stocks::"+totalSumStocks); 81 | int totalNumberOfStocksInPortfolio = totalSumStocks * 2; 82 | 83 | int n = combinedList.size(); 84 | int divideStocks = totalNumberOfStocksInPortfolio; 85 | 86 | List divideRatio = new ArrayList(); 87 | 88 | Random random = new Random(System.currentTimeMillis()); 89 | for (int i = 0; i < n -1; i++) 90 | { 91 | int j = random.nextInt(divideStocks - (n -i)) + 1; 92 | divideRatio.add(j); 93 | divideStocks -= j; 94 | } 95 | divideRatio.add(divideStocks); 96 | 97 | logger.info("divideRatio::"+divideRatio); 98 | 99 | List buyList = new ArrayList(); 100 | List sellList = new ArrayList(); 101 | List holdList = new ArrayList(); 102 | 103 | for (int i=0; i 0) 114 | { 115 | buyList.add(s); 116 | } 117 | else 118 | { 119 | sellList.add(s); 120 | } 121 | } 122 | 123 | logger.info("sellList:"+sellList); 124 | logger.info("buyList:"+buyList); 125 | 126 | if (sellList.size()>1) 127 | { 128 | Stock sellTemp = sellList.get(0); 129 | holdList.add(sellTemp); 130 | sellList.remove(sellTemp); 131 | } 132 | 133 | 134 | Map > results = new HashMap>(); 135 | results.put("Sell", sellList); 136 | results.put("Buy", buyList); 137 | results.put("Hold", holdList); 138 | 139 | return results; 140 | 141 | } 142 | 143 | public int getStockAmountFromStock (Stock s, List sellStocks, List sellAmount) 144 | { 145 | int resultAmount =0; 146 | for (int i=0; i 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | My Profile 12 | 13 | 14 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 |
24 | 25 | 26 |
27 | 78 |
79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 |
97 | 98 | 99 | 100 | 101 | 102 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/user-account.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | My Profile 12 | 13 | 14 | 16 | 17 | 28 | 29 | 30 | 31 | 32 | 33 |
34 | 35 |
36 | 37 | 38 |
39 | 91 |
92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 |
110 | 111 | 112 | 113 | 114 | 115 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/UserAuthController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | import com.neu.edu.stocktrading.model.LoginForm; 9 | import com.neu.edu.stocktrading.model.User; 10 | import com.neu.edu.stocktrading.service.UserAuthService; 11 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 12 | import com.neu.edu.stocktrading.validator.RegisterUserValidator; 13 | 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.stereotype.Controller; 18 | import org.springframework.ui.ModelMap; 19 | import org.springframework.validation.BindingResult; 20 | import org.springframework.validation.annotation.Validated; 21 | import org.springframework.web.bind.annotation.GetMapping; 22 | import org.springframework.web.bind.annotation.ModelAttribute; 23 | import org.springframework.web.bind.annotation.PostMapping; 24 | import org.springframework.web.bind.annotation.RequestMapping; 25 | import org.springframework.web.servlet.ModelAndView; 26 | 27 | @Controller 28 | public class UserAuthController { 29 | private static final Logger logger = LoggerFactory.getLogger(UserAuthController.class); 30 | 31 | @Autowired 32 | private UserAuthService userAuthService; 33 | 34 | @Autowired 35 | private SessionManagementUtil sessionMgmtUtils; 36 | 37 | @Autowired 38 | RegisterUserValidator registerUserValidator; 39 | 40 | @GetMapping(value = "/register.htm") 41 | public ModelAndView showRegisterPage(HttpServletRequest request, HttpServletResponse response, ModelMap map) { 42 | ModelAndView mv = new ModelAndView("register-form"); 43 | mv.addObject("user", new User()); 44 | return mv; 45 | } 46 | 47 | @PostMapping(value = "/register.htm") 48 | public ModelAndView registerUser(HttpServletRequest request, 49 | HttpServletResponse response, @ModelAttribute("user") @Validated User user, BindingResult bindingResult, 50 | ModelMap map) throws IllegalStateException, IOException { 51 | 52 | registerUserValidator.validate(user, bindingResult); 53 | 54 | if (bindingResult.hasErrors()) 55 | { 56 | ModelAndView mv = new ModelAndView("register-form"); 57 | mv.addObject("user", new User()); 58 | mv.addObject("errorMessage", "Password should be minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character"); 59 | return mv; 60 | } 61 | 62 | if (this.userAuthService.checkIfUserRegistered(user)) { 63 | ModelAndView mv = new ModelAndView("register-form"); 64 | mv.addObject("user", new User()); 65 | mv.addObject("errorMessage", "Oops. An account with this email already exists."); 66 | return mv; 67 | } 68 | 69 | if (userAuthService.registerUser(user)) 70 | { 71 | logger.info("User successfully registered"); 72 | ModelAndView mv = new ModelAndView("login-form"); 73 | mv.addObject("user", new User()); 74 | return mv; 75 | } 76 | else 77 | { 78 | ModelAndView mv = new ModelAndView("register-form"); 79 | mv.addObject("user", new User()); 80 | mv.addObject("errorMessage", "Oops. Something went wrong. Please try again."); 81 | return mv; 82 | 83 | } 84 | 85 | } 86 | 87 | @GetMapping(value = "/login.htm") 88 | public ModelAndView showLoginPage(HttpServletRequest request, HttpServletResponse response, LoginForm user) { 89 | ModelAndView mv = new ModelAndView("login-form"); 90 | mv.addObject("user", new User()); 91 | return mv; 92 | } 93 | 94 | @PostMapping(value = "/login.htm") 95 | public ModelAndView loginUser(HttpServletRequest request, HttpServletResponse response, 96 | @ModelAttribute("user") @Validated LoginForm loginForm, BindingResult bindingResult) { 97 | 98 | if (bindingResult.hasErrors()) { 99 | return new ModelAndView("login-form"); 100 | } 101 | 102 | if (!this.sessionMgmtUtils.doesSessionExist(request)) { 103 | 104 | if (this.userAuthService.isAdmin(loginForm) == true) { 105 | logger.info("Admin login"); 106 | this.sessionMgmtUtils.createNewSessionForUser(request, loginForm.getEmail()); 107 | ModelAndView mv = new ModelAndView("redirect:/"); 108 | request.getSession().setAttribute("isAdmin", "Yes"); 109 | return mv; 110 | } else if (this.userAuthService.authenticate(loginForm) == true) { 111 | logger.info("Successfully authenticated"); 112 | this.sessionMgmtUtils.createNewSessionForUser(request, loginForm.getEmail()); 113 | ModelAndView mv = new ModelAndView("redirect:/"); 114 | if (this.userAuthService.isUserVerified(loginForm)) { 115 | request.getSession().setAttribute("verified", "yes"); 116 | } else { 117 | request.getSession().setAttribute("verified", "no"); 118 | } 119 | return mv; 120 | 121 | } else { 122 | logger.info("Invalid user credentails"); 123 | ModelAndView mv = new ModelAndView("login-form"); 124 | mv.addObject("user", new User()); 125 | mv.addObject("errorMessage", "Invalid credentails. Please try again."); 126 | return mv; 127 | } 128 | 129 | } 130 | ModelAndView mv = new ModelAndView("redirect:/"); 131 | return mv; 132 | 133 | } 134 | 135 | @RequestMapping(value = "/logout.htm") 136 | public ModelAndView logoutUser(HttpServletRequest request) 137 | { 138 | logger.info("Logging out"); 139 | request.getSession().invalidate(); 140 | return new ModelAndView("redirect:/"); 141 | } 142 | 143 | } -------------------------------------------------------------------------------- /stocktrading/src/main/resources/templates/user-transaction.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 17 | 18 | 19 | 22 | 23 | Transaction Summary 24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
32 |
33 |
34 |
35 |
36 |
Congratulations, your transaction was successfully completed !
37 |
38 | 39 |
40 |
41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 69 | 71 | 72 | 73 | 74 | 75 | 76 | 79 | 81 | 82 | 83 |
Transaction ID:
Stock NameQuantityPrice per stockPrice
67 | Service Charge 68 | 70 |
77 | Total 78 | 80 |
84 |
85 |
86 | 87 | 88 |
89 |
90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 118 | 120 | 121 | 122 | 123 | 124 | 125 | 128 | 130 | 131 | 132 |
Transaction ID:
Stock NameQuantityPrice per stockPrice
116 | Service Charge 117 | 119 |
126 | Total 127 | 129 |
133 |
134 | 135 |

Thank you for your business! 136 |

137 | 138 | 139 | 140 | 141 | 142 | 143 |
144 |
145 | 146 | 147 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/service/HomePageService.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import com.fasterxml.jackson.databind.ObjectMapper; 10 | import com.neu.edu.stocktrading.dao.HomePageDAO; 11 | import com.neu.edu.stocktrading.model.Stock; 12 | import com.neu.edu.stocktrading.model.StockAPIBean; 13 | 14 | import org.json.simple.JSONArray; 15 | import org.json.simple.JSONObject; 16 | import org.json.simple.parser.JSONParser; 17 | import org.json.simple.parser.ParseException; 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | import org.springframework.beans.factory.annotation.Autowired; 21 | import org.springframework.stereotype.Service; 22 | import org.springframework.web.client.RestTemplate; 23 | 24 | import net.sf.json.JSONSerializer; 25 | 26 | @Service 27 | public class HomePageService 28 | { 29 | @Autowired 30 | private HomePageDAO homePageDAO; 31 | 32 | private static final Logger logger = LoggerFactory.getLogger(HomePageService.class); 33 | 34 | @Autowired 35 | private RestTemplate restTemplate; 36 | 37 | // final String stockUri = "https://marketdata.websol.barchart.com/getQuote.json?apikey=b0ccbbb0dae9d39ce81f65718f0ecd10&symbols=AMZN,GOOG,AAPL,GOOG,NFLX,TSLA,FB,CSCO,ORCL,INTC,QCOM,EBAY,DELL,COST,MSFT,TWTR,AABA,SNAP,AMD,ATVI,ZNGA,WDC,BKNG&fields=fiftyTwoWkHigh%2CfiftyTwoWkHighDate%2CfiftyTwoWkLow%2CfiftyTwoWkLowDate"; 38 | final String stockUri1 = "https://marketdata.websol.barchart.com/getQuote.json?apikey=b0ccbbb0dae9d39ce81f65718f0ecd10&symbols=AMZN,GOOG,AAPL,NFLX,TSLA,FB,CSCO,ORCL,INTC,QCOM,EBAY,DELL,COST,MSFT,TWTR,AABA,SNAP,AMD,ATVI,ZNGA&fields=fiftyTwoWkHigh%2CfiftyTwoWkHighDate%2CfiftyTwoWkLow%2CfiftyTwoWkLowDate"; 39 | 40 | final String stockUri2 = "https://marketdata.websol.barchart.com/getQuote.json?apikey=b0ccbbb0dae9d39ce81f65718f0ecd10&symbols=WDC,BKNG,VZ,HPQ,SNE,W,BABA,JNJ,JPM,XOM,BAC,WMT,WFC,V,PG,BUD,T,UNH,HD,C&fields=fiftyTwoWkHigh%2CfiftyTwoWkHighDate%2CfiftyTwoWkLow%2CfiftyTwoWkLowDate"; 41 | 42 | 43 | 44 | final String currencyUri = "https://www.worldtradingdata.com/api/v1/forex?base=USD&sort=newest&api_token=uRqeU8C651htqmF8iI5N6VvSBEIpTiQ5xvvKkz9Slsm1D9jFvIGdG97m0RpF"; 45 | 46 | public List getTopStocks () 47 | { 48 | List stocks = new ArrayList(); 49 | 50 | String result = this.restTemplate.getForObject(stockUri1, String.class); 51 | Object obj = null; 52 | JSONObject jo = null; 53 | try { 54 | obj = new JSONParser().parse(result); 55 | jo = (JSONObject) obj; 56 | } catch (ParseException e) { 57 | logger.error(e.toString()); 58 | obj = null; 59 | jo = null; 60 | } 61 | 62 | if (obj != null && jo != null) { 63 | JSONArray ja = (JSONArray) jo.get("results"); 64 | 65 | Iterator itr2 = ja.iterator(); 66 | 67 | while (itr2.hasNext()) { 68 | 69 | Map map = (Map) itr2.next(); 70 | ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper 71 | StockAPIBean pojo = mapper.convertValue(map, StockAPIBean.class); 72 | stocks.add(pojo); 73 | } 74 | } 75 | 76 | result = this.restTemplate.getForObject(stockUri2, String.class); 77 | obj = null; 78 | jo = null; 79 | try { 80 | obj = new JSONParser().parse(result); 81 | jo = (JSONObject) obj; 82 | } catch (ParseException e) { 83 | logger.error(e.toString()); 84 | obj = null; 85 | jo = null; 86 | } 87 | 88 | if (obj != null && jo != null) 89 | { 90 | JSONArray ja = (JSONArray) jo.get("results"); 91 | 92 | Iterator itr2 = ja.iterator(); 93 | 94 | while (itr2.hasNext()) { 95 | 96 | Map map = (Map) itr2.next(); 97 | ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper 98 | StockAPIBean pojo = mapper.convertValue(map, StockAPIBean.class); 99 | stocks.add(pojo); 100 | } 101 | } 102 | 103 | saveAllStocks(stocks); 104 | 105 | logger.info("size::" + stocks.size()); 106 | return stocks; 107 | 108 | } 109 | 110 | public void saveAllStocks(List stocks) 111 | { 112 | 113 | logger.info("Saving stock object to database"); 114 | for (StockAPIBean stock : stocks) { 115 | Stock temp = null; 116 | try { 117 | temp = this.homePageDAO.checkIfStockExists(stock.getSymbol()); 118 | } catch (Exception e) { 119 | temp = null; 120 | } 121 | if (temp == null) 122 | { 123 | //this.homePageDAO.saveStock(stock); 124 | } 125 | else { 126 | this.homePageDAO.updateStock(stock, temp.getId()); 127 | 128 | } 129 | 130 | } 131 | logger.info("Done updating stock table"); 132 | 133 | } 134 | 135 | public Map getTopCurrencies () 136 | { 137 | String result = this.restTemplate.getForObject(currencyUri, String.class); 138 | 139 | net.sf.json.JSONObject json = (net.sf.json.JSONObject) JSONSerializer.toJSON( result ); 140 | net.sf.json.JSONObject data = json.getJSONObject("data"); 141 | 142 | Map map = new HashMap(); 143 | Iterator iter = data.keys(); 144 | 145 | while(iter.hasNext()) 146 | { 147 | String key = (String)iter.next(); 148 | String value = data.getString(key); 149 | map.put(key,value); 150 | } 151 | 152 | Map resultMap = new HashMap(); 153 | 154 | String eur = map.get("EUR"); 155 | String jpy = map.get("JPY"); 156 | String inr = map.get("INR"); 157 | 158 | resultMap.put("Euro", eur); 159 | resultMap.put("Yen", jpy); 160 | resultMap.put("Rupee", inr); 161 | 162 | return resultMap; 163 | 164 | } 165 | 166 | 167 | 168 | } -------------------------------------------------------------------------------- /stocktrading/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /stocktrading/src/main/java/com/neu/edu/stocktrading/controller/StockTradeController.java: -------------------------------------------------------------------------------- 1 | package com.neu.edu.stocktrading.controller; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Random; 9 | 10 | import javax.servlet.http.HttpServletRequest; 11 | 12 | import com.mysql.cj.Session; 13 | import com.neu.edu.stocktrading.model.Trade; 14 | import com.neu.edu.stocktrading.model.Transaction; 15 | import com.neu.edu.stocktrading.model.User; 16 | import com.neu.edu.stocktrading.service.StockTradeService; 17 | import com.neu.edu.stocktrading.util.FileReaderUtil; 18 | import com.neu.edu.stocktrading.util.GeneratePdfUtil; 19 | import com.neu.edu.stocktrading.util.SessionManagementUtil; 20 | 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.core.io.InputStreamResource; 25 | import org.springframework.http.HttpHeaders; 26 | import org.springframework.http.MediaType; 27 | import org.springframework.http.ResponseEntity; 28 | import org.springframework.stereotype.Controller; 29 | import org.springframework.web.bind.annotation.GetMapping; 30 | import org.springframework.web.bind.annotation.PostMapping; 31 | import org.springframework.web.bind.annotation.RequestBody; 32 | import org.springframework.web.servlet.ModelAndView; 33 | 34 | @Controller 35 | public class StockTradeController { 36 | private static final Logger logger = LoggerFactory.getLogger(StockTradeController.class); 37 | 38 | @Autowired 39 | private StockTradeService stockTradeService; 40 | 41 | @Autowired 42 | private SessionManagementUtil sessionMgmtUtils; 43 | 44 | @PostMapping(value = "/check/account.htm" , consumes = MediaType.APPLICATION_JSON_VALUE) 45 | public ResponseEntity checkIfAccountAttached (HttpServletRequest request , @RequestBody HashMap stockSymbol) 46 | { 47 | logger.info("checkIfAccountAttached::"); 48 | String email = (String) request.getSession().getAttribute("user"); 49 | User user = this.stockTradeService.getProfileAttributes(email); 50 | 51 | boolean result = this.stockTradeService.checkIfAccountAttached(user); 52 | 53 | if (!result){ 54 | return ResponseEntity.badRequest().body("No user bank details found for user"); 55 | } 56 | else { 57 | Map res = new HashMap(); 58 | res.put("result", "Success"); 59 | return ResponseEntity.ok(res); 60 | } 61 | 62 | } 63 | 64 | @PostMapping(value = "/trade/watchlist.htm") 65 | public ModelAndView addToTrade(HttpServletRequest request) { 66 | logger.info("addToTrade::"); 67 | String email = (String) request.getSession().getAttribute("user"); 68 | User user = this.stockTradeService.getProfileAttributes(email); 69 | 70 | String[] stockSymbols = request.getParameterValues("checkedRows"); 71 | 72 | Map> stockList = this.stockTradeService.retrieveBuyList(user, stockSymbols); 73 | ModelAndView mv = new ModelAndView(); 74 | mv.addObject("stockList", stockList); 75 | mv.setViewName("user-trade"); 76 | 77 | request.getSession().setAttribute("stockList", stockList); 78 | 79 | return mv; 80 | } 81 | 82 | @PostMapping(value = "/trade/transaction.htm") 83 | public ModelAndView showTradeTransaction(HttpServletRequest request) { 84 | logger.info("showTradeTransaction::"); 85 | String email = (String) request.getSession().getAttribute("user"); 86 | User user = this.stockTradeService.getProfileAttributes(email); 87 | 88 | String[] quantities = request.getParameterValues("quantity"); 89 | 90 | String[] selling = request.getParameterValues("checkedRows"); 91 | 92 | Map> stockList = (Map>) request.getSession() 93 | .getAttribute("stockList"); 94 | 95 | List stockBuying = stockList.get("Buy"); 96 | 97 | ModelAndView mv = new ModelAndView(); 98 | mv.setViewName("user-transaction"); 99 | 100 | mv.addObject("transactionBuyId", new Random().nextInt(1000000)); 101 | mv.addObject("transactionSellId", new Random().nextInt(1000000)); 102 | 103 | Transaction t = this.stockTradeService.completeTransaction(user, quantities, stockBuying, selling); 104 | logger.info("showTradeTransaction::"+t.getId()); 105 | 106 | List currentBuyTrades = this.stockTradeService.getBuyTradesUsingCurrentTransaction (user , t); 107 | 108 | List currentSellTrades = new ArrayList(); 109 | currentSellTrades = this.stockTradeService.getSellTradesUsingCurrentTransaction (user , t); 110 | 111 | 112 | 113 | mv.addObject("tradeBuyList", currentBuyTrades); 114 | mv.addObject("tradeSellList", currentSellTrades); 115 | 116 | 117 | 118 | 119 | Double serviceCharge = Double.parseDouble( FileReaderUtil.readServiceChargeValue() ); 120 | Double buyTax = (serviceCharge/100 * this.stockTradeService.getTotalPrice(currentBuyTrades)); 121 | mv.addObject("serviceBuyTax", buyTax); 122 | 123 | Double sellTax = (serviceCharge/100 * this.stockTradeService.getTotalPrice(currentSellTrades)); 124 | mv.addObject("serviceSellTax", sellTax); 125 | 126 | mv.addObject("totalBuyPrice", this.stockTradeService.getTotalPrice(currentBuyTrades) + buyTax); 127 | mv.addObject("totalSellPrice", this.stockTradeService.getTotalPrice(currentSellTrades) + sellTax); 128 | 129 | return mv; 130 | } 131 | 132 | @GetMapping(value = "/statement.htm") 133 | public ModelAndView home(HttpServletRequest request) 134 | { 135 | if (!this.sessionMgmtUtils.doesSessionExist(request)) 136 | { 137 | logger.info("Please login to access this page"); 138 | ModelAndView mv = new ModelAndView("login-form"); 139 | mv.addObject("user", new User()); 140 | mv.addObject("errorMessage", "Please login to access this page"); 141 | return mv; 142 | 143 | } 144 | 145 | ModelAndView mv = new ModelAndView("account-statement"); 146 | String email = (String) request.getSession().getAttribute("user"); 147 | 148 | List temp = this.stockTradeService.getAllTransactions(email); 149 | 150 | List result = new ArrayList(); 151 | if (temp !=null) 152 | { 153 | for (Transaction t : temp) 154 | { 155 | if (Double.compare(t.getTotalPrice(), 0.0) !=0) 156 | { 157 | result.add(t); 158 | } 159 | } 160 | } 161 | 162 | mv.addObject("transactionList", result); 163 | return mv; 164 | } 165 | 166 | @GetMapping(value = "/transaction.pdf" , produces = MediaType.APPLICATION_PDF_VALUE) 167 | public ResponseEntity generatePdf(HttpServletRequest request) 168 | { 169 | String email = (String) request.getSession().getAttribute("user"); 170 | List temp = this.stockTradeService.getAllTransactions(email); 171 | List result = new ArrayList(); 172 | if (temp !=null) 173 | { 174 | for (Transaction t : temp) 175 | { 176 | if (Double.compare(t.getTotalPrice(), 0.0) !=0) 177 | { 178 | result.add(t); 179 | } 180 | } 181 | } 182 | 183 | ByteArrayInputStream bis = GeneratePdfUtil.transactionReport(result); 184 | 185 | HttpHeaders headers = new HttpHeaders(); 186 | headers.add("Content-Disposition", "inline; filename=transactionReport.pdf"); 187 | 188 | return ResponseEntity 189 | .ok() 190 | .headers(headers) 191 | .contentType(MediaType.APPLICATION_PDF) 192 | .body(new InputStreamResource(bis)); 193 | 194 | } 195 | 196 | } --------------------------------------------------------------------------------