REF


위의 REF를 참조해서 아래와 같이 string으로 변경하면

mySql에서 바로 사용이 가능하다. 



Clock clock;

DateTimeFormatter DB_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

String alarmTime = dateTime.format(DB_TIME_FORMAT);



String alarm2 = LocalDateTime.now(clock).format(DB_TIME_FORMAT)


그리고, LocalDateTime을 바로 MySQL에 저장도 가능한데.. (음 이게 더 나아보인다)


단, 이때 String 을  LocalDateTime으로 변환필요시가 있을때에는

"yyyy-MM-ddTHH:mm:ss") 형태를 사용해야 한다.   ( T가 중요)

Posted by yongary
,

몇몇 Annotation

Spring 2017. 3. 9. 18:48

 @ModelAttribute on a method argument -  indicates the argument will be retrieved from the model. If not present in the model, the argument will be instantiated first and then added to the model.


@Retryable (a.Exception, b.Exception 지정가능. 미지정시 상시.. )


@Recover (a.Exception) : a.Exception으로 실패시에에만 호출되어서.. 특별한 뒷처리 및 로그작업등 가능.



@Component( name부여가능 )


@Profile("profile_name")  - name에 해당하는 profile이 active일 때만, Bean이 생성됨. dev test등 주로 이용.


@Conditional - 조건부 Bean생성. 


@GatherJob    (USER_Defined)

  - 나중에 모으고 싶은 것들을 임의로 선언한다. (class는 있어야 죠 , 간단한 빈깡통 Interface면 됨.)

Set<Class<?>> gather = New Reflections(My.class.getPackage().getName())

.getTypesAnnotatedWith(GatherJob.class);


@Qualifier("my name") - 

Posted by yongary
,

REF


Mokito의 ArgumentCaptor를 사용해, insert/update같은 동작을 간단하게  hooking할 수 있다.


(예제)

final ArgumentCaptor<Ticket> logCaptor = ArgumentCaptor.forClass(Ticket.class);
verify(chatTicketRepository).update(logCaptor.capture());
Ticket ticket = logCaptor.getValue();

assertThat(ticket.getStatus(), is(TicketStatus.EXPIRED));



좀 더 복잡한 경우는, ArgumentMatcher를 이용해 복잡한 비교를 할 수 있다. 



파라미터를 hooking하는 다른방법: REF

when(mockObject.myMethod(any(parameterClass.class))).thenAnswer(
                invocation -> invocation.getArgumentAt(0, parameterClass.class));


Posted by yongary
,

MySQL 시간 비교

BACK-END 2017. 3. 2. 16:30

REF


시간비교시에는 MySQL의 INTERVAL 을 이용하는 것이 가장 편한 것으로 보인다.


예)

WHERE

myTable.datetimefield > now() - INTERVAL 3 DAY (or MONTH or WEEK ) 

==> 그러나, 날짜간에는 빼기 보다는  DATE_SUB를 사용해야 하고.


BETWEEN도 사용이 가능하지만,.. 작은 날짜를 앞에 써야 한다.

WHERE my_date BETWEEN DATE_SUB(now(), INTERVAL 1 WEEK) AND now()

참) 그리고 NULL을 비교할때는,  IS NULL   또는  IS NOT NULL 을 사용해야 한다.



그 외 Doma라는 ORM에서 IF와 같이 쓰는 경우엔 다음과 같이 섞어서 사용할 수도 있다.

service.service_code
/*%if sortKey == @com.linecorp.fortune.constant.ServiceSortKey@NEW */
, IF ( NOW() - INTERVAL 1 WEEK < forum_service.published_at, 1, 0) as is_new
/*%elseif sortKey == @com.linecorp.fortune.constant.ServiceSortKey@ANSWER_TIME */
, IF (forum_service_condition.average_answer_time = 0, 12, forum_service_condition.average_answer_time) as answer_time
/*%end*/


Posted by yongary
,

스프링으로 주기적으로 도는 함수를 만들고 싶으면... 


아주 간단하게


public 함수위에 

@Scheduled(cron = "0 39 */2 * * *")와 같이 선언하면 된다.



아래는 매일 2시 49분에 도는 함수!


@Scheduled(cron = "0 49 2 * * *")

참고:  제일앞자리는 cron에 없는거네요.. 용도는?  초.   */30 이러면 매 30초마다임.  REF

   

초 0-59 , - * / 

분 0-59 , - * / 

시 0-23 , - * / 

일 1-31 , - * ? / L W

월 1-12 or JAN-DEC , - * / 

요일 1-7 or SUN-SAT , - * ? / L # 

년(옵션) 1970-2099 , - * /

* : 모든 값

? : 특정 값 없음

- : 범위 지정에 사용

, : 여러 값 지정 구분에 사용

/ : 초기값과 증가치 설정에 사용

L : 지정할 수 있는 범위의 마지막 값

W : 월~금요일 또는 가장 가까운 월/금요일

# : 몇 번째 무슨 요일 2#1 => 첫 번째 월요일



<cron 은    REF 참조>


crontab 파일 형식
------    --------  ---------------------------------------------------
필  드    의  미    범  위
------    --------  ---------------------------------------------------
첫번째    분        0-59
두번째    시        0-23
세번째    일        0-31
네번째    월        1-12
다섯번째  요일      0-7 (0 또는 7=일요일, 1=월, 2=화,...)
여섯번째  명령어    실행할 명령을 한줄로 쓴다.
------    --------  ---------------------------------------------------


예) 5  */2 *  *  * 명령어 => 매일 2시간간격으로 5분대에 

Posted by yongary
,

mysql Enum

BACK-END 2017. 2. 20. 15:35

(테이블 생성시)

  `type` ENUM('paid', 'free') NOT NULL,


(Insert 시) 'String'을 넣거나 index 숫자를 넣을 수도 있음.




Enum 전반적인 설명-REF1:

   

  - 잘못된 값 삽입시 "" 이 삽입됨. index=0

  - NULL은 index도 null임

  - 일반적인 index는 1부터 시작됨. 



Enum을 Where절에 사용:  REF


  -  index 사용시에는 잘 되지만, 일반적으로 사용시에는 string순서로 비교된다.


Posted by yongary
,

MySql Row Lock

Spring 2017. 2. 19. 23:14

InnoDB Lock: REF



엔진확인 

   mysql> show engines;

   mysql> show variables;   (autocommit등의  Variables 확인) 



Spring 의 @Transactional과 함께 사용하면 autcommit이 일반적으로는 자동으로 풀렸다가 다시 설정 된다..  REF(Stack-overFlow)  REF



=======================================


Mysql에서 엔진이 innodb(요즘 보통다 이러함)일 경우, row level lock이 지원된다.REF


- start transaction   -> 작업 ->  commit 순으로 수행하면 된다.


start transaction;

select * from sales_item where id=99  lock in share mode;

commit; 



transaction도중에 다른 작업이 또 들어오면

  1. wait이 되거나 (위 REF 참조)

  2. 자동으로 에러가 나서 거절이 되는데..  

(1,2번 중 원하는 데로 선택을 어떻게 하는지 ... 연구 중)



 select for update도 있긴한데.. 한 문장 밖에 안되므로 좀 활용도가 떨어지지만
 spring의 @Transactional과 같이 사용하기에 유리하다.    REF


일단 설정 파일에서
init_connect = 'set autocommit=0'
으로 설정하여 오토커밋을 해제합니다. 기본적으로 mySQL 설치 시엔 오토커밋일 설정되어 있습니다



innodb_lock_wait_timeout 확인 방법.

show variables like '%wait_timeout%';

Posted by yongary
,

MockMvc결과가 문자열 json일 때 쉽게 체크하는 법은 jsonPath를 사용하는 방법. REF



그러나, 결과가 Attribute내에 Object 등으로 오는 경우가 많은데..

이럴 경우에는 org.hamcrest.Matchers 를 사용하면 좋다.



<Attribute가 단순 String일 경우>

.andExpect(model().attribute("ReserveResult", org.hamcrest.Matchers.containsString("rtncd=0000")));



<(result내의 Model)  AttributeJson Object일 경우> org.hamcrest.Matchers.CustomMatcher를 사용한다.

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

//Check if rtncd="0000"
Matcher< ResultClass > resultMatcher = new CustomMatcher< ResultClass >("") {
public boolean matches(Object object) {
return ((object instanceof ResultClass) && ((ResultClass) object).getRtncd().equals("00"));
}
};

mockMvc.perform(request)
.andDo(print())
.andExpect(status().is3xxRedirection())
.andExpect(model().attribute("reserveResult", resultMatcher));


Posted by yongary
,

<module-js> REF

Single Page Web Application에서 표준화를 해주는 라이브러리이다.

아래의 browserify와 함께 스면 좋다. 




<browserify> REF


  node코드들을 browser에서도 쓸 수 있게 해주는 library이다.


    간단히 설치:

    $npm install -g browserify 


  대표적으로   require('modules') 코드를 script 안에서 많이 쓴다.


Posted by yongary
,


========node와 연계해서 빌드도 가능===========REF

spring과 npm을 연계해서 빌드시에,


$npm run build:js  등으로 package.json을 이용해 직접 build명령을 내릴 수도 있다.



npm  REF

  - npm은 필요모듈 설치시, 글로벌설치/로컬설치 가능. 일반적으로는 로컬설치가 좋지만 선택이 어려울경우가 있다.

   

npm 환경설정 npm   


각종  npm 패키지 명령:  REF

   - npm list browserify

   - npm view browerify version ( 최신버전확인)

   - npm remove browserify

   - npm install (-g) browserify   (-g: global)




<빌드 LifeCycle>: REF

default 빌드 LifeCycle은 다음과 같다.

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • verify - run any checks on results of integration tests to ensure quality criteria are met
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.


아래와 같이 springBoot 실행도 가능.

$mvn springboot run  REF


------------------------------------------------------------------------------------------------------------


=====maven 확인========  REF

$mvn -version


없으면 mac의 경우에는 brew install maven



=======BUILD+package=============== REF

$mvn package


빌드 에러메시지를 상세히 보고 싶다면


$mvn -e -X package  




===기본설명===

spring 에서   pom.xmL을 이용해 maven 의존성 관리를 한다.


maven을 직접사용하는 방법도 있는데

maven 설치 후


mvn archetype:generate     해서 각종 값을 넣고 나면 (주로  package 명으로 넣으면된다)

pom.xml까지 자동 생성이 되며,


mvn compile exec:java -Dexec.mainClass=com.ky.App

 으로 바로 커맨드 상에서 실행한다.


매우 유용하다. 



=== MOJO ============


MOJO : Maven plain Old Java Object 이다.    REF

            - maven의 java-plugin을 만드는데 사용된다.


만들때는 @Mojo를 써서 간단히 만들 수 있다는데, 만들일 은 잘 없고.. 쓸 일은 많으니.. .. 쓸 때 위주로 보면.


groupIdThis is the group ID for the plugin, and should match the common prefix to the packages used by the mojos
artifactIdThis is the name of the plugin
versionThis is the version of the plugin
packagingThis should be set to "maven-plugin"
dependenciesA dependency must be declared to the Maven Plugin Tools API to resolve "AbstractMojo" and related classes


plugin내의  mojo를 실행시키려면  

  - "$mvn sample.plugin:hello-maven-plugin:1.0-SNAPSHOT:sayhi" 로도 가능하다.

       ($mvn groupId:artifactId:version:goal )


Posted by yongary
,