F,P,S & FunctionalInterface

java8~ 2016. 10. 23. 11:20

  

java 8 경험자 Tip:   REF-SITE ,  http://okky.kr/article/357825  


 

1. Object리턴시에  null처리가 쉽도록, Optional.ofNullable() 사용.

   예제)  

           Optional<Soundcard> soundcard = Optional.ofNullable(mabyeSoundcard); 
           if(soundcard .isPresent())

   System.out.println (soundcard.get()); //get Real Value from Optional

또는

soundcard.ifPresent(System.out::println); 도 OK.

soundcard.ifPresent(card -> map.put(card)); 도 가능.


      Soundcard soundcard = mabyeSoundcard.orElse(new Soundcard("defaut"));

- orElseThrow(IllegalStateException::new); 도 가능

 

Optional.map(s->s.getID()).orElse()도 굿.  orElseGet( blabla) 도 있음. 

Optional.flatMap : content가 또 Optional일경우 벗김-  REF2번참조


 

2.  mutable인 String[]리턴 대신에, immutable인 Stream<String> 리턴.  REF-SITE

  

Stream<String> words = Stream.of("Java", "Magazine", "is", "the", "best");

or

Stream<String> words = Arrays.stream(arrOfStr); //String[] arrOfStr = {"A","BB"}

 

 

   예제) "hey duke".chars().forEach (c -> System.out.println((char)c));

           Stream<Character> sch = "abc".chars().mapToObj(i -> (char)i);     (char)가 Character로 autobox됨.


 

3. Function Reference & Predicate Reference. (함수의 파라미터로도 넘길 수 있게 됨)

   

   Predicate의 경우 scala와 거의 유사한 방식으로. boolean리턴하는 method define후, 이 것들을 넘길 수 있음. 

 


  Function<String, Integer> f = Integer::parseInt;
  Integer result = f.apply("123");

 

  Predicate<String> p = str::equals;
  p.test("world");

 

 Supplier< > s = 

 s. get(); 

 


 4. interface  : 기존 interface를 좀 다르게 FunctionalInterface로 사용가능. @FunctionalInterface 도 존재.

   => 이걸 파라미터로 넘길수도 있다.  (function도 넘길 수 있듯이)  : 음 class도 넘길수 있으니 당연한 건가..

   

    FunctionalInterface REF -> abstract Method는 한개만 존재

    javaInAction8책에서는 Validator Strategy및 8.2장 참조.




Posted by yongary
,

mySql Tip

BACK-END 2016. 10. 12. 17:00

참고: mySql에서 

  - Key키워드도 index를 의미한다.  

     (왜 key라고 부르면서 index와 동일한 건지? 이유가 있을텐데.. 아직은 모르겠음)


 

mySQL을 쓰면서 하면안되는 일들 17가지 blog : REF

 

요약하면

- 파티션/복제/Caching계획을 세우기

- Explain포함 Profile링과 벤치마크 쓰기

- 인덱스 layout과 쿼리 cach 이해하기

- Stored procedure보다는 Prepared구문&Dynamic SQL사용

  (MySQL은 한번 연결해서 여러번 사용해야 효율 적)

- AUTO_INCREMENT 꼭 사용

- ON DUPLICATE KEY UPDATE 꼭 사용

 

정도이다.

 

시간을 가지고 개인적인 의견 하나씩 추가 계획.

 

 

Posted by yongary
,

구글 SLAM 공개

IT 2016. 10. 11. 13:39

구굴이 SLAM(Simultaneous Localization and Mapping)용

오픈소스 지도기술 Cartographer를 공개하였다.



SLAM: 로봇이 위치를 인식해서 즉석해서 지도를 작성.

- 무인자동차, 로봇청소기, 드론등에서 활용



이제 일반인도 드론이나 로봇청소기 제작시 본 API를 활용해

야외나 실내의 맵을 실시간으로 만들어 

로봇의 탐색경로를 쉽게 최적화할 수 있을 것으로 보인다.



참고사이트: http://www.bloter.net/archives/265140

시연영상: https://youtu.be/DM0dpHLhtX0 

Cartographer GitHub: https://github.com/googlecartographer 

                  소개: https://opensource.googleblog.com/2016/10/introducing-cartographer.html 





Posted by yongary
,

auto login + data Add

java core 2016. 10. 7. 17:55

java로 web페이지에 login을 해서 session을 유지하면서

data를 form방식으로 입력하는 예제입니다. 


(login페이지는 ajax/json리턴 방식이고, data add 페이지는 일반적인 form방식을 가정)

login세션 유지는 cookie에서 JESSIONID를 읽어서 다시 세팅해야 합니다.



data는 file에서 하나씩 읽어서 web상으로 입력하는 형태입니다.


=========java source=====================

import java.io.BufferedReader;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.List;

import java.util.Map;

import java.util.Scanner;



public class LoginAndInsert {


public static void main(String[] args) throws Exception{

//LOG IN

URL url = new URL("http://221.100.200.180/loginProc");

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setUseCaches( false );

conn.setConnectTimeout(1000);

conn.setRequestProperty("Accept", "*/*");

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

conn.setRequestMethod("POST");


//data setting

String postData = "user_id=admin" + "&user_pwd=" + "a123456789";

System.out.println(postData.toString());

conn.setRequestProperty("Content-Length", String.valueOf(postData.getBytes("UTF-8").length));

conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

conn.setDoOutput(true); //POST

conn.connect();

OutputStream outputStream = conn.getOutputStream();

outputStream.write(postData.getBytes("UTF-8"));

outputStream.close();

InputStream inputStream = null;

try { 

inputStream = conn.getInputStream();

}catch (IOException ioe){

ioe.printStackTrace();

}


String m_cookies = "";

String line3;

      BufferedReader reader = new BufferedReader(new 

                                    InputStreamReader( inputStream  ));

      while ((line3 = reader.readLine()) != null) {

         System.out.println(line3);

      }

   

      //save Cookie


      Map<String, List<String>> imap = conn.getHeaderFields( ) ;

      System.out.println(imap.size());

   

   

 if( imap.containsKey( "Set-Cookie" ) ) //"Set-Cookie"

 {

    List<String> lString = imap.get( "Set-Cookie"); //"Set-Cookie" );

    for( int i = 0 ; i < lString.size() ; i++ ) 

    m_cookies += lString.get( i ) ;

 }

   

       System.err.println("Cookie:"+ m_cookies);

   

 //find JSESSIONID

 String[] cookieTokens = m_cookies.split(";");

 String JSESSIONID = cookieTokens[1].substring( cookieTokens[1].indexOf("D=")+2 );

   

 System.err.println("JSESSIONID:"+ JSESSIONID);

   

 reader.close();

 Thread.sleep(500);


//Data process

Scanner in = new Scanner(new File("./dataFile.txt"));

int i=0;

while ( in.hasNextLine() ){

String line = in.nextLine();

//System.out.println(line);


String[] token = line.split(",");

String id = token[0];

String phone = token[1];

String name = token[2];

String pw = "tel" + phone.substring(3);

if (id.length() < 4) System.err.println(id);

if (pw.length() < 10) System.err.println(pw);


//INSERT by POST

url = new URL("http://221.148.199.79/admin/normalUserMng/registProc");

conn = (HttpURLConnection)url.openConnection();

conn.setUseCaches( false );

conn.setConnectTimeout(1000);

conn.setRequestProperty("Accept", "*/*");

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

conn.setRequestMethod("POST");

conn.setRequestProperty( "Cookie", "JSESSIONID="+JSESSIONID );

conn.setInstanceFollowRedirects(false); //For cookie


//data Setting

postData = "act=R" 

+ "&user_id=" + id

+ "&user_pwd=" + pw

+ "&user_name=" + name

+ "&user_phone=" + phone

+ "&is_active=1"

+ "&user_domain=ktait.com";

conn.setRequestProperty("Content-Length", String.valueOf(postData.getBytes("UTF-8").length));

System.out.println(i++ + "====== "+name + "," + id + "," + phone + "," + pw +",     "+ postData);

conn.setDoOutput(true); //POST

//conn.setDoInput(true); //POST

conn.connect();

outputStream = conn.getOutputStream();

outputStream.write(postData.getBytes("UTF-8"));

outputStream.close();


String line2;

reader = new BufferedReader(new 

                                    InputStreamReader(conn.getInputStream()));

while ((line2 = reader.readLine()) != null) {

     System.out.print(line2);

}

reader.close();

System.out.println("");

Thread.sleep(100);

}

  }

}



Posted by yongary
,

한국과 일본 LTE

통신 2016. 9. 27. 14:02

한국과 일본의 LTE 주파수가 겹치는 부분도 있고, 다른 부분도 있지만

대체적으로 겹치는 부분이 존재하기 때문에,

 

한국폰을 들고 일본에 가서 가입해서 사용할 수 있다.

(보통 APN을 설정해야 한다.

  - APN: AP의 명칭으로 data망을 잡을 때 사용하는 중계기이름) : 설정경험site

 

 

<주파수 설정>

주파수가 다르지만 자동으로 되는폰과 안되는 폰이 있는데, 자동으로 LTE가 안잡히는 폰은 설정을 할 수 있다.

 

KT스마트폰 삼성폰인 경우  자동으로 안되면

통화 dialer에서 319712358 입력하고 비번에서 774632 입력하면 된다.

 

=> 그 후, Network Setting -> Network Mode에가서

일본 LTE주파수 참고해서 고르면 된다.  도코모의 경우 B1으로 선택하면 된다. 아니면 자동으로

 

    LG폰:  5457#* + 모델명3자리 + #      (5457대신 3845인 폰도 존재)

    펜텍폰:  ##7788#

 

<일본 MVNO>

 

B모바일 = 도코모의 mvno  :  개통경험사이트

=> B모바일은 15년 2월 기준으로 속도가 느림: site

빅심(IIJmio) = 도코모의 mvno  : 좀 믿을만 하겠죠.

 

라인mobile = 도코모mvno : 라인free와 커뮤니케이션free(facebook포함) 요금제 존재. : site

               -> 라인mobile 정식오픈은 16년 10월 1일.  메신저 많이 쓰는 사람 이게 유리할 듯하네요
               요금제 + (월)700엔 내야지 전화번호까지 줌. 

 

 

<참고 사이트>

일본 LTE주파수 - 참고사이트

 

한국LTE 주파수-  참고사이트

 

일본 MVNO 비교 - 참고 사이트

 

SKT폰도 비번만 다르고 동일함 - 참고사이트

 

 

Posted by yongary
,

netty

network개발 2016. 9. 26. 13:49

netty =  Async전문 java network Library

   - UserGuide(4.0 wiki)  ,  한글번역본

 

   - 3.1 Chapter2 Architecture Overview

 

   - 4.0javadoc   5.0alpha2_javadoc

 

 

netty의 핵심 Interface

 - Channel

 - ChannelFuture

 - ChannelHandler

 - ChannelHandlerContext

 - ChannelPipeline

 - EventLoop

 

 [그 외]

 - ChannelBuffer

 기존 java nio의  ByteBuffer를 쓰지 않고, ChannleBuffer를 이용해
1. flip()호출이 필요없으며 사용자정의 buffer type이 가능하다.

2. zero-copy가 가능하다.(SG-DMA NIC필요) :  zeroCopyRef

zero-copy: disk->커널메모리->유저메모리->커널메모리->NIC  이던것을

               => disk->커널메모리->NIC 방식으로 copy. (File을 socket으로 쏠때 특히 유리)

3. StringBuffer처럼 dynamic Buffer이다.

 - ChannelFactory

NIO-TCP / OIO-TCP / OIO-UDP /Local 통신등을 ChannelFactory선택만으로 쉽게 swithcing가능.

 

기본예제: jdm.kr

 

 

Posted by yongary
,

[Netflix 블로그:  곧 open Source로 공개 예정]

http://techblog.netflix.com/2016/09/zuul-2-netflix-journey-to-asynchronous.html?m=1 

 

 

Posted by yongary
,

Git advanced.

springBoot gradle 2016. 9. 12. 15:21

git기본은: http://yongary.tistory.com/151




http://learngitbranching.js.org/   graphical 공부site


  - git의 commit은 매우 가볍다. 이전버전과 차이점 delta만 관리. 

  - local 관리버전을 master라고 부름.. (remote가 origin 인 듯)

  - branch는 단지 commit으로의 pointer이다. (storage/memory overhead없음)

git branch branchName해서 만들고 + git checkout branchName 한 다음에 git commit해야 함. 

: or  git checkout -b branchName 하면 branch를 만들면서 checkOut도 같이 함.

  - git merge 방법:

: git branch bugFix

:    git checkout bugFix

:    수정후 git commit

: git checkout master

:    git commit  (이 단계가 왜 필요한지?? 연구 중)

