Skip to content
GitLab
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
라이앤캐처스 크루공간
허창호
연습용
Commits
969fb9e8
Commit
969fb9e8
authored
Feb 06, 2022
by
madvirus
Browse files
Initial Commit
parents
Changes
187
Hide whitespace changes
Inline
Side-by-side
src/main/java/com/myshop/order/query/application/ListRequest.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.application
;
public
class
ListRequest
{
private
int
page
;
private
int
size
;
public
ListRequest
(
int
page
,
int
size
)
{
this
.
page
=
page
;
this
.
size
=
size
;
}
public
int
getPage
()
{
return
page
;
}
public
int
getSize
()
{
return
size
;
}
}
src/main/java/com/myshop/order/query/application/OrderDetail.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.application
;
import
com.myshop.order.command.domain.Order
;
import
com.myshop.order.command.domain.OrderState
;
import
com.myshop.order.command.domain.Orderer
;
import
com.myshop.order.command.domain.ShippingInfo
;
import
java.util.List
;
public
class
OrderDetail
{
private
final
String
number
;
private
long
version
;
private
final
Orderer
orderer
;
private
final
ShippingInfo
shippingInfo
;
private
final
OrderState
state
;
private
final
int
totalAmounts
;
private
List
<
OrderLineDetail
>
orderLines
;
private
final
boolean
notYetShipped
;
public
OrderDetail
(
Order
order
,
List
<
OrderLineDetail
>
orderLines
)
{
this
.
orderLines
=
orderLines
;
number
=
order
.
getNumber
().
getNumber
();
version
=
order
.
getVersion
();
orderer
=
order
.
getOrderer
();
shippingInfo
=
order
.
getShippingInfo
();
state
=
order
.
getState
();
notYetShipped
=
order
.
isNotYetShipped
();
totalAmounts
=
order
.
getTotalAmounts
().
getValue
();
}
public
String
getNumber
()
{
return
number
;
}
public
long
getVersion
()
{
return
version
;
}
public
Orderer
getOrderer
()
{
return
orderer
;
}
public
ShippingInfo
getShippingInfo
()
{
return
shippingInfo
;
}
public
OrderState
getState
()
{
return
state
;
}
public
int
getTotalAmounts
()
{
return
totalAmounts
;
}
public
List
<
OrderLineDetail
>
getOrderLines
()
{
return
orderLines
;
}
public
boolean
isNotYetShipped
()
{
return
notYetShipped
;
}
}
src/main/java/com/myshop/order/query/application/OrderDetailService.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.application
;
import
com.myshop.catalog.query.product.ProductData
;
import
com.myshop.catalog.query.product.ProductQueryService
;
import
com.myshop.order.command.domain.Order
;
import
com.myshop.order.command.domain.OrderNo
;
import
com.myshop.order.command.domain.OrderRepository
;
import
org.springframework.stereotype.Component
;
import
org.springframework.transaction.annotation.Transactional
;
import
java.util.List
;
import
java.util.Optional
;
import
java.util.stream.Collectors
;
@Component
public
class
OrderDetailService
{
private
OrderRepository
orderRepository
;
private
ProductQueryService
productQueryService
;
public
OrderDetailService
(
OrderRepository
orderRepository
,
ProductQueryService
productQueryService
)
{
this
.
orderRepository
=
orderRepository
;
this
.
productQueryService
=
productQueryService
;
}
@Transactional
public
Optional
<
OrderDetail
>
getOrderDetail
(
String
orderNumber
)
{
Optional
<
Order
>
orderOpt
=
orderRepository
.
findById
(
new
OrderNo
(
orderNumber
));
return
orderOpt
.
map
(
order
->
{
List
<
OrderLineDetail
>
orderLines
=
order
.
getOrderLines
().
stream
()
.
map
(
orderLine
->
{
Optional
<
ProductData
>
productOpt
=
productQueryService
.
getProduct
(
orderLine
.
getProductId
().
getId
());
return
new
OrderLineDetail
(
orderLine
,
productOpt
.
orElse
(
null
));
}).
collect
(
Collectors
.
toList
());
return
new
OrderDetail
(
order
,
orderLines
);
});
}
}
src/main/java/com/myshop/order/query/application/OrderLineDetail.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.application
;
import
com.myshop.catalog.query.product.ProductData
;
import
com.myshop.order.command.domain.OrderLine
;
public
class
OrderLineDetail
{
private
final
String
productId
;
private
final
int
price
;
private
final
int
quantity
;
private
final
int
amounts
;
private
final
String
productName
;
private
final
String
productImagePath
;
public
OrderLineDetail
(
OrderLine
orderLine
,
ProductData
product
)
{
productId
=
orderLine
.
getProductId
().
getId
();
price
=
orderLine
.
getPrice
().
getValue
();
quantity
=
orderLine
.
getQuantity
();
amounts
=
orderLine
.
getAmounts
().
getValue
();
productName
=
product
.
getName
();
productImagePath
=
product
.
getFirstIamgeThumbnailPath
();
}
public
String
getProductId
()
{
return
productId
;
}
public
int
getPrice
()
{
return
price
;
}
public
int
getQuantity
()
{
return
quantity
;
}
public
int
getAmounts
()
{
return
amounts
;
}
public
String
getProductName
()
{
return
productName
;
}
public
String
getProductImagePath
()
{
return
productImagePath
;
}
}
src/main/java/com/myshop/order/query/application/OrderViewListService.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.application
;
import
com.myshop.order.query.dao.OrderSummaryDao
;
import
com.myshop.order.query.dto.OrderSummary
;
import
org.springframework.data.domain.Page
;
import
org.springframework.data.domain.PageRequest
;
import
org.springframework.data.domain.Sort
;
import
org.springframework.stereotype.Component
;
import
org.springframework.transaction.annotation.Transactional
;
@Component
public
class
OrderViewListService
{
private
OrderSummaryDao
orderSummaryDao
;
public
OrderViewListService
(
OrderSummaryDao
orderSummaryDao
)
{
this
.
orderSummaryDao
=
orderSummaryDao
;
}
@Transactional
public
Page
<
OrderSummary
>
getList
(
ListRequest
listReq
)
{
PageRequest
pageable
=
PageRequest
.
of
(
listReq
.
getPage
(),
listReq
.
getSize
(),
Sort
.
by
(
Sort
.
Direction
.
DESC
,
"number"
));
return
orderSummaryDao
.
findAll
(
pageable
);
}
}
src/main/java/com/myshop/order/query/dao/OrderSummaryDao.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.dao
;
import
com.myshop.order.query.dto.OrderSummary
;
import
com.myshop.order.query.dto.OrderView
;
import
org.springframework.data.domain.Page
;
import
org.springframework.data.domain.Pageable
;
import
org.springframework.data.domain.Sort
;
import
org.springframework.data.jpa.domain.Specification
;
import
org.springframework.data.jpa.repository.Query
;
import
org.springframework.data.repository.Repository
;
import
java.util.List
;
public
interface
OrderSummaryDao
extends
Repository
<
OrderSummary
,
String
>
{
List
<
OrderSummary
>
findByOrdererId
(
String
ordererId
);
List
<
OrderSummary
>
findByOrdererId
(
String
ordererId
,
Sort
sort
);
List
<
OrderSummary
>
findByOrdererId
(
String
ordererId
,
Pageable
pageable
);
List
<
OrderSummary
>
findByOrdererIdOrderByNumberDesc
(
String
ordererId
);
List
<
OrderSummary
>
findAll
(
Specification
<
OrderSummary
>
spec
);
List
<
OrderSummary
>
findAll
(
Specification
<
OrderSummary
>
spec
,
Sort
sort
);
List
<
OrderSummary
>
findAll
(
Specification
<
OrderSummary
>
spec
,
Pageable
pageable
);
Page
<
OrderSummary
>
findAll
(
Pageable
pageable
);
@Query
(
"""
select new com.myshop.order.query.dto.OrderView(
o.number, o.state, m.name, m.id, p.name
)
from Order o join o.orderLines ol, Member m, Product p
where o.orderer.memberId.id = :ordererId
and o.orderer.memberId.id = m.id
and index(ol) = 0
and ol.productId.id = p.id
order by o.number.number desc
"""
)
List
<
OrderView
>
findOrderView
(
String
ordererId
);
}
src/main/java/com/myshop/order/query/dao/OrderSummarySpecs.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.dao
;
import
com.myshop.order.query.dto.OrderSummary
;
import
com.myshop.order.query.dto.OrderSummary_
;
import
org.springframework.data.jpa.domain.Specification
;
import
javax.persistence.criteria.CriteriaBuilder
;
import
javax.persistence.criteria.CriteriaQuery
;
import
javax.persistence.criteria.Order
;
import
javax.persistence.criteria.Root
;
import
java.time.LocalDateTime
;
public
class
OrderSummarySpecs
{
public
static
Specification
<
OrderSummary
>
ordererId
(
String
ordererId
)
{
return
(
Root
<
OrderSummary
>
root
,
CriteriaQuery
<?>
query
,
CriteriaBuilder
cb
)
->
cb
.
equal
(
root
.<
String
>
get
(
"ordererId"
),
ordererId
);
}
public
static
Specification
<
OrderSummary
>
orderDateBetween
(
LocalDateTime
from
,
LocalDateTime
to
)
{
return
(
Root
<
OrderSummary
>
root
,
CriteriaQuery
<?>
query
,
CriteriaBuilder
cb
)
->
cb
.
between
(
root
.
get
(
OrderSummary_
.
orderDate
),
from
,
to
);
}
}
src/main/java/com/myshop/order/query/dao/OrdererIdSpec.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.dao
;
import
com.myshop.order.query.dto.OrderSummary
;
import
com.myshop.order.query.dto.OrderSummary_
;
import
org.springframework.data.jpa.domain.Specification
;
import
javax.persistence.criteria.CriteriaBuilder
;
import
javax.persistence.criteria.CriteriaQuery
;
import
javax.persistence.criteria.Predicate
;
import
javax.persistence.criteria.Root
;
public
class
OrdererIdSpec
implements
Specification
<
OrderSummary
>
{
private
String
ordererId
;
public
OrdererIdSpec
(
String
ordererId
)
{
this
.
ordererId
=
ordererId
;
}
@Override
public
Predicate
toPredicate
(
Root
<
OrderSummary
>
root
,
CriteriaQuery
<?>
query
,
CriteriaBuilder
cb
)
{
return
cb
.
equal
(
root
.
get
(
OrderSummary_
.
ordererId
),
ordererId
);
}
}
src/main/java/com/myshop/order/query/dto/OrderSummary.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.dto
;
import
org.hibernate.annotations.Immutable
;
import
org.hibernate.annotations.Subselect
;
import
org.hibernate.annotations.Synchronize
;
import
javax.persistence.Column
;
import
javax.persistence.Entity
;
import
javax.persistence.Id
;
import
java.time.LocalDateTime
;
@Entity
@Immutable
@Subselect
(
"""
select o.order_number as number,
o.version,
o.orderer_id,
o.orderer_name,
o.total_amounts,
o.receiver_name,
o.state,
o.order_date,
p.product_id,
p.name as product_name
from purchase_order o inner join order_line ol
on o.order_number = ol.order_number
cross join product p
where
ol.line_idx = 0
and ol.product_id = p.product_id"""
)
@Synchronize
({
"purchase_order"
,
"order_line"
,
"product"
})
public
class
OrderSummary
{
@Id
private
String
number
;
private
long
version
;
@Column
(
name
=
"orderer_id"
)
private
String
ordererId
;
@Column
(
name
=
"orderer_name"
)
private
String
ordererName
;
@Column
(
name
=
"total_amounts"
)
private
int
totalAmounts
;
@Column
(
name
=
"receiver_name"
)
private
String
receiverName
;
private
String
state
;
@Column
(
name
=
"order_date"
)
private
LocalDateTime
orderDate
;
@Column
(
name
=
"product_id"
)
private
String
productId
;
@Column
(
name
=
"product_name"
)
private
String
productName
;
protected
OrderSummary
()
{
}
public
String
getNumber
()
{
return
number
;
}
public
long
getVersion
()
{
return
version
;
}
public
String
getOrdererId
()
{
return
ordererId
;
}
public
String
getOrdererName
()
{
return
ordererName
;
}
public
int
getTotalAmounts
()
{
return
totalAmounts
;
}
public
String
getReceiverName
()
{
return
receiverName
;
}
public
String
getState
()
{
return
state
;
}
public
LocalDateTime
getOrderDate
()
{
return
orderDate
;
}
public
String
getProductId
()
{
return
productId
;
}
public
String
getProductName
()
{
return
productName
;
}
}
src/main/java/com/myshop/order/query/dto/OrderSummary_.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.dto
;
import
javax.persistence.metamodel.SingularAttribute
;
import
javax.persistence.metamodel.StaticMetamodel
;
import
java.time.LocalDateTime
;
@StaticMetamodel
(
OrderSummary
.
class
)
public
class
OrderSummary_
{
public
static
volatile
SingularAttribute
<
OrderSummary
,
String
>
number
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
Long
>
version
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
String
>
ordererId
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
String
>
ordererName
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
Integer
>
totalAmounts
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
String
>
receiverName
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
String
>
state
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
LocalDateTime
>
orderDate
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
String
>
productId
;
public
static
volatile
SingularAttribute
<
OrderSummary
,
String
>
productName
;
}
src/main/java/com/myshop/order/query/dto/OrderView.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.query.dto
;
import
com.myshop.member.command.domain.MemberId
;
import
com.myshop.order.command.domain.OrderNo
;
import
com.myshop.order.command.domain.OrderState
;
public
class
OrderView
{
private
final
String
number
;
private
final
OrderState
state
;
private
final
String
memberName
;
private
final
String
memberId
;
private
final
String
productName
;
public
OrderView
(
OrderNo
number
,
OrderState
state
,
String
memberName
,
MemberId
memberId
,
String
productName
)
{
this
.
number
=
number
.
getNumber
();
this
.
state
=
state
;
this
.
memberName
=
memberName
;
this
.
memberId
=
memberId
.
getId
();
this
.
productName
=
productName
;
}
public
String
getNumber
()
{
return
number
;
}
public
OrderState
getState
()
{
return
state
;
}
public
String
getMemberName
()
{
return
memberName
;
}
public
String
getMemberId
()
{
return
memberId
;
}
public
String
getProductName
()
{
return
productName
;
}
}
src/main/java/com/myshop/order/ui/CancelOrderController.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.ui
;
import
com.myshop.order.command.application.CancelOrderService
;
import
com.myshop.order.command.domain.Canceller
;
import
com.myshop.order.command.domain.OrderNo
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.userdetails.User
;
import
org.springframework.stereotype.Controller
;
import
org.springframework.ui.ModelMap
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.RequestMapping
;
@Controller
public
class
CancelOrderController
{
private
CancelOrderService
cancelOrderService
;
public
CancelOrderController
(
CancelOrderService
cancelOrderService
)
{
this
.
cancelOrderService
=
cancelOrderService
;
}
@RequestMapping
(
"/my/orders/{orderNo}/cancel"
)
public
String
orderDetail
(
@PathVariable
(
"orderNo"
)
String
orderNo
,
ModelMap
modelMap
)
{
User
user
=
(
User
)
SecurityContextHolder
.
getContext
().
getAuthentication
().
getPrincipal
();
cancelOrderService
.
cancel
(
new
OrderNo
(
orderNo
),
new
Canceller
(
user
.
getUsername
()));
return
"my/orderCanceled"
;
}
}
src/main/java/com/myshop/order/ui/MyOrderController.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.ui
;
import
com.myshop.order.query.application.OrderDetail
;
import
com.myshop.order.query.application.OrderDetailService
;
import
com.myshop.order.query.dao.OrderSummaryDao
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.userdetails.User
;
import
org.springframework.stereotype.Controller
;
import
org.springframework.ui.ModelMap
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
java.util.Optional
;
@Controller
public
class
MyOrderController
{
private
OrderDetailService
orderDetailService
;
private
OrderSummaryDao
orderSummaryDao
;
public
MyOrderController
(
OrderDetailService
orderDetailService
,
OrderSummaryDao
orderSummaryDao
)
{
this
.
orderDetailService
=
orderDetailService
;
this
.
orderSummaryDao
=
orderSummaryDao
;
}
@RequestMapping
(
"/my/orders"
)
public
String
orders
(
ModelMap
modelMap
)
{
User
user
=
(
User
)
SecurityContextHolder
.
getContext
().
getAuthentication
().
getPrincipal
();
modelMap
.
addAttribute
(
"orders"
,
orderSummaryDao
.
findByOrdererId
(
user
.
getUsername
()));
return
"my/orders"
;
}
@RequestMapping
(
"/my/orders/{orderNo}"
)
public
String
orderDetail
(
@PathVariable
(
"orderNo"
)
String
orderNo
,
ModelMap
modelMap
)
{
User
user
=
(
User
)
SecurityContextHolder
.
getContext
().
getAuthentication
().
getPrincipal
();
Optional
<
OrderDetail
>
orderDetail
=
orderDetailService
.
getOrderDetail
(
orderNo
);
if
(
orderDetail
.
isPresent
())
{
if
(
orderDetail
.
get
().
getOrderer
().
getMemberId
().
getId
().
equals
(
user
.
getUsername
()))
{
modelMap
.
addAttribute
(
"order"
,
orderDetail
.
get
());
return
"my/orderDetail"
;
}
else
{
return
"my/notYourOrder"
;
}
}
else
{
return
"my/noOrder"
;
}
}
}
src/main/java/com/myshop/order/ui/OrderController.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.ui
;
import
com.myshop.catalog.query.product.ProductData
;
import
com.myshop.catalog.query.product.ProductQueryService
;
import
com.myshop.common.ValidationErrorException
;
import
com.myshop.member.command.domain.MemberId
;
import
com.myshop.order.command.application.NoOrderProductException
;
import
com.myshop.order.command.application.OrderProduct
;
import
com.myshop.order.command.application.OrderRequest
;
import
com.myshop.order.command.application.PlaceOrderService
;
import
com.myshop.order.command.domain.OrderNo
;
import
com.myshop.order.command.domain.OrdererService
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.userdetails.User
;
import
org.springframework.stereotype.Controller
;
import
org.springframework.ui.ModelMap
;
import
org.springframework.validation.BindingResult
;
import
org.springframework.web.bind.WebDataBinder
;
import
org.springframework.web.bind.annotation.ExceptionHandler
;
import
org.springframework.web.bind.annotation.InitBinder
;
import
org.springframework.web.bind.annotation.ModelAttribute
;
import
org.springframework.web.bind.annotation.PostMapping
;
import
java.util.ArrayList
;
import
java.util.List
;
import
java.util.Optional
;
@Controller
public
class
OrderController
{
private
ProductQueryService
productQueryService
;
private
PlaceOrderService
placeOrderService
;
private
OrdererService
ordererService
;
public
OrderController
(
ProductQueryService
productQueryService
,
PlaceOrderService
placeOrderService
,
OrdererService
ordererService
)
{
this
.
productQueryService
=
productQueryService
;
this
.
placeOrderService
=
placeOrderService
;
this
.
ordererService
=
ordererService
;
}
@PostMapping
(
"/orders/orderConfirm"
)
public
String
orderConfirm
(
@ModelAttribute
(
"orderReq"
)
OrderRequest
orderRequest
,
ModelMap
modelMap
)
{
User
user
=
(
User
)
SecurityContextHolder
.
getContext
().
getAuthentication
().
getPrincipal
();
orderRequest
.
setOrdererMemberId
(
MemberId
.
of
(
user
.
getUsername
()));
populateProductsAndTotalAmountsModel
(
orderRequest
,
modelMap
);
return
"order/confirm"
;
}
private
void
populateProductsAndTotalAmountsModel
(
OrderRequest
orderRequest
,
ModelMap
modelMap
)
{
List
<
ProductData
>
products
=
getProducts
(
orderRequest
.
getOrderProducts
());
modelMap
.
addAttribute
(
"products"
,
products
);
int
totalAmounts
=
0
;
for
(
int
i
=
0
;
i
<
orderRequest
.
getOrderProducts
().
size
()
;
i
++)
{
OrderProduct
op
=
orderRequest
.
getOrderProducts
().
get
(
i
);
ProductData
prod
=
products
.
get
(
i
);
totalAmounts
+=
op
.
getQuantity
()
*
prod
.
getPrice
().
getValue
();
}
modelMap
.
addAttribute
(
"totalAmounts"
,
totalAmounts
);
}
private
List
<
ProductData
>
getProducts
(
List
<
OrderProduct
>
orderProducts
)
{
List
<
ProductData
>
results
=
new
ArrayList
<>();
for
(
OrderProduct
op
:
orderProducts
)
{
Optional
<
ProductData
>
productOpt
=
productQueryService
.
getProduct
(
op
.
getProductId
());
ProductData
product
=
productOpt
.
orElseThrow
(()
->
new
NoOrderProductException
(
op
.
getProductId
()));
results
.
add
(
product
);
}
return
results
;
}
@PostMapping
(
"/orders/order"
)
public
String
order
(
@ModelAttribute
(
"orderReq"
)
OrderRequest
orderRequest
,
BindingResult
bindingResult
,
ModelMap
modelMap
)
{
User
user
=
(
User
)
SecurityContextHolder
.
getContext
().
getAuthentication
().
getPrincipal
();
orderRequest
.
setOrdererMemberId
(
MemberId
.
of
(
user
.
getUsername
()));
try
{
OrderNo
orderNo
=
placeOrderService
.
placeOrder
(
orderRequest
);
modelMap
.
addAttribute
(
"orderNo"
,
orderNo
.
getNumber
());
return
"order/orderComplete"
;
}
catch
(
ValidationErrorException
e
)
{
e
.
getErrors
().
forEach
(
err
->
{
if
(
err
.
hasName
())
{
bindingResult
.
rejectValue
(
err
.
getName
(),
err
.
getCode
());
}
else
{
bindingResult
.
reject
(
err
.
getCode
());
}
});
populateProductsAndTotalAmountsModel
(
orderRequest
,
modelMap
);
return
"order/confirm"
;
}
}
@ExceptionHandler
(
NoOrderProductException
.
class
)
public
String
handleNoOrderProduct
()
{
return
"order/noProduct"
;
}
@InitBinder
public
void
init
(
WebDataBinder
binder
)
{
binder
.
initDirectFieldAccess
();
}
}
src/main/java/com/myshop/order/ui/OrderRequestValidator4Spring.java
0 → 100644
View file @
969fb9e8
package
com.myshop.order.ui
;
import
com.myshop.order.command.application.OrderProduct
;
import
com.myshop.order.command.application.OrderRequest
;
import
org.springframework.validation.Errors
;
import
org.springframework.validation.ValidationUtils
;
import
org.springframework.validation.Validator
;
public
class
OrderRequestValidator4Spring
implements
Validator
{
@Override
public
boolean
supports
(
Class
<?>
aClass
)
{
return
OrderRequest
.
class
.
isAssignableFrom
(
aClass
);
}
@Override
public
void
validate
(
Object
o
,
Errors
errors
)
{
OrderRequest
orderReq
=
(
OrderRequest
)
o
;
if
(
orderReq
.
getOrderProducts
()
==
null
||
orderReq
.
getOrderProducts
().
isEmpty
())
{
ValidationUtils
.
rejectIfEmptyOrWhitespace
(
errors
,
"orderProducts"
,
"required"
);
}
else
{
for
(
int
i
=
0
;
i
<
orderReq
.
getOrderProducts
().
size
();
i
++)
{
OrderProduct
orderProduct
=
orderReq
.
getOrderProducts
().
get
(
i
);
if
(
orderProduct
.
getProductId
()
==
null
||
orderProduct
.
getProductId
().
trim
().
isEmpty
())
{
errors
.
rejectValue
(
"orderProducts["
+
i
+
"].productId"
,
"required"
);
}
if
(
orderProduct
.
getQuantity
()
<=
0
)
{
errors
.
rejectValue
(
"orderProducts["
+
i
+
"].quantity"
,
"nonPositive"
);
}
}
}
ValidationUtils
.
rejectIfEmptyOrWhitespace
(
errors
,
"shippingInfo.receiver.name"
,
"required"
);
ValidationUtils
.
rejectIfEmptyOrWhitespace
(
errors
,
"shippingInfo.receiver.phone"
,
"required"
);
ValidationUtils
.
rejectIfEmptyOrWhitespace
(
errors
,
"shippingInfo.address.zipCode"
,
"required"
);
ValidationUtils
.
rejectIfEmptyOrWhitespace
(
errors
,
"shippingInfo.address.address1"
,
"required"
);
ValidationUtils
.
rejectIfEmptyOrWhitespace
(
errors
,
"shippingInfo.address.address2"
,
"required"
);
}
}
src/main/java/com/myshop/springconfig/security/CookieSecurityContextRepository.java
0 → 100644
View file @
969fb9e8
package
com.myshop.springconfig.security
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.core.context.SecurityContext
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.core.userdetails.UserDetailsService
;
import
org.springframework.security.core.userdetails.UsernameNotFoundException
;
import
org.springframework.security.web.context.HttpRequestResponseHolder
;
import
org.springframework.security.web.context.SecurityContextRepository
;
import
javax.servlet.http.Cookie
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
java.net.URLDecoder
;
import
static
com
.
myshop
.
springconfig
.
security
.
WebSecurityConfig
.
AUTHCOOKIENAME
;
public
class
CookieSecurityContextRepository
implements
SecurityContextRepository
{
private
Logger
logger
=
LoggerFactory
.
getLogger
(
getClass
());
private
UserDetailsService
userDetailsService
;
public
CookieSecurityContextRepository
(
UserDetailsService
userDetailsService
)
{
this
.
userDetailsService
=
userDetailsService
;
}
@Override
public
SecurityContext
loadContext
(
HttpRequestResponseHolder
requestResponseHolder
)
{
SecurityContext
sc
=
SecurityContextHolder
.
createEmptyContext
();
Cookie
cookie
=
findAuthCookie
(
requestResponseHolder
.
getRequest
());
if
(
cookie
!=
null
)
{
String
id
=
getUserId
(
cookie
);
if
(
id
!=
null
)
{
populateAuthentication
(
sc
,
id
);
}
}
return
sc
;
}
private
void
populateAuthentication
(
SecurityContext
sc
,
String
id
)
{
try
{
UserDetails
userDetails
=
userDetailsService
.
loadUserByUsername
(
id
);
sc
.
setAuthentication
(
new
UsernamePasswordAuthenticationToken
(
userDetails
,
""
,
userDetails
.
getAuthorities
()));
}
catch
(
UsernameNotFoundException
e
)
{
logger
.
debug
(
"user name not found: "
+
id
,
e
);
}
}
private
String
getUserId
(
Cookie
cookie
)
{
try
{
return
URLDecoder
.
decode
(
cookie
.
getValue
(),
"utf-8"
);
}
catch
(
Exception
ex
)
{
return
null
;
}
}
private
Cookie
findAuthCookie
(
HttpServletRequest
request
)
{
Cookie
[]
cookies
=
request
.
getCookies
();
if
(
cookies
==
null
||
cookies
.
length
==
0
)
return
null
;
for
(
Cookie
c
:
cookies
)
{
if
(
c
.
getName
().
equals
(
AUTHCOOKIENAME
))
{
return
c
;
}
}
return
null
;
}
@Override
public
void
saveContext
(
SecurityContext
context
,
HttpServletRequest
request
,
HttpServletResponse
response
)
{
}
@Override
public
boolean
containsContext
(
HttpServletRequest
request
)
{
return
false
;
}
}
src/main/java/com/myshop/springconfig/security/CustomAuthSuccessHandler.java
0 → 100644
View file @
969fb9e8
package
com.myshop.springconfig.security
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.web.authentication.AuthenticationSuccessHandler
;
import
javax.servlet.ServletException
;
import
javax.servlet.http.Cookie
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.IOException
;
import
java.io.UnsupportedEncodingException
;
import
java.net.URLEncoder
;
import
static
com
.
myshop
.
springconfig
.
security
.
WebSecurityConfig
.
AUTHCOOKIENAME
;
public
class
CustomAuthSuccessHandler
implements
AuthenticationSuccessHandler
{
@Override
public
void
onAuthenticationSuccess
(
HttpServletRequest
request
,
HttpServletResponse
response
,
Authentication
authentication
)
throws
IOException
,
ServletException
{
UserDetails
user
=
(
UserDetails
)
authentication
.
getPrincipal
();
try
{
Cookie
authCookie
=
new
Cookie
(
AUTHCOOKIENAME
,
URLEncoder
.
encode
(
encryptId
(
user
),
"UTF-8"
));
authCookie
.
setPath
(
"/"
);
response
.
addCookie
(
authCookie
);
}
catch
(
UnsupportedEncodingException
ex
)
{
throw
new
RuntimeException
(
ex
);
}
response
.
sendRedirect
(
"/home"
);
}
private
String
encryptId
(
UserDetails
user
)
{
return
user
.
getUsername
();
}
}
src/main/java/com/myshop/springconfig/security/WebSecurityConfig.java
0 → 100644
View file @
969fb9e8
package
com.myshop.springconfig.security
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
;
import
org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.config.annotation.web.builders.WebSecurity
;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
;
import
org.springframework.security.core.userdetails.UserDetailsService
;
import
org.springframework.security.crypto.password.NoOpPasswordEncoder
;
import
org.springframework.security.web.context.SecurityContextRepository
;
import
org.springframework.security.web.savedrequest.NullRequestCache
;
import
javax.sql.DataSource
;
@EnableWebSecurity
@EnableGlobalMethodSecurity
(
prePostEnabled
=
true
)
@Configuration
public
class
WebSecurityConfig
extends
WebSecurityConfigurerAdapter
{
public
static
final
String
AUTHCOOKIENAME
=
"AUTH"
;
@Autowired
private
DataSource
dataSource
;
@Override
protected
void
configure
(
AuthenticationManagerBuilder
auth
)
throws
Exception
{
auth
.
jdbcAuthentication
()
.
dataSource
(
dataSource
)
.
usersByUsernameQuery
(
"select member_id, password, 'true' from member where member_id = ?"
)
.
authoritiesByUsernameQuery
(
"select member_id, authority from member_authorities where member_id = ?"
)
.
passwordEncoder
(
NoOpPasswordEncoder
.
getInstance
())
;
}
@Override
public
void
configure
(
WebSecurity
web
)
throws
Exception
{
web
.
ignoring
().
antMatchers
(
"/vendor/**"
,
"/api/**"
,
"/images/**"
,
"/favicon.ico"
);
}
@Override
protected
void
configure
(
HttpSecurity
http
)
throws
Exception
{
http
.
securityContext
().
securityContextRepository
(
new
CookieSecurityContextRepository
(
userDetailsService
()));
http
.
requestCache
().
requestCache
(
new
NullRequestCache
());
http
.
authorizeRequests
()
.
antMatchers
(
"/"
,
"/home"
,
"/categories/**"
,
"/products/**"
).
permitAll
()
.
antMatchers
(
"/admin/**"
).
hasRole
(
"ADMIN"
)
.
anyRequest
().
authenticated
()
.
and
()
.
formLogin
()
// login
.
loginPage
(
"/login"
)
.
permitAll
()
.
successHandler
(
new
CustomAuthSuccessHandler
())
.
and
()
.
logout
()
// /login?logout
.
logoutUrl
(
"/logout"
)
.
logoutSuccessUrl
(
"/loggedOut"
)
.
deleteCookies
(
AUTHCOOKIENAME
)
.
permitAll
()
.
and
()
.
csrf
().
disable
()
;
}
@Bean
@Override
public
UserDetailsService
userDetailsServiceBean
()
{
return
super
.
userDetailsService
();
}
}
src/main/java/com/myshop/springconfig/web/WebMvcConfig.java
0 → 100644
View file @
969fb9e8
package
com.myshop.springconfig.web
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.web.servlet.config.annotation.ViewControllerRegistry
;
import
org.springframework.web.servlet.config.annotation.WebMvcConfigurer
;
@Configuration
public
class
WebMvcConfig
implements
WebMvcConfigurer
{
@Override
public
void
addViewControllers
(
ViewControllerRegistry
registry
)
{
registry
.
addRedirectViewController
(
"/"
,
"/home"
);
registry
.
addViewController
(
"/home"
).
setViewName
(
"home"
);
registry
.
addViewController
(
"/login"
).
setViewName
(
"login"
);
registry
.
addViewController
(
"/error/forbidden"
).
setViewName
(
"error/forbidden"
);
registry
.
addViewController
(
"/error/notFound"
).
setViewName
(
"error/notFound"
);
registry
.
addViewController
(
"/my/main"
).
setViewName
(
"my/myMain"
);
registry
.
addViewController
(
"/admin/main"
).
setViewName
(
"admin/adminMain"
);
registry
.
addViewController
(
"/loggedOut"
).
setViewName
(
"loggedOut"
);
}
}
src/main/resources/application.properties
0 → 100644
View file @
969fb9e8
spring.datasource.url
=
jdbc:mysql://localhost/shop?characterEncoding=utf8
spring.datasource.username
=
shopuser
spring.datasource.password
=
shoppass
spring.datasource.driver-class-name
=
com.mysql.cj.jdbc.Driver
spring.datasource.hikari.maximum-pool-size
=
10
spring.jpa.database
=
mysql
spring.jpa.show-sql
=
true
spring.jpa.hibernate.naming.physical-strategy
=
org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.open-in-view
=
false
logging.level.root
=
INFO
logging.level.com.myshop
=
DEBUG
logging.level.org.springframework.security
=
DEBUG
\ No newline at end of file
Prev
1
…
3
4
5
6
7
8
9
10
Next
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment