diff --git a/build.gradle b/build.gradle index f732450..b80b5d3 100644 --- a/build.gradle +++ b/build.gradle @@ -72,6 +72,12 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-jdbc' + + // mybatis + implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' + //implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter' + + // config 암호화 사용 implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.3' // spring-boot 2.3 까지는 사용 불가 - spring-boot-starter-web에 포함되어 있다 @@ -103,7 +109,7 @@ dependencies { // Mybatis //-----------------------------------------------------------------------------------// implementation 'org.mybatis:mybatis:3.5.9' - implementation 'org.mybatis:mybatis-typehandlers-jsr310:1.0.2' + //implementation 'org.mybatis:mybatis-typehandlers-jsr310:1.0.2' implementation 'org.mybatis:mybatis-spring:2.0.6' //-----------------------------------------------------------------------------------// @@ -223,6 +229,10 @@ dependencies { //implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.12.5' //-----------------------------------------------------------------------------------// + // https://mvnrepository.com/artifact/com.googlecode.juniversalchardet/juniversalchardet + implementation group: 'com.googlecode.juniversalchardet', name: 'juniversalchardet', version: '1.0.3' + + //-----------------------------------------------------------------------------------// // Test //-----------------------------------------------------------------------------------// diff --git a/src/main/java/com/xit/biz/ctgy/controller/BoardController.java b/src/main/java/com/xit/biz/ctgy/controller/BoardController.java index 4f89880..bbe5860 100644 --- a/src/main/java/com/xit/biz/ctgy/controller/BoardController.java +++ b/src/main/java/com/xit/biz/ctgy/controller/BoardController.java @@ -39,6 +39,7 @@ public class BoardController { @Parameters({ @Parameter(in = ParameterIn.QUERY, name = "ciTitle", description = "제목", required = false, example = " "), @Parameter(in = ParameterIn.QUERY, name = "ciName", description = "이름", required = false, example = " "), + @Parameter(in = ParameterIn.QUERY, name = "ciContents", description = "내용", required = false, example = " "), @Parameter(in = ParameterIn.QUERY, name = "page", description = "페이지", required = true, example = "0"), @Parameter(in = ParameterIn.QUERY, name = "size", description = "페이지당갯수", required = true, example = "10") }) diff --git a/src/main/java/com/xit/biz/ctgy/v2/controller/BoardController.java b/src/main/java/com/xit/biz/ctgy/v2/controller/BoardController.java index b1a52f8..6a198b8 100644 --- a/src/main/java/com/xit/biz/ctgy/v2/controller/BoardController.java +++ b/src/main/java/com/xit/biz/ctgy/v2/controller/BoardController.java @@ -39,6 +39,7 @@ public class BoardController { @Parameters({ @Parameter(in = ParameterIn.QUERY, name = "ciTitle", description = "제목", required = false, example = " "), @Parameter(in = ParameterIn.QUERY, name = "ciName", description = "이름", required = false, example = " "), + @Parameter(in = ParameterIn.QUERY, name = "ciContents", description = "내용", required = false, example = " "), @Parameter(in = ParameterIn.QUERY, name = "page", description = "페이지", required = true, example = "0"), @Parameter(in = ParameterIn.QUERY, name = "size", description = "페이지당갯수", required = true, example = "10") }) @@ -48,35 +49,34 @@ public class BoardController { final BoardDto dto, @Parameter(hidden = true) final Pageable pageable) { - //return RestResponse.of(service.findAll(dto, pageable)); - return RestResponse.of(service.findAllTest(dto)); + return RestResponse.of(service.findAll(dto, pageable)); } - @Secured(policy = SecurityPolicy.TOKEN) - @Operation(summary = "게시글 조회수 증가" , description = "게시글 조회수 증가") - @Parameters({ - @Parameter(in = ParameterIn.PATH, name = "ciCode", description = "게시글번호", required = true, example = "18"), - }) - @PutMapping(value = "/hit/{ciCode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity modifyByCiCode(@PathVariable final Long ciCode) { - return RestResponse.of(service.modifyByCiCode(ciCode)); - } - - @Secured(policy = SecurityPolicy.TOKEN) - @Operation(summary = "게시글 등록" , description = "게시글 등록") - @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity saveBoard(BoardDto dto) { - service.saveBoard(dto); - return RestResponse.of(HttpStatus.OK); - } - - @Secured(policy = SecurityPolicy.TOKEN) - @Operation(summary = "게시글 삭제", description = "게시글 삭제") - @PostMapping(value = "/{ciCode}") - public ResponseEntity removeBoard(@PathVariable @Nonnull final Long ciCode) { - AssertUtils.isTrue(!Checks.isEmpty(ciCode), "게시글이 선택되지 않았습니다."); - service.removeBoard(ciCode); - - return RestResponse.of(HttpStatus.OK); - } +// @Secured(policy = SecurityPolicy.TOKEN) +// @Operation(summary = "게시글 조회수 증가" , description = "게시글 조회수 증가") +// @Parameters({ +// @Parameter(in = ParameterIn.PATH, name = "ciCode", description = "게시글번호", required = true, example = "18"), +// }) +// @PutMapping(value = "/hit/{ciCode}", produces = MediaType.APPLICATION_JSON_VALUE) +// public ResponseEntity modifyByCiCode(@PathVariable final Long ciCode) { +// return RestResponse.of(service.modifyByCiCode(ciCode)); +// } +// +// @Secured(policy = SecurityPolicy.TOKEN) +// @Operation(summary = "게시글 등록" , description = "게시글 등록") +// @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE) +// public ResponseEntity saveBoard(BoardDto dto) { +// service.saveBoard(dto); +// return RestResponse.of(HttpStatus.OK); +// } +// +// @Secured(policy = SecurityPolicy.TOKEN) +// @Operation(summary = "게시글 삭제", description = "게시글 삭제") +// @PostMapping(value = "/{ciCode}") +// public ResponseEntity removeBoard(@PathVariable @Nonnull final Long ciCode) { +// AssertUtils.isTrue(!Checks.isEmpty(ciCode), "게시글이 선택되지 않았습니다."); +// service.removeBoard(ciCode); +// +// return RestResponse.of(HttpStatus.OK); +// } } diff --git a/src/main/java/com/xit/biz/ctgy/v2/service/IBoardService.java b/src/main/java/com/xit/biz/ctgy/v2/service/IBoardService.java index 3d209a3..7170dbe 100644 --- a/src/main/java/com/xit/biz/ctgy/v2/service/IBoardService.java +++ b/src/main/java/com/xit/biz/ctgy/v2/service/IBoardService.java @@ -6,17 +6,17 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Map; +import java.util.List; public interface IBoardService { - Page findAll(final BoardDto dto, Pageable pageable); + List> findAll(final BoardDto dto, Pageable pageable); - Map findAllTest(final BoardDto dto); - Page findAll2(final MinCivBoard680 entity, Pageable pageable); - - int modifyByCiCode(Long ciCode); - - void saveBoard(BoardDto dto); - - void removeBoard(Long ciCode); +// Page findAll2(final MinCivBoard680 entity, Pageable pageable); +// +// int modifyByCiCode(Long ciCode); +// +// void saveBoard(BoardDto dto); +// +// void removeBoard(Long ciCode); } diff --git a/src/main/java/com/xit/biz/ctgy/v2/service/impl/BoardService.java b/src/main/java/com/xit/biz/ctgy/v2/service/impl/BoardService.java index 7d19cc0..dcb923c 100644 --- a/src/main/java/com/xit/biz/ctgy/v2/service/impl/BoardService.java +++ b/src/main/java/com/xit/biz/ctgy/v2/service/impl/BoardService.java @@ -2,10 +2,12 @@ package com.xit.biz.ctgy.v2.service.impl; import com.google.common.base.Objects; import com.xit.biz.ctgy.dto.BoardDto; +import com.xit.biz.ctgy.dto.JudgeListDto; import com.xit.biz.ctgy.dto.struct.MinCivBoard680Mapstruct; import com.xit.biz.ctgy.entity.MinCivBoard680; import com.xit.biz.ctgy.repository.IBoardRepository; import com.xit.biz.ctgy.v2.service.IBoardService; +import com.xit.core.config.database.BaseMybatisDaoSupport; import com.xit.core.constant.ErrorCode; import com.xit.core.exception.CustomBaseException; import com.xit.core.oauth2.utils.HeaderUtil; @@ -13,8 +15,16 @@ import com.xit.core.support.jpa.JpaUtil; import com.xit.core.util.Checks; import com.xit.core.util.CommUtil; import com.xit.core.util.mpower.MpowerUtil; +import com.xit.core.util.mpower.MpowerUtils; import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; import org.mapstruct.factory.Mappers; +import org.mybatis.spring.SqlSessionTemplate; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.data.domain.Page; @@ -23,6 +33,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.nio.charset.Charset; import java.util.List; import java.util.Map; @@ -30,113 +41,78 @@ import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatc @Service @AllArgsConstructor +@Slf4j public class BoardService implements IBoardService { - private final IBoardRepository repository; private final PasswordEncoder passwordEncoder; - private final MinCivBoard680Mapstruct mapstruct = Mappers.getMapper(MinCivBoard680Mapstruct.class); + private final SqlSessionTemplate sqlSessionTemplate; @Transactional(readOnly = true) - public Page findAll(final BoardDto dto, Pageable pageable) { - pageable = JpaUtil.getPagingInfo(pageable); - return repository.findAll(dto, pageable); - } - @Transactional(readOnly = true) - public Map findAllTest(final BoardDto dto){ - MpowerUtil sendXml = new MpowerUtil(); - String query = "SELECT ci_code ciCode,\n" + - " name ciName,\n" + - " ci_contentno ciContentno,\n" + - " ci_title ciTitle,\n" + - " ci_contents ciContents,\n" + - " ci_nalja ciNalja,\n" + - " ci_step ciStep,\n" + - " ci_revel ciRevel,\n" + - " ci_ref ciRef,\n" + - " ci_hit ciHit,\n" + - " ci_pass ciPass,\n" + - " ci_id ciId \n" + - " FROM min_civ_board680 LEFT OUTER JOIN min_userinfo ON (ci_id = userid)\n" + - " WHERE ci_code IN\n" + - " (20,\n" + - " 19,\n" + - " 18,\n" + - " 17,\n" + - " 16,\n" + - " 13,\n" + - " 15,\n" + - " 12,\n" + - " 14,\n" + - " 11,\n" + - " 9,\n" + - " 10,\n" + - " 7,\n" + - " 8,\n" + - " 6,\n" + - " 4,\n" + - " 3,\n" + - " 1,\n" + - " 5,\n" + - " 2)"; - sendXml.setFeilds("ciCode, ciName, ciContentno, ciTitle, ciContents, ciNalja, ciStep, ciRevel, ciRef, ciHit, ciPass, ciId"); - sendXml.setQuery(query); - Map eMap = sendXml.selectCustomQuery(); - return eMap; - } - @Transactional(readOnly = true) - public Page findAll2(final MinCivBoard680 entity, Pageable pageable) { - pageable = JpaUtil.getPagingInfo(pageable); - ExampleMatcher exampleMatcher = ExampleMatcher.matchingAll() - .withMatcher("ciTitle", contains()) - .withMatcher("ciName", contains()); - Example example = Example.of(entity, exampleMatcher); - return repository.findAll(example, pageable); - } + public List> findAll(final BoardDto dto, Pageable pageable) { - @Override - @Transactional - public int modifyByCiCode(Long ciCode) { - return repository.updateInHitForMinCivBoard680(ciCode); - } + String sql = CommUtil.getMybatisSql(sqlSessionTemplate, "board.selectBoardList", dto); - @Override - @Transactional - public void saveBoard(BoardDto dto) { - MinCivBoard680 entity = null; + MpowerUtils sendXml = new MpowerUtils(); + sendXml.setFeilds("ciCode, ciName, ciContentno, ciTitle, ciContents, ciNalja, ciStep, ciRevel, ciRef, ciHit, ciPass, ciId"); + sendXml.setQuery(sql); - // update 인 경우 - if(Checks.isNotEmpty(dto.getCiCode())) { - entity = repository.findById(dto.getCiCode()).orElseThrow(() -> new CustomBaseException(ErrorCode.DATA_NOT_FOUND)); - if(!entity.getCiPass().equals(passwordEncoder.encode(dto.getCiPass()))){ - throw new CustomBaseException(ErrorCode.MISMATCH_PASSWORD); - } - entity.setCiTitle(dto.getCiTitle()); - entity.setCiContents(dto.getCiContents()); - }else { - dto.setCiCode(repository.getCiCode()); - dto.setCiContentno(dto.getCiCode()); - if (Checks.isEmpty(dto.getCiRef()) || dto.getCiRef() == 0L) { - dto.setCiRef(dto.getCiCode()); - dto.setCiStep(0L); - dto.setCiRevel(0L); - } - dto.setCiPass(passwordEncoder.encode(dto.getCiPass())); - dto.setCiIp(CommUtil.getDeviceInfo().getIp()); - entity = mapstruct.toEntity(dto); - } - repository.save(entity); + return sendXml.selectCustomQuery(); } - @Override - @Transactional - public void removeBoard(Long ciCode) { - - MinCivBoard680 savedEntity = repository.findById(ciCode).orElseThrow(() -> new CustomBaseException(ErrorCode.NOT_FOUND)); - if(!Objects.equal(HeaderUtil.getUserId(), savedEntity.getCiId())) throw new CustomBaseException("삭제 권한(게시글 소유자)이 없는 사용자 입니다"); - - // 댓글 존재 여부 조회 - List list = repository.findByCiRef(ciCode); - if(list.size() > 1) throw new CustomBaseException("삭제 할 수 없는 게시글 입니다[댓글 존재]"); - repository.deleteById(ciCode); - } +// @Transactional(readOnly = true) +// public Page findAll2(final MinCivBoard680 entity, Pageable pageable) { +// pageable = JpaUtil.getPagingInfo(pageable); +// ExampleMatcher exampleMatcher = ExampleMatcher.matchingAll() +// .withMatcher("ciTitle", contains()) +// .withMatcher("ciName", contains()); +// Example example = Example.of(entity, exampleMatcher); +// return repository.findAll(example, pageable); +// } +// +// @Override +// @Transactional +// public int modifyByCiCode(Long ciCode) { +// return repository.updateInHitForMinCivBoard680(ciCode); +// } +// +// @Override +// @Transactional +// public void saveBoard(BoardDto dto) { +// MinCivBoard680 entity = null; +// +// // update 인 경우 +// if(Checks.isNotEmpty(dto.getCiCode())) { +// entity = repository.findById(dto.getCiCode()).orElseThrow(() -> new CustomBaseException(ErrorCode.DATA_NOT_FOUND)); +// if(!entity.getCiPass().equals(passwordEncoder.encode(dto.getCiPass()))){ +// throw new CustomBaseException(ErrorCode.MISMATCH_PASSWORD); +// } +// entity.setCiTitle(dto.getCiTitle()); +// entity.setCiContents(dto.getCiContents()); +// }else { +// dto.setCiCode(repository.getCiCode()); +// dto.setCiContentno(dto.getCiCode()); +// if (Checks.isEmpty(dto.getCiRef()) || dto.getCiRef() == 0L) { +// dto.setCiRef(dto.getCiCode()); +// dto.setCiStep(0L); +// dto.setCiRevel(0L); +// } +// dto.setCiPass(passwordEncoder.encode(dto.getCiPass())); +// dto.setCiIp(CommUtil.getDeviceInfo().getIp()); +// entity = mapstruct.toEntity(dto); +// } +// repository.save(entity); +// } +// +// @Override +// @Transactional +// public void removeBoard(Long ciCode) { +// +// MinCivBoard680 savedEntity = repository.findById(ciCode).orElseThrow(() -> new CustomBaseException(ErrorCode.NOT_FOUND)); +// if(!Objects.equal(HeaderUtil.getUserId(), savedEntity.getCiId())) throw new CustomBaseException("삭제 권한(게시글 소유자)이 없는 사용자 입니다"); +// +// // 댓글 존재 여부 조회 +// List list = repository.findByCiRef(ciCode); +// if(list.size() > 1) throw new CustomBaseException("삭제 할 수 없는 게시글 입니다[댓글 존재]"); +// repository.deleteById(ciCode); +// } } diff --git a/src/main/java/com/xit/core/config/EncodingFilterConfig.java b/src/main/java/com/xit/core/config/EncodingFilterConfig.java index 8311be3..657f50a 100644 --- a/src/main/java/com/xit/core/config/EncodingFilterConfig.java +++ b/src/main/java/com/xit/core/config/EncodingFilterConfig.java @@ -1,10 +1,14 @@ package com.xit.core.config; +import com.xit.core.config.support.EucKrEncodingFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.CharacterEncodingFilter; +import java.nio.charset.StandardCharsets; + /** * 기본 UTF-8인데, encoding이 EUC-KR로 들어오는 경우가 있는 경우(외부에서 들어오는 - 결재 등 -) 사용 * spring.http.encoding.force = false 추가 @@ -13,14 +17,28 @@ import org.springframework.web.filter.CharacterEncodingFilter; //TODO :: 기본 UTF-8인데, encoding이 EUC-KR로 들어오는 경우가 있는 경우(외부에서 들어오는 - 결재 등 -) 사용 public class EncodingFilterConfig { + @Bean - public FilterRegistrationBean encodingFilterBean() { - FilterRegistrationBean registrationBean = new FilterRegistrationBean(); + public FilterRegistrationBean encodingFilterBean() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setForceEncoding(true); - filter.setEncoding("MS949"); + filter.setEncoding("euc-kr"); registrationBean.setFilter(filter); - registrationBean.addUrlPatterns("/ms949filterUrl/*"); + registrationBean.addUrlPatterns("/api/v2/*"); return registrationBean; } + +/* + @Bean + public FilterRegistrationBean encodingFilterBean() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + //CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); + //filter.setForceEncoding(true); + //filter.setEncoding("EUC-KR"); + registrationBean.setFilter(new EucKrEncodingFilter()); + registrationBean.addUrlPatterns("/api/v2/*"); + return registrationBean; + } + */ } \ No newline at end of file diff --git a/src/main/java/com/xit/core/config/database/BaseMybatisDaoSupport.java b/src/main/java/com/xit/core/config/database/BaseMybatisDaoSupport.java new file mode 100644 index 0000000..d3fee6f --- /dev/null +++ b/src/main/java/com/xit/core/config/database/BaseMybatisDaoSupport.java @@ -0,0 +1,48 @@ +package com.xit.core.config.database; + +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionTemplate; +import org.springframework.dao.support.DaoSupport; +import org.springframework.util.Assert; + + +public abstract class BaseMybatisDaoSupport extends DaoSupport +{ + + private SqlSession sqlSession; + private SqlSessionFactory sqlSessionFactory; + private boolean extenalSqlSession = false; + + public final void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { + this.sqlSession = sqlSessionTemplate; + this.extenalSqlSession = true; + } + + public final SqlSession getSqlSession() { + return sqlSession; + } + + public final void setSqlSession(SqlSession sqlSession) { + this.sqlSession = sqlSession; + } + + public final SqlSessionFactory getSqlSessionFactory() { + return sqlSessionFactory; + } + + public final void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { + this.sqlSessionFactory = sqlSessionFactory; + if(!this.extenalSqlSession) { + this.sqlSession = new SqlSessionTemplate(sqlSessionFactory); + } + } + + @Override + protected void checkDaoConfig() throws IllegalArgumentException { + Assert.notNull(this.sqlSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required"); + } + + + +} diff --git a/src/main/java/com/xit/core/config/support/EucKrEncodingFilter.java b/src/main/java/com/xit/core/config/support/EucKrEncodingFilter.java new file mode 100644 index 0000000..addea40 --- /dev/null +++ b/src/main/java/com/xit/core/config/support/EucKrEncodingFilter.java @@ -0,0 +1,11 @@ +package com.xit.core.config.support; + +import org.springframework.web.filter.CharacterEncodingFilter; + +public class EucKrEncodingFilter extends CharacterEncodingFilter { + + public EucKrEncodingFilter() { + setEncoding("EUC-KR"); + setForceEncoding(true); + } +} \ No newline at end of file diff --git a/src/main/java/com/xit/core/util/CommUtil.java b/src/main/java/com/xit/core/util/CommUtil.java index 9226261..17101b7 100644 --- a/src/main/java/com/xit/core/util/CommUtil.java +++ b/src/main/java/com/xit/core/util/CommUtil.java @@ -4,6 +4,9 @@ import com.rits.cloning.Cloner; import eu.bitwalker.useragentutils.UserAgent; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.ParameterMapping; +import org.apache.ibatis.session.SqlSession; import org.mozilla.universalchardet.UniversalDetector; import org.springframework.http.ResponseCookie; import org.springframework.mobile.device.Device; @@ -18,9 +21,11 @@ import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLEncoder; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; @@ -645,6 +650,57 @@ public class CommUtil { System.out.println(getRanStrKey(16)); } } + + public static String detectCharset(byte[] bytes) { + UniversalDetector detector = new UniversalDetector(null); + detector.handleData(bytes, 0, bytes.length); + detector.dataEnd(); + String detectedCharset = detector.getDetectedCharset(); + if (detectedCharset != null && detector.isDone() && Charset.isSupported(detectedCharset)) { + return detectedCharset; + } + return detectedCharset; + } + + public static String getMybatisSql(SqlSession sqlSession, String id, Object param) { + BoundSql boundSql = sqlSession.getConfiguration().getMappedStatement(id).getBoundSql(param); + + List parameterMappings = new ArrayList<>(boundSql.getParameterMappings()); + Map parameters = new HashMap<>(); + if (param instanceof Map) { + parameters.putAll((Map) param); + } else { + for (ParameterMapping parameterMapping : parameterMappings) { + try { + String field = parameterMapping.getProperty(); + //try { + String methodNm = "get"+field.substring(0,1).toUpperCase()+field.substring(1); + Method method = param.getClass().getMethod(methodNm); + + parameters.put(field, method.invoke(param)); + //parameters.put(field, param.getClass().getMethod("get"+field.substring(0,1).toUpperCase()+field.substring(1)).invoke(param)); + + } catch (NoSuchMethodException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } catch (InvocationTargetException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + + String sql = boundSql.getSql(); + + for (ParameterMapping par : parameterMappings) { + Object parameter = parameters.get(par.getProperty()); + + if (parameter == null) + sql = sql.replaceFirst("\\?", "NULL"); + else + sql = sql.replaceFirst("\\?", "'" + parameter.toString() + "'"); + } + return sql; + } } diff --git a/src/main/java/com/xit/core/util/mpower/MpowerUtil.java b/src/main/java/com/xit/core/util/mpower/MpowerUtil.java index e8c4eac..8da5ea5 100644 --- a/src/main/java/com/xit/core/util/mpower/MpowerUtil.java +++ b/src/main/java/com/xit/core/util/mpower/MpowerUtil.java @@ -1,5 +1,8 @@ package com.xit.core.util.mpower; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.sql.CallableStatement; import java.sql.Connection; @@ -10,13 +13,12 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.*; -//import org.apache.log4j.Logger; - -//import com.gpki.util.Base64; import com.plf.client.Client; +import com.xit.core.util.CommUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.binary.StringUtils; -//import egovframework.rte.psl.dataaccess.util.EgovMap; - +@Slf4j public class MpowerUtil { //DBName Properties // static String DbName2 = PropertiesUtil.getValue("Globals.DBName"); @@ -42,7 +44,7 @@ public class MpowerUtil { static int firstIndex = 0; static int lastIndex = 10; static int recordCountPerPage = 10; - static String beforeXml = ""; static String afterXmlsp = "]]>"; @@ -210,6 +212,8 @@ public class MpowerUtil { 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"); @@ -634,7 +638,7 @@ public class MpowerUtil { * @ 페이징 처리 SELECT 호출 * @return */ - public Map selectCustomQuery() { + public List> selectCustomQuery() { //EgovMap mListMap = new EgovMap(); Map mListMap = new HashMap<>(); //배열로 넘어온 필드를 String 오브젝트로 변형 @@ -652,14 +656,19 @@ public class MpowerUtil { System.out.println("======"+query); //List mList = new ArrayList(); - List mList = new ArrayList<>(); + List> mList = new ArrayList<>(); int mListCount = 0; try { mpower = new Client(hostip,port); + mpower.setCryptEnable(false); mpower.getConnection("MPowerXmlToQuery.xmlQuery1"); mpower.setInput("SQLXML", query); mpower.Request(); String result = mpower.getString("result", 0, 0); + + System.out.println("#######message = "+mpower.getMessage()); + System.out.println("#######message charset = "+CommUtil.detectCharset(mpower.getMessage().getBytes())); + int row; if (result.equals("true")){ row = mpower.getMaxRow("list1"); @@ -676,7 +685,6 @@ public class MpowerUtil { } mList.add(m); } - mListMap.put("resultList", mList); } } mpower.disconnect(); @@ -686,9 +694,7 @@ public class MpowerUtil { } finally{ clearValidation(); } - String s = String.valueOf(mList); - byte[] b = s.getBytes(StandardCharsets.UTF_8); - return mListMap; + return mList; } @@ -700,91 +706,6 @@ public class MpowerUtil { tmpFeilds = string; } - //단속사진 폴더 및 사진복사 - /*public static String[] fnVioPhoto(String mmCode,String mmDbgb,String photocode,String sessionId){ - String serviceName = "XitFile.XitDownload"; - String[] returnImgStr = new String[4]; - String fph = MpowerUtil.class.getResource("").getPath(); - mpower2 = new Client(hostip,port); - - String tmpPhoto =""; //단속사진 단속구분에 따라 경로변경 - if(mmDbgb.equals("11")){ - tmpPhoto =vioPhoto; - }else{ - tmpPhoto = vioPhotoBus; - } - - - 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 imgPath = tmpPhoto + EgovStringUtil.Get_M_ImgFD(photocode) + "/" + EgovStringUtil.Get_C_ImgFD(photocode) + "/" + EgovStringUtil.Get_B_ImgFD(photocode); //터널링에 저장된 단속사진 경로 - System.out.println("최종이미지경로:::::" + imgPath); - - try{ - mpower2.getConnection(serviceName); - mpower2.setInput("dnfile1",imgPath+ "/P" + EgovStringUtil.ZeroCnt(photocode) + "A.jpg"); //터널링에 실질 존재하는 경로,파일명 - System.out.println("사진이름:" + EgovStringUtil.ZeroCnt(photocode)); - mpower2.setInput("dnfile2",imgPath+ "/P" + EgovStringUtil.ZeroCnt(photocode) + "B.jpg"); - mpower2.setInput("dnfile3",imgPath+ "/P" + EgovStringUtil.ZeroCnt(photocode) + "C.jpg"); - mpower2.setInput("dnfile4",imgPath+ "/P" + EgovStringUtil.ZeroCnt(photocode) + "D.jpg"); - mpower2.Request(); - String result = mpower2.getString("result", 0, 0); - - if (result.equals("true")){ - mpower2.getFileName("imageA"); - mpower2.getFileName("imageB"); - mpower2.getFileName("imageC"); - mpower2.getFileName("imageD"); - mpower2.savefile("imageA", fph); - mpower2.savefile("imageB", fph); - mpower2.savefile("imageC", fph); - mpower2.savefile("imageD", fph); - - String strpath = "/vioPhoto/"+sessionId+"/P" + EgovStringUtil.ZeroCnt(photocode); - System.out.println("strPath ::: " + strpath); - returnImgStr[0] = strpath + "A.jpg"; - returnImgStr[1] = strpath + "B.jpg"; - returnImgStr[2] = strpath + "C.jpg"; - returnImgStr[3] = strpath + "D.jpg"; - } - }catch(Exception e){ - - } - //logger.debug(fph); - return returnImgStr; - }*/ - - //버스단속사진 - /*public static String[] fnVioPhotoBus(String photocode, String sessionId) { - String fph = MpowerUtil.class.getResource("").getPath(); - fph = fph.replace("WEB-INF/classes/xit/cmmn/utill/", "vioPhoto/"+sessionId+"/"); - String[] imgFmn = {"A","B","C","D"}; - String[] imgFile = new String[4]; - try{ - File d = new File(fph); - if(!d.isDirectory())d.mkdir(); - for (int i = 0; i < imgFmn.length; i++) { - String imgPath = EgovStringUtil.Get_M_ImgFD(photocode) + "/" + EgovStringUtil.Get_C_ImgFD(photocode) + "/" + EgovStringUtil.Get_B_ImgFD(photocode); - String url = "http://211.35.57.16/bus_photo/"+imgPath+"/P" + EgovStringUtil.ZeroCnt(photocode) + imgFmn[i] +".jpg"; - - System.out.println(" 최종 URL ::: " + url); - - BufferedImage img = ImageIO.read(new URL(url)); - File f = new File(fph + photocode + imgFmn[i]+".jpg"); - ImageIO.write(img, "jpg", f); - imgFile[i] = "/vioPhoto/"+sessionId+ "/"+ photocode + imgFmn[i]+".jpg"; - System.out.println(imgFile[i]); - } - }catch(Exception e){ - - } - return imgFile; - - }*/ - //첨부파일 터널링 서버로 복사 public void fnFileUpload(String tmpFileLocation,String realRcRilenm){ @@ -830,22 +751,4 @@ public class MpowerUtil { //logger.debug("웹서버 저장되는 첨부파일 위치:"+fph); System.out.println("웹서버 저장되는 첨부파일 위치:"+fph); } - - /*private static String fileToBinary(String tmpImg1) { - // TODO Auto-generated method stub - //logger.debug(tmpImg1); - String encodedImage = null; - try { - BufferedImage image = ImageIO.read(new File(tmpImg1)); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.write(image, "png", baos); - encodedImage = Base64.encode(baos.toByteArray()); - // logger.debug(encodedImage); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - encodedImage = ""; - } - return encodedImage; - }*/ } diff --git a/src/main/java/com/xit/core/util/mpower/MpowerUtils.java b/src/main/java/com/xit/core/util/mpower/MpowerUtils.java new file mode 100644 index 0000000..c256ca2 --- /dev/null +++ b/src/main/java/com/xit/core/util/mpower/MpowerUtils.java @@ -0,0 +1,465 @@ +package com.xit.core.util.mpower; + +import com.plf.client.Client; +import com.xit.core.util.CommUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.binary.StringUtils; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.ParameterMapping; +import org.apache.ibatis.session.SqlSession; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.sql.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +public class MpowerUtils { + //DBName Properties +// static String DbName2 = PropertiesUtil.getValue("Globals.DBName"); + static String DbName2 = "gn"; + + + Client mpower = null; + static String hostip = "127.0.0.1"; + static int port = 9999; + static String query = ""; + static ArrayList feilds = new ArrayList(); + 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 = ""; + + + + //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){ + MpowerUtils.query = query; + } + + public void setFeild(String feildNm){ + feilds.add(feildNm); + } + + public int getFirstIndex() { + return (pageIndex - 1) * recordCountPerPage +1; + } + + public int getLastIndex() { + return lastIndex = pageIndex * recordCountPerPage; + } + + public List> selectQuery() { + String fileList = ""; + for(int cnt = 0;cnt mList = new ArrayList(); + List> mList= new ArrayList>(); + + 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 m = new HashMap<>(); + for(int j=0;j(); + tableNm = ""; + WhereStr = ""; + Orderby = ""; + } + + return mList; + } + + private void clearValidation() { + query = ""; + feilds = new ArrayList(); + tableNm = ""; + WhereStr = ""; + Orderby=""; + psParamCount = 0; + QueryXml = ""; + Params = ""; + psFinalFarams = ""; + recordCountPerPage = 10; + feild = ""; + } + + + /** + * @ 페이징 처리 SELECT 호출 + * @return + */ + public Map selectListQuery() { + //EgovMap mListMap = new EgovMap(); + Map mListMap = new HashMap<>(); + //배열로 넘어온 필드를 String 오브젝트로 변형 + String fileList = ""; + for(int cnt = 0;cnt(); + this.setFeilds("RN, "+tmpFeilds); + } + + //List mList = new ArrayList(); + List> 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 m = new HashMap<>(); + for(int j=0;j0){ + 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 selectListQueryNew() throws SQLException { + //EgovMap mListMap = new EgovMap(); + Map mListMap = new HashMap<>(); + //배열로 넘어온 필드를 String 오브젝트로 변형 + String fileList = ""; + for(int cnt = 0;cnt(); + this.setFeilds("RN, "+tmpFeilds); + } + + //List mList = new ArrayList(); + List> mList = new ArrayList>(); + 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 m = new HashMap<>(); + if(!chpoint) + { + for(int j=0;j> selectCustomQuery() { + //EgovMap mListMap = new EgovMap(); + Map mListMap = new HashMap<>(); + //배열로 넘어온 필드를 String 오브젝트로 변형 + String fileList = ""; + for(int cnt = 0;cnt mList = new ArrayList(); + List> mList = new ArrayList<>(); + int mListCount = 0; + try { + mpower = new Client(hostip,port); + mpower.setCryptEnable(false); + mpower.getConnection("MPowerXmlToQuery.xmlQuery1"); + mpower.setInput("SQLXML", query); + mpower.Request(); + String result = mpower.getString("result", 0, 0); + + System.out.println("#######message = "+mpower.getMessage()); + System.out.println("#######message charset = "+CommUtil.detectCharset(mpower.getMessage().getBytes())); + + + int row; + if (result.equals("true")){ + row = mpower.getMaxRow("list1"); + if(row>0){ + for(int i=0;i m = new HashMap<>(); + if(!"".equals(feild) && feild != null){ + m.put("cbContent", mpower.getString("list1", i, 4)); + }else{ + for(int j=0;j + + + + + + + \ No newline at end of file