:    git merge bugFix

   

  - git rebase : 패러랠 branch작업을 sequential한 history로 변환시켜 줌. (대단하네요)

              현재 bugFix* checkout된 상태에서, 

: git rebase master 하면 sequential로 되고 그 후,  (현재 bugFix*가 계속유지됨.)

: git rebase bugFix   (master*가 current로 바뀜. sequential상에서의 merge효과가 생김. ) 

      


           

<기억할 명령어>

git checkout FileName  : 파일 하나 Revert

git checkout -- FileName  :  파일 하나 Revert from -- branch. (need test)  REF



git branch -v :  branch상태 확인가능.. 로컬이 앞서가면(commit 이 많으면 ahead 2 이런식으로 나옴)  : REF

==>  $ git fetch --all; git branch -w   이렇게 사용해야 최신 정보가 비교가 됨.



Posted by yongary
,

<동작구조>


Request --->  DispatcherServlet  ---------------------------> Haldlermapping

                                     ----------------------------> Controller

                                     <--Model & view name--

                                     ---------------------------->ViewResolver

                                     ----------------------------> View

      response <--------------------------------------------



<어노테이션>  annotation-Driven.   @Component로 하고,  component-scan으로 자동으로 Bean으로 등록. 

  @Controller

  @RequestMapping( { "/", "/homepage" } )   =>  controller에서 이 String array를 통해 여러 request 수용가능.

  public class myController {....


 

  -param 처리  /show?my_id=12345 URL처리하려면

   public String show( @RequestParam("my_id") long myId, Model model) {
   }

  - URL방식 param처리

   @RequestMapping(value="/{my_id}", method=RequestMethod.GET)
   public String show( @PathVariable("my_id") long myId, Model model) {

   }





<Spring's MockMVC>

  myRepository mockRepository =

     mock (myRepository.class);

   when (mockRepository.findData())

     .thenReturn(expectedData);


     .setSingleView  .build  .perform  .andExpect 등.   



<Web controller에>

 @Autowired 생성자. 가능.    #146 



  Model: View로 전달할 key,value Map.이며 아래와같이 사용함.

   <c:forEach  items="${modelName}" var="oneData">

<c:out value="${oneData.kv1}" />

   </c:forEach>

   => spring에서 만든 sf (spring form) tag library도 존재.
    sf:input 이런식으로 사용하며 Model과 연동이 잘된다. 

   => srping에서 만든 s tag library도 존재

    s:message   리소스 파일등에서 읽어서 메시지 출력.




<ViewResolver>

  InternalResourceViewResolver를 기본적으로 쓰는데, 그 외 UrlBasedViewResolver, XmlViewResolver, 

  TilesViewResolver (Apache Tiles를 이용해 Web페이지 구성, tiles는 t tagLib 사용.),

  ThymeleafViewRelolsver ( Tyhymeleaf = jsp 사용성 개선한 범용 template-th tag 사용하며 html처럼 막 편집가능
        즉, jsp안에 <> <c:> 이런거 섞어쓰면서 오는 <>개수 혼란 등을 피할 수 있음.)
  
  등 10개 이상의 용도에 따른 ViewResolver가 존재한다.

 

 

<기타 & Advanced>

WebApplicationInitializer

- DispatcherServlet 외에 추가적인 servlet나 filter를 등록해서 사용가능.

- onStartup & getServletFilters 메쏘드 override .   (#7.1)

 

multipart는 보통 StandardServletMultipartResolver 를 사용.

 

 

flash attribute: redirect시 Object전달 같은 일회성 data전달을 model을 이용해 지원.

-사용법: model.addFlashAttribute("spitter", spitter);

 


 Web Flow:  spring MVC확장 framework로 flow를 관리한다.

     - status, transitions, flow_Data 의 3개 요소로 구성됨.



Posted by yongary
,

AsyncFileChannel

java core 2016. 8. 28. 21:24

[오늘의 Tip] Java는 call by value이다. (Object의 경우는 reference주소=Pointer주소 가 전달된다)

c++은 call by reference가 있는데, 이 것은 실제로는 reference of reference가 전달된다.



[본론]


jdk 1.7 에 AsynchronousFileChannel class가 있다.  REF


그냥 java 의  NIO를 사용해도 될텐데.. 차이점이 무언인지 분석을 해보자.



..




Posted by yongary
,