Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .DS_Store
Binary file not shown.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Compiled class file
#/ Compiled class file
*.class
/target/

Expand Down
18 changes: 18 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,24 @@
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.1.RELEASE</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.1.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>



Expand Down
Binary file removed src/.DS_Store
Binary file not shown.
Binary file removed src/main/.DS_Store
Binary file not shown.
Binary file removed src/main/java/.DS_Store
Binary file not shown.
Binary file removed src/main/java/com/.DS_Store
Binary file not shown.
Binary file removed src/main/java/com/packt/.DS_Store
Binary file not shown.
17 changes: 17 additions & 0 deletions src/main/java/com/packt/webstore/config/LoginController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.packt.webstore.config;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* ログインコントローラー
* @author hirooka
*/
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(){
return "login";
}
}
61 changes: 61 additions & 0 deletions src/main/java/com/packt/webstore/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.packt.webstore.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


/**
* ログインの設定
* ログインされていない場合これらの設定に従って動作する。
* @author hirooka
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//ユーザーの登録
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("john").password("pa55word").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("root123").roles("USER", "ADMIN");
}


/**
* 認証のさいのいろいろな設定
*
* @param httpSecurity
* @throws Exception
*/
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {

//認証がされていないときに呼び出される。
//ここで呼び出すページはコントローラーの中で呼び出されるページと同じ
httpSecurity.formLogin().loginPage("/login")
.usernameParameter("userId")
.passwordParameter("password");

httpSecurity.formLogin().defaultSuccessUrl("/market/products/add")
.failureUrl("/login?error");

//ログアウトが成功した際のページ呼び出し
httpSecurity.logout().logoutSuccessUrl("/login?logout");

//許可されていないページへ入った際に呼び出される。
httpSecurity.exceptionHandling().accessDeniedPage("/login?accessDenied");

//ロールによってredirectするページを変更する。
httpSecurity.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/**/add").access("hasRole('ADMIN')")
.antMatchers("/**/market/**").access("hasRole('USER')");

//
httpSecurity.csrf().disable();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.packt.webstore.config;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

/**
* Spring起動の際にSpring側にセキュリティログインの設定があることを知らせるためのクラス
*
* @author hirooka
*
*/
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
package com.packt.webstore.config;


import com.packt.webstore.intercepter.ProcessingTimeLogInterceptor;
import com.packt.webstore.intercepter.PromoCodeInterceptor;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.util.UrlPathHelper;

import java.util.ResourceBundle;

@Configuration
@EnableWebMvc
@ComponentScan("com.packt.webstore")
Expand Down Expand Up @@ -47,6 +48,16 @@ public MessageSource messageSource(){
return resource;
}

@Bean
public HandlerInterceptor promoCodeInterceptor(){
PromoCodeInterceptor promoCodeInterceptor = new PromoCodeInterceptor();
promoCodeInterceptor.setPromoCode("OFF3R");
promoCodeInterceptor.setOfferRedirect("/market/products");
promoCodeInterceptor.setErrorRedirect("invalidPromoCode");
return promoCodeInterceptor;
}


/**
* HandlerMappingの設定
*
Expand All @@ -58,4 +69,15 @@ public void configurePathMatch(PathMatchConfigurer configurer) {
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}

/**
* インターセプターの設定
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ProcessingTimeLogInterceptor());
registry.addInterceptor(promoCodeInterceptor())
.addPathPatterns("/**/market/products/specialOffer");
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.packt.webstore.controller;

import com.packt.webstore.domain.Product;
import com.packt.webstore.domain.repository.ProductRepository;
import com.packt.webstore.exeption.NoProductsFoundUnderCategoryException;
import com.packt.webstore.exeption.ProductNotFoundException;
import com.packt.webstore.service.ProductService;
Expand All @@ -16,8 +15,6 @@
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RequestWrapper;
import java.util.List;
import java.util.Map;

Expand Down Expand Up @@ -86,7 +83,12 @@ public String processAddNewProductForm(@ModelAttribute("newProduct") Product new
return "redirect:/market/products";
}

@RequestMapping("/products/invalidPromoCode")
public String invalidPromoCode(){
return "invalidPromoCode";
}

@InitBinder
public void initialiseBinder(WebDataBinder binder) {
binder.setAllowedFields("productId",
"name",
Expand All @@ -108,6 +110,4 @@ public ModelAndView handleError(HttpServletRequest request,
mav.setViewName("productNotFound");
return mav;
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.packt.webstore.intercepter;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* インターセプターの追加
* レスポンス速度を測る。
* @author hirooka
*/
public class ProcessingTimeLogInterceptor implements HandlerInterceptor {

private static final Logger LOGGER = Logger.getLogger(ProcessingTimeLogInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object o) throws Exception {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object o, ModelAndView modelAndView) throws Exception {
String queryString = request.getQueryString() == null ? "" : "?" + request.getQueryString();
String path = request.getRequestURL() + queryString;
long startTime = (Long) request.getAttribute("startTime");
long endTime = System.currentTimeMillis();
LOGGER.info(String.format("%s millisecond taken to process the request %s", (endTime - startTime), path));

}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object o, Exception e) throws Exception {
//nop
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.packt.webstore.intercepter;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PromoCodeInterceptor extends HandlerInterceptorAdapter {
private String promoCode;
private String errorRedirect;
private String offerRedirect;

public PromoCodeInterceptor() {
super();
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
String givenPromoCode = request.getParameter("promo");
if (promoCode.equals(givenPromoCode)) {
response.sendRedirect(request.getContextPath() + "/" + offerRedirect);
} else {
response.sendRedirect(errorRedirect);
}
return false;
}

public void setPromoCode(String promoCode) {
this.promoCode = promoCode;
}

public void setErrorRedirect(String errorRedirect) {
this.errorRedirect = errorRedirect;
}

public void setOfferRedirect(String offerRedirect) {
this.offerRedirect = offerRedirect;
}
}
14 changes: 14 additions & 0 deletions src/main/resources/log4j.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Root logger option
log4j.rootLogger=INFO, file, stdout
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/Users/hirookayuukana/Desktop/log/performance.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n
7 changes: 7 additions & 0 deletions src/main/webapp/WEB-INF/views/addProduct.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@
<title>Products</title>
</head>
<body>
<section>
<div class="pull-right" style="padding-right:50px">
<a href="?language=en" >English</a>|<a href="?language=nl" >Dutch</a>
<a href="<c:url value="/logout" />">Logout</a>
</div>
</section>
<section>
<div class="jumbotron">
<div class="container">
Expand Down Expand Up @@ -100,6 +106,7 @@
<div class="col-lg-offset-2 col-lg-10">
<input type="submit" id="btnAdd" class="btnbtn-primary" value="Add"/>
</div>

</div>
</fieldset>
</form:form>
29 changes: 29 additions & 0 deletions src/main/webapp/WEB-INF/views/invalidPromoCode.jsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<title>Invalid promo code</title>
</head>
<body>
<section>
<div class="jumbotron">
<div class="container">
<h1 class="alert alert-danger">Invalid Promo Code</h1>
</div>
</div>
</section>
<section>
<div class="container">
<p>
<a href="<spring:url value="/market/products" />"
class="btn btn-primary">
<span class="glyphicon-hand-left glyphicon">
</span> products
</a>
</p></div>
</section>
</body>
</html>
Loading