feat: login / Spring Security mpower 적용

dev
minuk926 2 years ago
parent 15dd7c64b6
commit 4f94fbe137

@ -1,6 +1,7 @@
package com.xit.biz.ctgy.auth; package com.xit.biz.ctgy.auth;
import com.xit.biz.ctgy.repository.IMinUserRepository; import com.xit.biz.ctgy.repository.IMinUserRepository;
import com.xit.biz.ctgy.v2.dao.MinUserinfoDao;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -17,11 +18,7 @@ public class MinPasswordEncoder implements PasswordEncoder {
@Setter @Setter
private String userid; private String userid;
private final IMinUserRepository repository; private final MinUserinfoDao minUserinfoDao;
// public MinPasswordEncoder(IMinUserinfoRepository repository) {
// this.repository = repository;
// }
/** /**
* *
@ -33,7 +30,7 @@ public class MinPasswordEncoder implements PasswordEncoder {
if (rawPassword == null) { if (rawPassword == null) {
throw new IllegalArgumentException("rawPassword cannot be null"); throw new IllegalArgumentException("rawPassword cannot be null");
} }
return repository.queryGetPasswdEncode(rawPassword.toString()); return minUserinfoDao.queryGetPasswdEncode(rawPassword.toString());
} }
/** /**
@ -44,7 +41,6 @@ public class MinPasswordEncoder implements PasswordEncoder {
*/ */
@Override @Override
public boolean matches(CharSequence rawPassword, String encodedPassword) { public boolean matches(CharSequence rawPassword, String encodedPassword) {
//return false;
if (rawPassword == null) { if (rawPassword == null) {
throw new IllegalArgumentException("rawPassword cannot be null"); throw new IllegalArgumentException("rawPassword cannot be null");
@ -54,7 +50,7 @@ public class MinPasswordEncoder implements PasswordEncoder {
return false; return false;
} }
return Objects.equals(repository.queryGetPasswd(rawPassword.toString()), encodedPassword); return Objects.equals(minUserinfoDao.queryGetPasswd(rawPassword.toString()), encodedPassword);
} }
/** /**

@ -3,11 +3,14 @@ package com.xit.biz.ctgy.auth.service.impl;
import com.xit.biz.cmm.entity.CmmUser; import com.xit.biz.cmm.entity.CmmUser;
import com.xit.biz.ctgy.auth.service.IAuthMinService; import com.xit.biz.ctgy.auth.service.IAuthMinService;
import com.xit.biz.ctgy.dto.LoginMinRequestDto; import com.xit.biz.ctgy.dto.LoginMinRequestDto;
import com.xit.biz.ctgy.dto.MinUserinfoDto;
import com.xit.biz.ctgy.entity.MinUserinfo; import com.xit.biz.ctgy.entity.MinUserinfo;
import com.xit.biz.ctgy.repository.IMinUserRepository; import com.xit.biz.ctgy.repository.IMinUserRepository;
import com.xit.biz.ctgy.v2.dao.MinUserinfoDao;
import com.xit.core.constant.ErrorCode; import com.xit.core.constant.ErrorCode;
import com.xit.core.constant.XitConstants; import com.xit.core.constant.XitConstants;
import com.xit.core.exception.TokenAuthException; import com.xit.core.exception.TokenAuthException;
import com.xit.core.oauth2.api.dao.RefreshTokenDao;
import com.xit.core.oauth2.api.dto.TokenDto; import com.xit.core.oauth2.api.dto.TokenDto;
import com.xit.core.oauth2.api.dto.TokenRequestDto; import com.xit.core.oauth2.api.dto.TokenRequestDto;
import com.xit.core.oauth2.api.entity.RefreshToken; import com.xit.core.oauth2.api.entity.RefreshToken;
@ -49,9 +52,9 @@ public class AuthMinService implements IAuthMinService {
private final AppProperties appProperties; private final AppProperties appProperties;
private final AuthenticationManager authenticationManager; private final AuthenticationManager authenticationManager;
private final IMinUserRepository userRepository; private final MinUserinfoDao userinfoDao;
private final JwtTokenProvider jwtTokenProvider; private final JwtTokenProvider jwtTokenProvider;
private final RefreshTokenRepository refreshTokenRepository; private final RefreshTokenDao refreshTokenDao;
/** /**
* <pre> * <pre>
@ -96,19 +99,19 @@ public class AuthMinService implements IAuthMinService {
session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
} }
MinUserinfo user = userRepository.findByUserid(loginRequestDto.getUserid()).orElseThrow(() -> new UsernameNotFoundException(loginRequestDto.getUserid() + " -> 사용자를 찾을 수 없습니다.")); MinUserinfoDto user = userinfoDao.findByUserid(loginRequestDto.getUserid()).orElseThrow(() -> new UsernameNotFoundException(loginRequestDto.getUserid() + " -> 사용자를 찾을 수 없습니다."));
Map<String, Object> infoMap = new HashMap<>(); Map<String, Object> infoMap = new HashMap<>();
infoMap.put(XitConstants.JwtToken.TOKEN_USER_NAME.getCode(), user.getName()); infoMap.put(XitConstants.JwtToken.TOKEN_USER_NAME.getCode(), user.getName());
infoMap.put(XitConstants.JwtToken.TOKEN_USER_MAIL.getCode(), user.getEmail()); infoMap.put(XitConstants.JwtToken.TOKEN_USER_MAIL.getCode(), user.getEmail());
RefreshToken savedRefreshToken = refreshTokenRepository.findByKey(authentication.getName()) RefreshToken savedRefreshToken = refreshTokenDao.findByKey(authentication.getName())
.orElse(null); .orElse(null);
// 저장된 refresh token not exists // 저장된 refresh token not exists
if (Checks.isNull(savedRefreshToken) || Checks.isNull(savedRefreshToken.getValue())) { if (Checks.isNull(savedRefreshToken) || Checks.isNull(savedRefreshToken.getValue())) {
// 없는 경우 새로 등록 // 없는 경우 새로 등록
tokenDto = jwtTokenProvider.generateTokenDto(authentication, infoMap); tokenDto = jwtTokenProvider.generateTokenDto(authentication, infoMap);
refreshTokenRepository.saveAndFlush( refreshTokenDao.save(
RefreshToken.builder() RefreshToken.builder()
.key(loginRequestDto.getUserid()) .key(loginRequestDto.getUserid())
.value(tokenDto.getRefreshToken()) .value(tokenDto.getRefreshToken())
@ -118,7 +121,6 @@ public class AuthMinService implements IAuthMinService {
// 저장된 토큰이 있다 // 저장된 토큰이 있다
} else { } else {
// 만료되지 않은 refresh token // 만료되지 않은 refresh token
if(!jwtTokenProvider.isExpiredToken(savedRefreshToken.getValue())) { if(!jwtTokenProvider.isExpiredToken(savedRefreshToken.getValue())) {
@ -137,10 +139,10 @@ public class AuthMinService implements IAuthMinService {
tokenDto = TokenDto.builder() tokenDto = TokenDto.builder()
.grantType(XitConstants.JwtToken.GRANT_TYPE.getCode()) .grantType(XitConstants.JwtToken.GRANT_TYPE.getCode())
.accessToken(jwtTokenProvider.generateJwtAccessToken(authentication, infoMap)) .accessToken(jwtTokenProvider.generateJwtAccessToken(authentication, infoMap))
.refreshToken(null) .refreshToken(savedRefreshToken.getValue())
.build(); .build();
refreshTokenRepository.saveAndFlush( refreshTokenDao.update(
RefreshToken.builder() RefreshToken.builder()
.key(loginRequestDto.getUserid()) .key(loginRequestDto.getUserid())
.value(tokenDto.getRefreshToken()) .value(tokenDto.getRefreshToken())
@ -152,7 +154,7 @@ public class AuthMinService implements IAuthMinService {
}else{ }else{
tokenDto = jwtTokenProvider.generateTokenDto(authentication, infoMap); tokenDto = jwtTokenProvider.generateTokenDto(authentication, infoMap);
refreshTokenRepository.saveAndFlush( refreshTokenDao.update(
RefreshToken.builder() RefreshToken.builder()
.key(loginRequestDto.getUserid()) .key(loginRequestDto.getUserid())
.value(tokenDto.getRefreshToken()) .value(tokenDto.getRefreshToken())
@ -168,7 +170,20 @@ public class AuthMinService implements IAuthMinService {
} }
// 5. 토큰 발급 // 5. 토큰 발급
tokenDto.setUser(user); tokenDto.setUser(
MinUserinfo.builder()
.userid(user.getUserid())
.passwd(user.getPasswd())
.name(user.getName())
.regnum(user.getRegnum())
.mphone(user.getMphone())
.email(user.getEmail())
.accesstype(user.getAccesstype())
.regdate(user.getRegdate())
.isenable(user.getIsenable())
.gu(user.getGu())
.build()
);
return tokenDto; return tokenDto;
} }
@ -240,7 +255,7 @@ public class AuthMinService implements IAuthMinService {
jwtTokenProvider.validateTokenExcludeExpired(sRefreshToken, true, true); jwtTokenProvider.validateTokenExcludeExpired(sRefreshToken, true, true);
// userId refresh token 으로 DB 확인 // userId refresh token 으로 DB 확인
RefreshToken savedRefreshToken = refreshTokenRepository.findByKey(authentication.getName()) RefreshToken savedRefreshToken = refreshTokenDao.findByKey(authentication.getName())
.orElse(null); .orElse(null);
if (Checks.isEmpty(savedRefreshToken)) throw new TokenAuthException(ErrorCode.NOT_EXISTS_SAVED_REFRESH_TOKEN); if (Checks.isEmpty(savedRefreshToken)) throw new TokenAuthException(ErrorCode.NOT_EXISTS_SAVED_REFRESH_TOKEN);
@ -249,7 +264,7 @@ public class AuthMinService implements IAuthMinService {
} }
// 토큰 부가 정보 set // 토큰 부가 정보 set
MinUserinfo user = userRepository.findByUserid(authentication.getName()).orElse(null); MinUserinfoDto user = userinfoDao.findByUserid(authentication.getName()).orElse(null);
if(Checks.isNull(user)) throw new TokenAuthException(ErrorCode.INVALID_ROLE_TOKEN); if(Checks.isNull(user)) throw new TokenAuthException(ErrorCode.INVALID_ROLE_TOKEN);
Map<String, Object> infoMap = new HashMap<>(); Map<String, Object> infoMap = new HashMap<>();
infoMap.put(XitConstants.JwtToken.TOKEN_USER_NAME.getCode(), user.getName()); infoMap.put(XitConstants.JwtToken.TOKEN_USER_NAME.getCode(), user.getName());

@ -1,8 +1,10 @@
package com.xit.biz.ctgy.auth.service.impl; package com.xit.biz.ctgy.auth.service.impl;
import com.xit.biz.ctgy.auth.UserMinPrincipal; import com.xit.biz.ctgy.auth.UserMinPrincipal;
import com.xit.biz.ctgy.dto.MinUserinfoDto;
import com.xit.biz.ctgy.entity.MinUserinfo; import com.xit.biz.ctgy.entity.MinUserinfo;
import com.xit.biz.ctgy.repository.IMinUserRepository; import com.xit.biz.ctgy.repository.IMinUserRepository;
import com.xit.biz.ctgy.v2.dao.MinUserinfoDao;
import com.xit.core.constant.ErrorCode; import com.xit.core.constant.ErrorCode;
import com.xit.core.exception.CustomBaseException; import com.xit.core.exception.CustomBaseException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -15,11 +17,22 @@ import org.springframework.stereotype.Service;
@RequiredArgsConstructor @RequiredArgsConstructor
public class CustomMinUserDetailsService implements UserDetailsService { public class CustomMinUserDetailsService implements UserDetailsService {
private final IMinUserRepository userRepository; private final MinUserinfoDao minUserinfoDao;
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
MinUserinfo user = userRepository.findByUserid(username).orElseThrow(() -> new CustomBaseException(ErrorCode.USER_NOT_FOUND)); MinUserinfoDto user = minUserinfoDao.findByUserid(username).orElseThrow(() -> new CustomBaseException(ErrorCode.USER_NOT_FOUND));
return UserMinPrincipal.create(user); return UserMinPrincipal.create(MinUserinfo.builder()
.userid(user.getUserid())
.passwd(user.getPasswd())
.name(user.getName())
.regnum(user.getRegnum())
.mphone(user.getMphone())
.email(user.getEmail())
.accesstype(user.getAccesstype())
.regdate(user.getRegdate())
.isenable(user.getIsenable())
.gu(user.getGu())
.build());
} }
} }

@ -51,6 +51,7 @@ public class MinUserController {
final MinUserinfoDto minUserinfoDto, final MinUserinfoDto minUserinfoDto,
@Parameter(hidden = true) @Parameter(hidden = true)
final Pageable pageable) { final Pageable pageable) {
//return null;
return RestResponse.of(service.findMinUsers(mapstruct.toEntity(minUserinfoDto), pageable)); return RestResponse.of(service.findMinUsers(mapstruct.toEntity(minUserinfoDto), pageable));
} }

@ -4,6 +4,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*; import lombok.*;
import java.io.Serializable; import java.io.Serializable;
import java.time.LocalDate;
import java.util.Objects; import java.util.Objects;
@Schema(name = "MinUserinfoDto", description = "사용자 DTO") @Schema(name = "MinUserinfoDto", description = "사용자 DTO")
@ -39,7 +40,7 @@ public class MinUserinfoDto implements Serializable {
private String team; private String team;
@Schema(required = false, title = "등록일시", example = " ", description = "Input Description...") @Schema(required = false, title = "등록일시", example = " ", description = "Input Description...")
private java.sql.Date regdate; private LocalDate regdate;
@Schema(required = false, title = "사용여부", example = " ", description = "Input Description...") @Schema(required = false, title = "사용여부", example = " ", description = "Input Description...")
private String isenable; private String isenable;

@ -33,8 +33,6 @@ public class MinUserController {
private final IMinUserService service; private final IMinUserService service;
private final MinUserinfoMapstruct mapstruct = Mappers.getMapper(MinUserinfoMapstruct.class);
// TODO :: 파라메터 정의 필요 // TODO :: 파라메터 정의 필요
@Secured(policy = SecurityPolicy.TOKEN) @Secured(policy = SecurityPolicy.TOKEN)
@Operation(summary = "사용자 목록 조회" , description = "사용자 목록 조회") @Operation(summary = "사용자 목록 조회" , description = "사용자 목록 조회")
@ -51,7 +49,8 @@ public class MinUserController {
final MinUserinfoDto minUserinfoDto, final MinUserinfoDto minUserinfoDto,
@Parameter(hidden = true) @Parameter(hidden = true)
final Pageable pageable) { final Pageable pageable) {
return RestResponse.of(service.findMinUsers(mapstruct.toEntity(minUserinfoDto), pageable)); return null;
//return RestResponse.of(service.findMinUsers(mapstruct.toEntity(minUserinfoDto), pageable));
} }
@Operation(summary = "사용자 정보 조회" , description = "사용자 정보 조회") @Operation(summary = "사용자 정보 조회" , description = "사용자 정보 조회")

@ -0,0 +1,60 @@
package com.xit.biz.ctgy.v2.dao;
import com.xit.biz.ctgy.dto.MinUserinfoDto;
import com.xit.biz.ctgy.entity.MinUserinfo;
import com.xit.core.support.sql.parser.QueryGenerator;
import com.xit.core.util.mpower.MpowerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
@Slf4j
public class MinUserinfoDao {
public Optional<MinUserinfoDto> findByUserid(final String userid){
String sql = QueryGenerator.createNamedQuery("user", "selectUserInfo")
.setParameter("userid", userid)
.getQueryString();
MpowerUtils query = new MpowerUtils();
query.setFeilds("userid, passwd, name, regnum, mphone, email, accesstype, team, isenable, gu");
query.setQuery(sql);
log.debug("=======>>>>>>", sql);
return Optional.ofNullable(query.getListObject(MinUserinfoDto.class).get(0));
}
public String queryGetPasswdEncode(final String passwd){
String sql = QueryGenerator.createNamedQuery("user", "selectPasswdEnc")
.setParameter("passwd", passwd)
.getQueryString();
MpowerUtils query = new MpowerUtils();
query.setFeilds("passwd");
query.setQuery(sql);
log.debug("=======>>>>>>", sql);
return String.valueOf(query.getListMap().get(0).get("passwd"));
}
//@Query(value = "SELECT ECL_DECRYPT(MU.passwd) AS passwd FROM min_userinfo MU WHERE MU.userid = ?1", nativeQuery = true)
public String queryGetPasswd(final String userid){
String sql = QueryGenerator.createNamedQuery("user", "selectPasswdDec")
.setParameter("userid", userid)
.getQueryString();
MpowerUtils query = new MpowerUtils();
query.setFeilds("passwd");
query.setQuery(sql);
log.debug("=======>>>>>>", sql);
return String.valueOf(query.getListMap().get(0).get("passwd"));
}
public MinUserinfo findMinUserinfoByUserid(final String userid){
return null;
}
//-------------------------------------------------------------------------
// 주정차위반 심사대상 등록 - 등록 대상 심사자 조회
//-------------------------------------------------------------------------
public List<MinUserinfo> findAllByTeamAndIsenableAndAccesstype(String msuTeam, String isenabled, String accesstype){
return null;
}
}

@ -4,6 +4,7 @@ import com.xit.biz.ctgy.auth.MinPasswordEncoder;
import com.xit.biz.ctgy.auth.service.impl.CustomMinOAuth2UserService; import com.xit.biz.ctgy.auth.service.impl.CustomMinOAuth2UserService;
import com.xit.biz.ctgy.auth.service.impl.CustomMinUserDetailsService; import com.xit.biz.ctgy.auth.service.impl.CustomMinUserDetailsService;
import com.xit.biz.ctgy.repository.IMinUserRepository; import com.xit.biz.ctgy.repository.IMinUserRepository;
import com.xit.biz.ctgy.v2.dao.MinUserinfoDao;
import com.xit.core.oauth2.api.dao.RefreshTokenDao; import com.xit.core.oauth2.api.dao.RefreshTokenDao;
import com.xit.core.oauth2.api.repository.RefreshTokenRepository; import com.xit.core.oauth2.api.repository.RefreshTokenRepository;
import com.xit.core.oauth2.config.properties.AppProperties; import com.xit.core.oauth2.config.properties.AppProperties;
@ -105,10 +106,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomMinUserDetailsService userDetailsService; private final CustomMinUserDetailsService userDetailsService;
private final CustomMinOAuth2UserService customOAuth2UserService; private final CustomMinOAuth2UserService customOAuth2UserService;
private final TokenAccessDeniedHandler tokenAccessDeniedHandler; private final TokenAccessDeniedHandler tokenAccessDeniedHandler;
//private final RefreshTokenRepository refreshTokenRepository;
private final RefreshTokenDao refreshTokenDao; private final RefreshTokenDao refreshTokenDao;
private final MinUserinfoDao minUserinfoDao;
private final IMinUserRepository minUserRepository;
/** /**
* 1. configure( WebSecurity) : * 1. configure( WebSecurity) :
@ -244,7 +243,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
* */ * */
@Bean @Bean
public MinPasswordEncoder passwordEncoder() { public MinPasswordEncoder passwordEncoder() {
return new MinPasswordEncoder(minUserRepository); return new MinPasswordEncoder(minUserinfoDao);
} }
/* /*

@ -11,14 +11,10 @@ import java.util.Optional;
@Repository @Repository
public class RefreshTokenDao { public class RefreshTokenDao {
private static final String sqlXmlFile = "sql/refreshToken-mapper";
public Optional<RefreshToken> findByKey(String key){ public Optional<RefreshToken> findByKey(String key){
String sql = QueryGenerator.createNamedQuery("refreshToken", "selectRefreshToken") String sql = QueryGenerator.createNamedQuery("refreshToken", "selectRefreshToken")
.setParameter("key", key) .setParameter("key", key)
.getQueryString(); .getQueryString();
//String sql = DBUtils.getXmlSql(sqlXmlFile, "selectRefreshToken");
//sql = sql.replaceFirst(":userId", key);
MpowerUtils selectQuery = new MpowerUtils(); MpowerUtils selectQuery = new MpowerUtils();
selectQuery.setFeilds("key, value"); selectQuery.setFeilds("key, value");
@ -27,36 +23,22 @@ public class RefreshTokenDao {
} }
public void save(RefreshToken refreshToken){ public void save(RefreshToken refreshToken){
// String sql = DBUtils.getXmlSql(sqlXmlFile, "saveRefreshToken");
// sql = sql.replaceFirst(":userId", refreshToken.getKey());
// sql = sql.replaceFirst(":tokenValue", refreshToken.getValue());
String sql = QueryGenerator.createNamedQuery("refreshToken", "insertRefreshToken") String sql = QueryGenerator.createNamedQuery("refreshToken", "insertRefreshToken")
.setParameter("key", refreshToken.getKey()) .setParameter("key", refreshToken.getKey())
.setParameter("value", refreshToken.getValue()) .setParameter("value", refreshToken.getValue())
.getQueryString(); .getQueryString();
MpowerUtils saveQuery = new MpowerUtils(); MpowerUtils saveQuery = new MpowerUtils();
//sendXml.setFeilds("key, value"); saveQuery.insertQuery(sql);
//sendXml.setQuery(sql);
//return Optional.ofNullable(sendXml.selectCustomQuery(RefreshToken.class).get(0));
} }
public void update(RefreshToken refreshToken){ public void update(RefreshToken refreshToken){
// String sql = DBUtils.getXmlSql(sqlXmlFile, "updateRefreshToken");
// sql = sql.replaceFirst(":userId", refreshToken.getKey());
// sql = sql.replaceFirst(":tokenValue", refreshToken.getValue());
String sql = QueryGenerator.createNamedQuery("refreshToken", "updateRefreshToken") String sql = QueryGenerator.createNamedQuery("refreshToken", "updateRefreshToken")
.setParameter("value", refreshToken.getValue()) .setParameter("value", refreshToken.getValue())
.setParameter("key", refreshToken.getKey()) .setParameter("key", refreshToken.getKey())
.getQueryString(); .getQueryString();
MpowerUtils updateQuery = new MpowerUtils(); MpowerUtils updateQuery = new MpowerUtils();
//sendXml.setFeilds("key, value"); updateQuery.updateQuery(sql);
//sendXml.setQuery(sql);
//return Optional.ofNullable(sendXml.selectCustomQuery(RefreshToken.class).get(0));
} }
} }

@ -33,31 +33,12 @@ public class MpowerUtils {
static int port = 9999; static int port = 9999;
static String query = ""; static String query = "";
static ArrayList<String> feilds = new ArrayList<String>(); static ArrayList<String> feilds = new ArrayList<String>();
//static String feild = "";
static String tmpFeilds = "";
static Boolean RowNum = false;
static String tableNm = "";
static String WhereStr = "";
static String Orderby = "";
static int pageIndex = 0;
static int lastIndex = 10;
static int recordCountPerPage = 10;
static String beforeXml = "<?xml version='1.0' encoding='euc-kr'?><QUERYS DBNAME='"+DbName2+"' DEBUG='true'><QUERY TYPE='select' BATCH='false'><SQL><![CDATA["; static String beforeXml = "<?xml version='1.0' encoding='euc-kr'?><QUERYS DBNAME='"+DbName2+"' DEBUG='true'><QUERY TYPE='select' BATCH='false'><SQL><![CDATA[";
static String insertXml = "<?xml version='1.0' encoding='euc-kr'?><QUERYS DBNAME='"+DbName2+"' DEBUG='true'><QUERY TYPE='insert' BATCH='false'><SQL><![CDATA[";
static String updateXml = "<?xml version='1.0' encoding='euc-kr'?><QUERYS DBNAME='"+DbName2+"' DEBUG='true'><QUERY TYPE='update' BATCH='false'><SQL><![CDATA[";
static String deleteXml = "<?xml version='1.0' encoding='euc-kr'?><QUERYS DBNAME='"+DbName2+"' DEBUG='true'><QUERY TYPE='update' BATCH='false'><SQL><![CDATA[";
static String afterXml = "]]></SQL></QUERY></QUERYS>"; static String afterXml = "]]></SQL></QUERY></QUERYS>";
//Ps변수
static String Params = "";
static int psParamCount = 0;
static String psFinalFarams ="";
static String QueryXml = "";
static String vioPhoto = "";
static String vioPhotoBus = "";
static String tunullingFile = "";
public void setQuery(String query){ public void setQuery(String query){
MpowerUtils.query = query; MpowerUtils.query = query;
} }
@ -66,276 +47,10 @@ public class MpowerUtils {
feilds.add(feildNm); feilds.add(feildNm);
} }
public int getFirstIndex() {
return (pageIndex - 1) * recordCountPerPage +1;
}
public int getLastIndex() {
return lastIndex = pageIndex * recordCountPerPage;
}
public List<Map<String, Object>> selectQuery() {
String fileList = "";
for(int cnt = 0;cnt<feilds.size();cnt++){
if(cnt==0){
fileList += feilds.get(cnt);
}else{
fileList += "," + feilds.get(cnt);
}
}
query = beforeXml + "select "+ fileList +" from " + tableNm + WhereStr + afterXml ;
//logger.debug("=====================================================Select Query==================================================");
//logger.debug("select "+fileList +" from "+tableNm + WhereStr);
System.out.println("select "+fileList +" from "+tableNm + WhereStr);
//List<EgovMap> mList = new ArrayList<EgovMap>();
List<Map<String, Object>> mList= new ArrayList<Map<String, Object>>();
try {
mpower = new Client(hostip,port);
mpower.getConnection("MPowerXmlToQuery.xmlQuery1");
mpower.setInput("SQLXML", query);
mpower.Request();
String result = mpower.getString("result", 0, 0);
System.out.println("#######$$$$$$$$$$$$$$$$$$"+result);
int row;
if (result.equals("true")){
row = mpower.getMaxRow("list1");
if(row>0){
for(int i=0;i<row;i++){
//EgovMap m = new EgovMap();
Map<String,Object> m = new HashMap<>();
for(int j=0;j<feilds.size();j++){
m.put(feilds.get(j), mpower.getString("list1", i, j));
}
mList.add(m);
}
}
}
//logger.debug("SelectList Count :: "+mList.size()+"건");
//logger.debug("===================================================================================================================");
mpower.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally{
query = "";
feilds = new ArrayList<String>();
tableNm = "";
WhereStr = "";
Orderby = "";
}
return mList;
}
private void clearValidation() { private void clearValidation() {
query = ""; query = "";
feilds = new ArrayList<String>(); feilds = new ArrayList<String>();
tableNm = "";
WhereStr = "";
Orderby="";
psParamCount = 0;
QueryXml = "";
Params = "";
psFinalFarams = "";
recordCountPerPage = 10;
//feild = "";
}
/**
* @ SELECT
* @return
*/
public Map<String,Object> selectListQuery() {
//EgovMap mListMap = new EgovMap();
Map<String,Object> mListMap = new HashMap<>();
//배열로 넘어온 필드를 String 오브젝트로 변형
String fileList = "";
for(int cnt = 0;cnt<feilds.size();cnt++){
if(cnt==0){
fileList += feilds.get(cnt);
}else{
fileList += "," + feilds.get(cnt);
}
}
String init="";
String init2="";
init = beforeXml + "select RN,"+ fileList +" from(";
init2 = ")TB where RN BETWEEN "+getFirstIndex()+" and "+getLastIndex()+afterXml;
query = init;
query = query+"select ROWNUM RN,"+fileList+" from(";
query = query+"select "+fileList+" ";
query = query+"from "+tableNm+" ";
query = query+WhereStr+" ";
query = query+Orderby;
query = query+")TA";
query = query+init2;
System.out.println("이곳은쿼리");
System.out.println(query);
System.out.println("이곳은쿼리");
String Cquery = beforeXml + "select count(*) from " + tableNm +" "+ WhereStr +afterXml;
if(RowNum == true){
feilds = new ArrayList<String>();
this.setFeilds("RN, "+tmpFeilds);
}
//List<EgovMap> mList = new ArrayList<EgovMap>();
List<Map<String, Object>> mList = new ArrayList<>();
System.out.println("mlistmlist");
System.out.println(mList);
System.out.println("mlistmlist");
int mListCount = 0;
try {
mpower = new Client(hostip,port);
mpower.getConnection("MPowerXmlToQuery.xmlQuery1");
mpower.setInput("SQLXML", query);
mpower.Request();
String result = mpower.getString("result", 0, 0);
int row = 0;
if (result.equals("true")){
row = mpower.getMaxRow("list1");
if(row>0){
for(int i=0;i<row;i++){
//EgovMap m = new EgovMap();
Map<String,Object> m = new HashMap<>();
for(int j=0;j<feilds.size();j++){
if(RowNum == false){
m.put(feilds.get(j), mpower.getString("list1", i, j+1));
}else if(RowNum == true){
m.put(feilds.get(j), mpower.getString("list1", i, j));
}
}
mList.add(m);
}
mListMap.put("mList", mList);
}
}
mpower.disconnect();
if(row>0){
mpower = new Client(hostip,port);
mpower.getConnection("MPowerXmlToQuery.xmlQuery1");
mpower.setInput("SQLXML", Cquery);
mpower.Request();
String strList1 = mpower.getString("list1", 0, 0);
if( !strList1.equals("") && strList1 != null){
mListCount = Integer.parseInt(strList1);
}
mpower.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
clearValidation();
}
System.out.println("엠리스트트트트트");
System.out.println(mListCount);
System.out.println(mListMap);
System.out.println(mList);
System.out.println("엠리스트트트트트");
mListMap.put("mListCount", mListCount);
return mListMap;
}
//
/**
* @ SELECT
* @return
* @throws SQLException
*/
public Map<String,Object> selectListQueryNew() throws SQLException {
//EgovMap mListMap = new EgovMap();
Map<String,Object> mListMap = new HashMap<>();
//배열로 넘어온 필드를 String 오브젝트로 변형
String fileList = "";
for(int cnt = 0;cnt<feilds.size();cnt++){
if(cnt==0){
fileList += feilds.get(cnt);
}else{
fileList += "," + feilds.get(cnt);
}
}
String finalQuery = "";
String Cquery = beforeXml + "select count(*) from " + tableNm +" "+ WhereStr +afterXml;
// if(!"".equals(feild) && feild != null){
// finalQuery = query;
// }else{
finalQuery = "select " + fileList +" from " + tableNm +" "+ WhereStr;
//}
if(RowNum == true){
feilds = new ArrayList<String>();
this.setFeilds("RN, "+tmpFeilds);
}
//List<EgovMap> mList = new ArrayList<EgovMap>();
List<Map<String, Object>> mList = new ArrayList<Map<String, Object>>();
int mListCount = 0;
Connection con;
Statement stmt; //단순 쿼리 실행
PreparedStatement pstmt = null; //컴파일시 디비에 먼저 파싱하므로 Statement 보다 빠름
CallableStatement cstmt; //프로시져를 호출하므로 속도가 PreparedStatement 보다 빠름
ResultSet rs = null;
String dbURL = "jdbc:oracle:thin:@115.21.123.114:1521:ora10g";
String driver = "oracle.jdbc.OracleDriver";
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
con = DriverManager.getConnection(dbURL, "TRAFFIC", "xhdgkq0");
//3.1 Statement 객체로 구문객체 생성 및 실행
int size = 0;
try{
System.out.println("Query :" + finalQuery);
pstmt = con.prepareStatement(finalQuery);
rs = pstmt.executeQuery(); // 이거 왜 실행안???
System.out.println("rs:" + rs);
boolean chpoint = false;
while(rs.next())
{
size = rs.getInt(1);
//EgovMap m = new EgovMap();
Map<String,Object> m = new HashMap<>();
if(!chpoint)
{
for(int j=0;j<size;j++){
m.put(feilds.get(j),rs.getString(feilds.get(j).toString()));
}
mList.add(m);
}
}
mListMap.put("mList", mList);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
rs.close();
pstmt.close();
con.close();
clearValidation();
}catch(SQLException e){
e.printStackTrace();
}
}
return mListMap;
} }
//
/** /**
* @ SELECT * @ SELECT
@ -345,6 +60,7 @@ public class MpowerUtils {
List<Map<String,Object>> mList = new ArrayList<>(); List<Map<String,Object>> mList = new ArrayList<>();
query = beforeXml+query+afterXml; query = beforeXml+query+afterXml;
System.out.println(query);
try { try {
mpower = new Client(hostip,port); mpower = new Client(hostip,port);
mpower.setCryptEnable(false); mpower.setCryptEnable(false);
@ -380,6 +96,7 @@ public class MpowerUtils {
List<T> list = new ArrayList<>(); List<T> list = new ArrayList<>();
query = beforeXml+query+afterXml; query = beforeXml+query+afterXml;
System.out.println(query);
try { try {
mpower = new Client(hostip,port); mpower = new Client(hostip,port);
mpower.setCryptEnable(false); mpower.setCryptEnable(false);
@ -448,6 +165,7 @@ public class MpowerUtils {
if(totalCnt <= 0) return rtnMap; if(totalCnt <= 0) return rtnMap;
query = beforeXml+query+afterXml; query = beforeXml+query+afterXml;
System.out.println(query);
try { try {
mpower = new Client(hostip,port); mpower = new Client(hostip,port);
mpower.setCryptEnable(false); mpower.setCryptEnable(false);
@ -496,61 +214,45 @@ public class MpowerUtils {
return rtnMap; return rtnMap;
} }
public void setFeilds(String string) { public int insertQuery(String sql) {
String[] m = string.split(","); return executeQuery(insertXml + sql +afterXml);
for(int i=0;i<m.length;i++){
setFeild(m[i].trim());
}
tmpFeilds = string;
} }
public int updateQuery(String sql) {
//첨부파일 터널링 서버로 복사 return executeQuery(updateXml + sql +afterXml);
public void fnFileUpload(String tmpFileLocation,String realRcRilenm){
String fph = tunullingFile; //터널링에 복사되는 파일경로
try{
Client mp = new Client("127.0.0.1", 2500);
mp.getConnection("XitFile.XitUpload");
mp.setInput("dir",tunullingFile);
mp.setInput("upfile1",tmpFileLocation+realRcRilenm,true);
mp.Request();
}catch(Exception e){
e.printStackTrace();
}
//logger.debug(fph);
} }
public int deleteQuery(String sql) {
return executeQuery(deleteXml + sql +afterXml);
}
//터널링에서 웹서버로 첨부파일 복사 public int executeQuery(String sql) {
public static void fnDownFile(String fileName,String sessionId){ System.out.println(sql);
String serviceName = "XitFile.XitDownload";
String fph = MpowerUtils.class.getResource("").getPath();
fph = fph.replace("WEB-INF/classes/xit/cmmn/utill/", "vioPhoto/"+sessionId+"/"); //웹서버 저장 위치
String fphs = fph.substring(0,1);
if(fphs.equals("/")){
fph = fph.substring(1);
}
String tmpTunullingFile = tunullingFile; //터널링에 저장된 단속사진 경로
try{ try{
Client mp = new Client("127.0.0.1", 2500); mpower = new Client(hostip,port);
mp.getConnection("XitFile.XitDownload"); mpower.getConnection("MPowerXmlToQuery.xmlQuery1");
mp.setInput("dnfile1",tmpTunullingFile+ fileName); //터널링에 실질 존재하는 경로,파일명 mpower.setInput("SQLXML", sql);
mp.Request(); mpower.Request();
String result = mp.getString("result", 0, 0);
if (result.equals("true")){ String result = mpower.getString("result", 0, 0);
mp.getFileName("imageA"); if (!result.equals("true")){
mp.savefile("imageA", fph); System.out.println("<<<<<<<<<<<<===========#$#$#$$##$#$$#$#$$$$$$$====>>>>>>>>>");
} }
}catch(Exception e){
mpower.disconnect();
} catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally{
clearValidation();
} }
//logger.debug("웹서버 저장되는 첨부파일 위치:"+fph); return 1;
System.out.println("웹서버 저장되는 첨부파일 위치:"+fph);
}
}
public void setFeilds(String string) {
String[] m = string.split(",");
for(int i=0;i<m.length;i++){
setFeild(m[i].trim());
}
}
} }

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings namespace="user">
<native-query id="selectUserInfo">
/* minuserinfo-mapper|selectUserInfo|julim */
SELECT userid,
passwd,
name,
regnum,
mphone,
email,
accesstype,
team,
isenable,
gu
FROM min_userinfo
WHERE userid = #{userid}
</native-query>
<native-query id="selectPasswdEnc">
SELECT TRAFFIC.ECL_ENCRYPT(#{passwd}) AS passwd
FROM DUAL
</native-query>
<native-query id="selectPasswdDec">
SELECT TRAFFIC.ECL_DECRYPT(passwd) AS passwd
FROM min_userinfo
WHERE userid = #{userid}
</native-query>
</entity-mappings>
Loading…
Cancel
Save