학습자료/Java 2015. 7. 22. 10:11

자바에는 기본적으로 ScheduledJob과 Timer 이용하여 간단한 스케줄링이 가능하다.

하지만 30분 마다 0에 , 월요일부터 금요일까지 와 같이 디테일하게 스케줄링은 하기 어렵다.

리눅스에 crontab 이라는 스케줄링 데몬이 있는데 자바에서 그와 같은 동작을 하는 라이브러리를 사용하겠다.


crontab 사용

예)

20  2     *  *  6  명령어 => 매주 토요일 새벽 2:20

0  4-6   *  *  *  명령어 => 매일 오후 4,5,6시

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

15  1   1  *  *  명령어 => 매월 1일 새벽 1:15

30  0   1  1,7  *  명령어 => 1,7월 1일 새벽 0:30


quartz 라이브러리 다운로드(2.2.1)

http://quartz-scheduler.org/downloads



quartz 크론 표기법

http://quartz-scheduler.org/api/2.2.0/org/quartz/CronExpression.html

Field Name Allowed Values Allowed Special Characters
Seconds 0-59 , - * /
Minutes 0-59 , - * /
Hours 0-23 , - * /
Day-of-month 1-31 , - * ? / L W
Month 1-12 or JAN-DEC , - * /
Day-of-Week 1-7 or SUN-SAT , - * ? / L #
Year (Optional) empty, 1970-2199 , - * /


1.  main class (스케줄러에 job 등록, job에 데이터 바인딩, 스케줄러 주기 세팅)

public class CronTest {

public CronTest() {

try {

ArrayList state = new ArrayList<String>();

//주기적으로 실행시클 job 클래스 등록

//job 클래스는 생성자에 인자가 들어가면 안됨, inner class로 생성하면 안됨.

//job 클래스에 데이터 전송

JobDetail job = JobBuilder.newJob(DumbJob.class)

.withIdentity("testJob")

.usingJobData("jobSays", "Hello World!")

.usingJobData("myFloatValue", 3.141f).build();

job.getJobDataMap().put("state", state);


// 10초마다 계속 돌기 java Timer와 비슷

/*

* Trigger trigger = TriggerBuilder.newTrigger()

* .withSchedule(SimpleScheduleBuilder.simpleSchedule()

* .withIntervalInSeconds(10) .repeatForever()) .build();

*/


// CronTrigger 매 10초마다(10,20,30 ...) 작업 실행

CronTrigger cronTrigger = TriggerBuilder

.newTrigger()

.withIdentity("crontrigger", "crontriggergroup1")

.withSchedule(

CronScheduleBuilder.cronSchedule("*/10 * * * * ?"))

.build();


// schedule the job

SchedulerFactory schFactory = new StdSchedulerFactory();

Scheduler sch = schFactory.getScheduler();

    //스케줄러 시작

sch.start();

sch.scheduleJob(job, cronTrigger);

// 스케줄러 정지 sch.shutdown();


} catch (SchedulerException e) {

e.printStackTrace();

}

}


public static void main(String[] args) {

new CronTest();

}

}



2. job 구현

public class DumbJob implements Job {

    String jobSays;

    float myFloatValue;

    ArrayList state;

      

    public DumbJob() {

    }


//스케줄러에 인해 주기적으로 실행되는 함수.

    public void execute(JobExecutionContext context)

      throws JobExecutionException

    {

      JobKey key = context.getJobDetail().getKey();

      JobDataMap dataMap = context.getMergedJobDataMap(); 


//데이터는 아래 setter에서 저장된다. 혹은 아래와 같이 얻어도 된다.

/*

       String jobSays = dataMap.getString("jobSays");

       float myFloatValue = dataMap.getFloat("myFloatValue");

       ArrayList state = (ArrayList) dataMap.get("myStateData"); 

*/

      state.add(new Date());

      System.err.println("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue + ", state size:" + state.size() + "," +state.get(state.size()-1));

    }


//아래와 같이 setter 형식으로 값을 받을 수도 있고 혹은, datamap을 통해 얻을 수 있음

    public void setJobSays(String jobSays) {

      this.jobSays = jobSays;

    }

    public void setMyFloatValue(float myFloatValue) {

      this.myFloatValue = myFloatValue;

    }

    public void setState(ArrayList state) {

      this.state = state;

    }}


3. 실행결과

Instance DEFAULT.testJob of DumbJob says: Hello World!, and val is: 3.141, state size:1,Wed Jul 22 10:03:40 KST 2015

Instance DEFAULT.testJob of DumbJob says: Hello World!, and val is: 3.141, state size:2,Wed Jul 22 10:03:50 KST 2015

Instance DEFAULT.testJob of DumbJob says: Hello World!, and val is: 3.141, state size:3,Wed Jul 22 10:04:00 KST 2015


.....





참고

quartz 사이트(tutorials, examples, cookbook)

http://quartz-scheduler.org/documentation/quartz-2.2.x/quick-start


'학습자료 > Java' 카테고리의 다른 글

[java] 자바어플에 webview(javafx) 삽입  (0) 2015.03.16
[java] jTable 실시간 값 변경  (0) 2015.01.08
[java] timetask  (0) 2015.01.08
[java] 파일 실행  (0) 2015.01.08
[java] html 파싱, jsoup 예제  (0) 2015.01.08
posted by cozyboy
:
학습자료/Java 2015. 3. 16. 10:27



import java.awt.Dimension;
import java.awt.Point;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class JavaFX {

    /* Create a JFrame with a JButton and a JFXPanel containing the WebView. */
    private static void initAndShowGUI() {
        // This method is invoked on Swing thread
        JFrame frame = new JFrame("FX");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().setLayout(null); // do the layout manually

        final JButton jButton = new JButton("Button");
        final JFXPanel fxPanel = new JFXPanel();

        frame.add(jButton);
        frame.add(fxPanel);
        frame.setVisible(true);

        jButton.setSize(new Dimension(200, 27));
        fxPanel.setSize(new Dimension(300, 300));
        fxPanel.setLocation(new Point(0, 27));

        frame.getContentPane().setPreferredSize(new Dimension(300, 327));
        frame.pack();
        frame.setResizable(false);

        Platform.runLater(new Runnable() { // this will run initFX as JavaFX-Thread
            @Override
            public void run() {
                initFX(fxPanel);
            }
        });
    }

    /* Creates a WebView and fires up google.com */
    private static void initFX(final JFXPanel fxPanel) {
        Group group = new Group();
        Scene scene = new Scene(group);
        fxPanel.setScene(scene);

        WebView webView = new WebView();

        group.getChildren().add(webView);
        webView.setMinSize(300, 300);
        webView.setMaxSize(300, 300);

            // Obtain the webEngine to navigate
        WebEngine webEngine = webView.getEngine();
        webEngine.load("http://www.google.com/");
    }

    /* Start application */
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                initAndShowGUI();
            }
        });
    }
}

펌 : http://stackoverflow.com/questions/8374365/integrating-javafx-2-0-webview-into-a-swing-java-se-6-application



javafx 란 및 간단 강좌?? : http://btsweet.blogspot.kr/2014/03/javafx.html


javafx doc : 

http://www.oracle.com/technetwork/java/javase/documentation/javafx-docs-2159875.html

http://docs.oracle.com/javase/8/javase-clienttechnologies.htm


'학습자료 > Java' 카테고리의 다른 글

[java] 스케줄링 like cron(quartz Scheduler)  (1) 2015.07.22
[java] jTable 실시간 값 변경  (0) 2015.01.08
[java] timetask  (0) 2015.01.08
[java] 파일 실행  (0) 2015.01.08
[java] html 파싱, jsoup 예제  (0) 2015.01.08
posted by cozyboy
:
학습자료/Java 2015. 1. 8. 21:37

동작 (붉은색 글 표기)

1. 초기 더미데이터 2줄 테이블 생성

2. 시작 버튼을 누를시 timertask를 이용하여 주기적으로 테이블 값 변경

3. 정지 버튼 누를시 taimertask를 정지하여 테이블 값 변경을 취소


GUI 다루는건 항상 맘처럼 안되네요....


package test;


import java.awt.BorderLayout;

import java.awt.EventQueue;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JScrollPane;

import javax.swing.JTable;

import javax.swing.ListSelectionModel;

import javax.swing.table.DefaultTableModel;


public class TablePrint3 {


private JFrame frame;

private JTable table;

private JButton button;

private JButton button2;


ScheduledJob job;

Timer jobScheduler;

Integer a = 1;


public TablePrint3() {

initialize();

}


public static void main(String args[]) {

EventQueue.invokeLater(new Runnable() {


@Override

public void run() {

// TODO Auto-generated method stub

try {

TablePrint3 window = new TablePrint3();

window.frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}


}

});

}


private void initialize() {

Object headers[] = { "aaa", "aaaa", "제목", "aa위" };

Object[][] rows = { { "one", "1", "3", "4" }, { "one", "1", "3", "4" } };

frame = new JFrame("Table Printing");

table = new JTable(rows, headers);

// 초기 더미 테이블 값 설정


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);



JScrollPane scrollPane = new JScrollPane(table);

frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

button = new JButton("정지");

button2 = new JButton("시작");


ActionListener startTask = new ActionListener() {

public void actionPerformed(ActionEvent e) {

if( jobScheduler != null){ 

job = new ScheduledJob();

jobScheduler = new Timer();

jobScheduler.scheduleAtFixedRate(job, 1000, 3000);

}

}

};   //Time Task 시작

ActionListener openConfig = new ActionListener() {


@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub


jobScheduler.cancel();

//timetask 정지

jobScheduler = null;

Runtime rt = Runtime.getRuntime();

String exeFile = "C://Windows//System32//notepad.exe C://chc_conf.txt";

Process p;


try {

p = rt.exec(exeFile);

p.waitFor();

} catch (Exception ee) {

ee.printStackTrace();

}

}

};


button.addActionListener(openConfig);

button2.addActionListener(startTask);


frame.getContentPane().add(button, BorderLayout.SOUTH);

frame.getContentPane().add(button2, BorderLayout.NORTH);

frame.setSize(490, 592);

frame.setVisible(true);


}


class ScheduledJob extends TimerTask {


public void run() {

a++;

table.setValueAt(a, 1, 2);

//2째줄 3번째 칼럼의 수를 하나씩 올리는 부분

}

}


}



'학습자료 > Java' 카테고리의 다른 글

[java] 스케줄링 like cron(quartz Scheduler)  (1) 2015.07.22
[java] 자바어플에 webview(javafx) 삽입  (0) 2015.03.16
[java] timetask  (0) 2015.01.08
[java] 파일 실행  (0) 2015.01.08
[java] html 파싱, jsoup 예제  (0) 2015.01.08
posted by cozyboy
:
학습자료/Java 2015. 1. 8. 20:23

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;

public class PrintTimer {
   
   public static void main(String[] args) {
      ScheduledJob job = new ScheduledJob();
      Timer jobScheduler = new Timer();
      jobScheduler.scheduleAtFixedRate(job, 1000, 3000);
      try {
         Thread.sleep(20000);
      } catch(InterruptedException ex) {
         //
      }
      jobScheduler.cancel();
   }
}

class ScheduledJob extends TimerTask {
   
   public void run() {
      System.out.println(new Date());
   }
}

PrintTimer는 main() 메소드에서 Timer 객체를 생성한 후, scheduleAtFixedRate() 메소드를 사용하여 1초 후부터 3초 간격으로 ScheduledJob 클래스의 run() 메소드를 실행한다. PrintTimer 클래스를 실행해보면 다음과 같은 결과가 출력될 것이다.



펌 : http://javacan.tistory.com/28

'학습자료 > Java' 카테고리의 다른 글

[java] 자바어플에 webview(javafx) 삽입  (0) 2015.03.16
[java] jTable 실시간 값 변경  (0) 2015.01.08
[java] 파일 실행  (0) 2015.01.08
[java] html 파싱, jsoup 예제  (0) 2015.01.08
[java] proxy setting  (0) 2014.04.05
posted by cozyboy
:
학습자료/Java 2015. 1. 8. 17:39


button2를 눌렀을때 chc_conf.txt 이란 메모장을 열기


ActionListener openConfig = new ActionListener() {


@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

Runtime rt = Runtime.getRuntime();

String exeFile = "C://Windows//System32//notepad.exe C://chc_conf.txt";

Process p;


try {

p = rt.exec(exeFile);

p.waitFor();

} catch (Exception ee) {

ee.printStackTrace();

}

}

};


button2.addActionListener(printAction);


'학습자료 > Java' 카테고리의 다른 글

[java] jTable 실시간 값 변경  (0) 2015.01.08
[java] timetask  (0) 2015.01.08
[java] html 파싱, jsoup 예제  (0) 2015.01.08
[java] proxy setting  (0) 2014.04.05
Installing software' has encountered a problem. 이클립스 문제  (0) 2013.05.23
posted by cozyboy
:
학습자료/Java 2015. 1. 8. 12:40

1. jsoup 라이브러리 다운

http://jsoup.org/download


2. 샘플 코드 (args = http://www.google.co.kr)

package org.jsoup.examples;

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * Example program to list links from a URL.
 */

public class ListLinks {
   
public static void main(String[] args) throws IOException {
       
Validate.isTrue(args.length == 1, "usage: supply url to fetch");
       
String url = args[0];
       
print("Fetching %s...", url);

       
Document doc = Jsoup.connect(url).get();
       
Elements links = doc.select("a[href]");
       
Elements media = doc.select("[src]");
       
Elements imports = doc.select("link[href]");

       
print("\nMedia: (%d)", media.size());
       
for (Element src : media) {
           
if (src.tagName().equals("img"))
               
print(" * %s: <%s> %sx%s (%s)",
                        src
.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
                        trim
(src.attr("alt"), 20));
           
else
               
print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
       
}

       
print("\nImports: (%d)", imports.size());
       
for (Element link : imports) {
           
print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel"));
       
}

       
print("\nLinks: (%d)", links.size());
       
for (Element link : links) {
           
print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
       
}
   
}

   
private static void print(String msg, Object... args) {
       
System.out.println(String.format(msg, args));
   
}

   
private static String trim(String s, int width) {
       
if (s.length() > width)
           
return s.substring(0, width-1) + ".";
       
else
           
return s;
   
}

}


3. 결과

Fetching http://www.google.com...


Media: (2)

 * img: <http://www.google.co.kr/images/icons/product/chrome-48.png> x ()

 * img: <http://www.google.co.kr/textinputassistant/tia.png> 27x23 ()


Imports: (0)


Links: (21)

 * a: <http://www.google.co.kr/imghp?hl=ko&tab=wi>  (이미지)

 * a: <http://maps.google.co.kr/maps?hl=ko&tab=wl>  (지도)

 * a: <https://play.google.com/?hl=ko&tab=w8>  (Play)

 * a: <http://www.youtube.com/?gl=KR&tab=w1>  (YouTube)

 * a: <http://news.google.co.kr/nwshp?hl=ko&tab=wn>  (뉴스)

 * a: <https://mail.google.com/mail/?tab=wm>  (Gmail)

 * a: <https://drive.google.com/?tab=wo>  (드라이브)

 * a: <http://www.google.co.kr/intl/ko/options/>  (더보기 »)

 * a: <http://www.google.co.kr/history/optout?hl=ko>  (웹 기록)

 * a: <http://www.google.co.kr/preferences?hl=ko>  (설정)

 * a: <https://accounts.google.com/ServiceLogin?hl=ko&continue=http://www.google.co.kr/%3Fgfe_rd%3Dcr%26ei%3DtvutVPb5NsG6kAXVy4CwDA>  (로그인)

 * a: <http://www.google.co.kr/chrome/index.html?hl=ko&brand=CHNG&utm_source=ko-hpp&utm_medium=hpp&utm_campaign=ko>  (Chrome 다운로드)

 * a: <http://www.google.co.kr/advanced_search?hl=ko&authuser=0>  (고급검색)

 * a: <http://www.google.co.kr/language_tools?hl=ko&authuser=0>  (언어도구)

 * a: <http://www.google.co.kr/intl/ko/ads/>  (광고 프로그램)

 * a: <http://www.google.co.kr/intl/ko/services/>  (비즈니스 솔루션)

 * a: <https://plus.google.com/102197601262446632410>  (+Google)

 * a: <http://www.google.co.kr/intl/ko/about.html>  (Google 정보)

 * a: <http://www.google.co.kr/setprefdomain?prefdom=US&sig=0_zqOlB8Ip0P4chzkeavWzxYifIMQ%3D>  (Google.com)

 * a: <http://www.google.co.kr/intl/ko/policies/privacy/>  (개인정보 보호)

 * a: <http://www.google.co.kr/intl/ko/policies/terms/>  (약관)



4. jsoup api document

http://jsoup.org/apidocs/


5. cookbook

http://jsoup.org/cookbook/

'학습자료 > Java' 카테고리의 다른 글

[java] timetask  (0) 2015.01.08
[java] 파일 실행  (0) 2015.01.08
[java] proxy setting  (0) 2014.04.05
Installing software' has encountered a problem. 이클립스 문제  (0) 2013.05.23
[java] java.library.path - linux, eclipse  (0) 2013.03.19
posted by cozyboy
:
학습자료/Java 2014. 4. 5. 23:27

Solution:

Following example shows how to find proxy settings & create a proxy connection on a system using put method of systemSetting & getResponse method of HttpURLConnection class.

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;

public class Main{
   public static void main(String s[]) 
   throws Exception{
      try {
         Properties systemSettings = 
         System.getProperties();
         systemSettings.put("proxySet", "true");
         systemSettings.put("http.proxyHost", 
         "proxy.mycompany1.local");
         systemSettings.put("http.proxyPort", "80");
         URL u = new URL("http://www.google.com");
         HttpURLConnection con = (HttpURLConnection)
         u.openConnection();
         System.out.println(con.getResponseCode() + 
         " : " + con.getResponseMessage());
         System.out.println(con.getResponseCode() == 
         HttpURLConnection.HTTP_OK);
      }
      catch (Exception e) {
         e.printStackTrace();
         System.out.println(false);
      }
      System.setProperty("java.net.useSystemProxies", 
      "true");
      Proxy proxy = (Proxy) ProxySelector.getDefault().
      select(new URI("http://www.yahoo.com/")).iterator().
      next();;
      System.out.println("proxy hostname : " + proxy.type());
      InetSocketAddress addr = (InetSocketAddress)
      proxy.address();
      if (addr == null) {
         System.out.println("No Proxy");
      }
      else {
         System.out.println("proxy hostname : " 
         + addr.getHostName());
         System.out.println("proxy port : "
         + addr.getPort());
      }
   }
}

Result:

The above code sample will produce the following result.

200 : OK
true
proxy hostname : HTTP
proxy hostname : proxy.mycompany1.local
proxy port : 80

 

펌 : http://www.tutorialspoint.com/javaexamples/net_poxy.htm

posted by cozyboy
:
학습자료/Java 2013. 5. 23. 17:21

상단에 'Avilable Software Sites' 를 클릭

그 중에 다운 받을 항목만 체크 후, 다른것들은 모두 해제 한다. 그러면 update가 가능해 진다.


http://hyunssssss.tistory.com/entry/An-error-occurred-while-collecting-items-to-be-installed

'학습자료 > Java' 카테고리의 다른 글

[java] html 파싱, jsoup 예제  (0) 2015.01.08
[java] proxy setting  (0) 2014.04.05
[java] java.library.path - linux, eclipse  (0) 2013.03.19
[Java] messagePack(rpc 구현)  (0) 2013.02.27
[java] Java decompiler[Eclipse plugin]  (0) 2013.02.26
posted by cozyboy
:
학습자료/Java 2013. 3. 19. 17:26

OS : 리눅스

IDE: 이클립스


  • 에러 이유

자바 라이브러리(.jar)를 추가하였는데도 java.library.path 에러가 난다.

이유는 내가 추가한 external 자바 라이브러리가 네이티브 라이브러리를 사용하기 때문이다.


예를 들면, 자바 라이브러리가 윈도우에서는 .dll 파일을 이용하는것이고, 리눅스에서는 .so 를 내부적으로 사용한다.



  • 해결방법

방법1. 이클립스에서

LD_LIBRARY_PATH 에 네이티브 라이브러리 경로를 추가해야 한다.


프로젝트 좌클릭 -> Run as -> Run Configuration -> Enviroment TAB
에서


Name과 value에 LD_LIBRARY_PATH, /usr/local/lib(네이티브라이브러리가 존재하는 경로) 를 추가해 주면 된다.



방법2. 리눅스에서

  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib


위와 같이 리눅스상에 경로를 등록하여도 이클립스는 못알아 먹는다..

그래서 방법 1로 해결.


posted by cozyboy
:
학습자료/Java 2013. 2. 27. 13:26

messagePack - JSON,  BSON, Thrift, Protocol Buffer와 같이 데이터 형태이다. 클래스나 데이터를 시리얼라이재이션(직렬화) 하는 라이브러리로 사용되는데 그곳에서 rpc도 구현해둔게 있다.


RPC (remote procedure call) : 원격 프로시져 콜 이란..

간단하게 말해서 클라이언트에서 서버쪽 함수를 로컬에서 실행시킨다. 아니 시키는 것처럼 동작되는 것이다.

 

msgpack에서 제공하는 rpc구현언어는 c++, ruby, java, phython, php ... 등 여러가지가 존재한다.

 

라이브러리를 보면 자바 네트워크프레임워크 중 netty를 사용한다.

 

quick start의 예제 소스를보면 이해하기 쉬움.


[Web Site] (http://msgpack.org/)

[Wiki](http://wiki.msgpack.org/display/MSGPACK/Home)
[Sources](https://github.com/msgpack)
[Issues](http://jira.msgpack.org/browse/MSGPACK)


1. messagepack wiki home :

http://wiki.msgpack.org/display/MSGPACK/Home

 

2 . msgpack-rpc 저장소 :

https://github.com/msgpack/msgpack-rpc

 

3. messagepack-RPC for java  Quick Start  :

http://wiki.msgpack.org/display/MSGPACK/QuickStart+for+Java#QuickStartforJava-MessagePackRPCforJava


msgpack -java 저장소

https://github.com/msgpack/msgpack-java

 



 

posted by cozyboy
:
학습자료/Java 2013. 2. 26. 17:40

그냥 마켓에서 jadclipse 써도 나온다.


jadClipse 주소

http://sourceforge.net/projects/jadclipse/



설치는 아래 방법으로 했으나 마켓으로 해도 걍 되지 않을까..


 

1. 첨부파일 다운 받습니다

2. eclipse 가 있는 폴더안에 plugins 폴더안에 net.sf.jadclipse_3.3.0.jar파일 삽입

3. 이클립스 재시작

4. Window > Preferences > Java > JadClipse 에서 Path to decompiler 항목은 첨부파일을 받은 jad.exe 로 path를 잡아준다

ex) F:\springsource\sts-3.1.0.RELEASE\util\jad\jad.exe

Directory for temporay files 는 적당한 위치에 잡아준다

ex) F:\springsource\sts-3.1.0.RELEASE\util\.net.sf.jadclipse

5. Window > Preferences > Java > JadClipse > Mise 에서 Convert Unicode strings into ANSI strings 체크(한글깨짐방지)

6. Window > Preferences > General > Editors > File Associations 에서 *.class , *.class without source 두개다 default를 JadClipse Class File Viewer로 선택 후 ok 완료


 

http://blog.naver.com/youzang7/70152882826

posted by cozyboy
:
학습자료/Java 2013. 2. 26. 16:54

이희승 | Twitter 소프트웨어 엔지니어가 2012 deview에서 한 내용인듯.

http://deview.kr/2012/xe/index.php?document_srl=379&dummy=1&mid=track



Mina와 Netty는 둘다 이희승이라는 한국인이 만든 프레임워크다..
Mina는 Apache, Netty는 JBOSS.. 

Netty나 Mina를 하고선 느낀것은 참으로 삽질을 많이 줄여준다라는것이다.
소켓통신을 공부한후 Netty를 공부하면 참으로 좋을듯하다.
하지만 유일한 단점이.. 한국인이 만들었지만.. 한국어로된 문서가 상당히 부족하다..
이건머 다.. 영어다.... 못읽는건 아니지만 한글보다 느린건 어쩔수 없지...


라고 한다. - http://withoutwing.tistory.com/5




Netty

1. 네티 공식 사이트  - http://netty.io/

2. netty - 한글 사용자 가이드 첨부 - http://withoutwing.tistory.com/5

3. netty  한국인 사용자 그룹 -  http://groups.google.co.kr/group/netty-ko?hl=ko


netty 사용에 관한 몇가지 tip - 

http://blog.pointbre.com/351/netty-%EC%82%AC%EC%9A%A9%EC%97%90-%EA%B4%80%ED%95%9C-%EB%AA%87%EA%B0%80%EC%A7%80-tip.html


잡다 

네티란? - http://blog.naver.com/PostList.nhn?blogId=kjs077&from=postList&categoryNo=56


netty 사용법1(server) -  http://shonm.tistory.com/entry/JAVA-netty-%EB%B9%84%EB%8F%99%EA%B8%B0-%EC%9D%B4%EB%B2%A4%ED%8A%B8-%EB%B0%A9%EC%8B%9D-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%ED%94%84%EB%A0%88%EC%9E%84%EC%9B%8C%ED%81%AC-%EC%82%AC%EC%9A%A9%EB%B2%95-1-server

 

netty zerocopy 파일 전송 - http://clotho95.blog.me/140117229649

Apache MINA

1. 공식 사이트 - http://mina.apache.org/


아래주소는 그냥 위의 공식사이트에 나오는 링크이다.

- javadoc : http://mina.apache.org/mina-project/apidocs/index.html

- 특징 : http://mina.apache.org/mina-project/features.html

- quick start : http://mina.apache.org/mina-project/quick-start-guide.html

- MINA에 대한 사람들의 말들 : http://mina.apache.org/mina-project/testimonials.html

- download : http://mina.apache.org/mina-project/downloads.html


 예전 글이지만 netty 개발자가 소개글로 올린 : http://www.javaservice.co.kr/~java/bbs/read.cgi?b=news&c=r_p&m=resource&n=1104313609&p=13&s=t (2004년)



Netty vs Apache MINA stackoverflow - 

http://stackoverflow.com/questions/1637752/netty-vs-apache-mina


외..

Neuropu(java neural Network Framework)???

http://neuroph.sourceforge.net/

posted by cozyboy
:
학습자료/Java 2013. 2. 13. 14:52

zeroconf 간단 요약 -

http://cozyboy.tistory.com/entry/zero-configuration-networking

 

추가.

Bonjour browser download site

http://hobbyistsoftware.com/bonjourbrowser

이 프로그램을 사용하면 어떠한 장비들이 있는지 간단하게 볼수 있다.

굳이 검색할 장비를 세팅하지 않아도 나도모르게 내 컴퓨터엔, 혹은 주위에 이미 존재 하고 있을수도 있다.

아래 소스로 프로그램후, 위의 서비스 타입([ex] : _adisk._tcp)을 이용하여 검색해보자. 표시가 잘 된다면 기본은 성공이다.

 

 


목차는

- 환경

- avahi(검색할 리모트 네트워크 장비) conf file 내용

- 테스트 코드

- 결과

- 간략 설명

- 오픈소스 JBonjourBrowser 스샷 및 다운로드 위치 


 

 

  • 환경

zeroconf 구현물인 avahi는 리눅스에서 running 상태이고,

 

애플의 bonjour sdk에 있는 dnssd.jar를 이용하여

윈도우에서 리눅스 장비를 탐지 할 수 있다.

 

avahi는 왠만하면 OS설치시 깔려있다. 깔려있지 않을 시, 설치 및 구동 시켜야 한다.

 

avahi-dnsconfd 는 추가로 설치함.(아마 avahi service conf가 바뀌면 실시간으로 모니터링 하는 데몬인것 같다. 테스트 할시 용의하므로 추가 설치)

 

/etc/avahi/service/* 가 service config다

 

  • avahi service conf의 min.service파일 내용.

<?xml version='1.0' standalone='no'?><!--*-nxml-*--> <!DOCTYPE service-group SYSTEM 'avahi-service.dtd'> <service-group> <name>UCS-1078d23f2fbb</name> <service> <type>_cozy._tcp</type> <port>22</port> <txt-record>ID=cozy--</txt-record> <txt-record>NAME=min</txt-record> <txt-record>AGE=26</txt-record> <txt-record>COR=Gluesys</txt-record> </service> </service-group>


 

  • [테스트 코드]

bonjour sdk for window 다운 : https://developer.apple.com/bonjour/

- 아이디 만들고 다운받으면 된다. 분명 아이디 안만들고 어디선가 받았는데 못 찾겠음.

 

package test.dns;

/*
 * Browse -> Resolve(a single SRV record and a single TXT record에 적합하다) -> Query listen(txt record가 여러라인일때 쓴다.)
 * */

import com.apple.dnssd.BrowseListener;
import com.apple.dnssd.DNSSD;
import com.apple.dnssd.DNSSDException;
import com.apple.dnssd.DNSSDService;
import com.apple.dnssd.QueryListener;
import com.apple.dnssd.ResolveListener;
import com.apple.dnssd.TXTRecord;

public class Main implements BrowseListener, QueryListener, ResolveListener{

 private DNSSDService monitorQ = null;
 
 public static void browse() throws DNSSDException, InterruptedException{
  System.out.println("TestBrowse Starting");

  DNSSDService b = DNSSD.browse("_min._tcp", new Main());
  
  System.out.println("TestBrowse Running");
  Thread.sleep(500);
  System.out.println("TestBrowse Stopping");
  b.stop();
 }

 
 public void TestResolveWithMonitoring(String serviceName, String regType,  String domain)
   throws DNSSDException, InterruptedException {
  System.out.println("TestResolve Starting==================================");
  DNSSDService r = DNSSD.resolve(0, DNSSD.ALL_INTERFACES, serviceName, regType, domain, this);
  System.out.println("TestResolve Running");
   
  /*시간이 너무 짧을시, txt-record가  갯수만큼 안나온다.*/
  try {
   Thread.sleep(500);                  
  } catch (Exception e) {
   e.printStackTrace();
   System.exit(-1);
  }
  System.out.println("TestResolve Stopping===================================");
  if (monitorQ == null)
   r.stop();
  else
   monitorQ.stop();
  
 }
 
 
 public static void main(String[] args) {
  try { browse(); }
  catch (Exception e) {
   e.printStackTrace();
   System.exit(-1);
  }
 }

 /** Browser listener`s  */
 @Override
 public void serviceFound( DNSSDService browser,  int flags, int iflndex,
    String serviceName, String regType, String domain) {
  // TODO Auto-generated method stub
  System.out.print("\t(Browsing) Service Found : ");
  System.out.println("browser:" + browser + ", flags:" + flags
    + ", iflndex:" + iflndex + ", serviceName:" + serviceName+ ", regType:" + regType+ ", domain:" + domain);
 
  try {
   
   TestResolveWithMonitoring(serviceName, regType, domain);
   
  } catch (DNSSDException | InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 @Override
 public void serviceLost(DNSSDService arg0, int arg1, int arg2, String arg3,
   String arg4, String arg5) {
  // TODO Auto-generated method stub
  System.out.println("Add flags:" + arg0 + ", ifIndex:" + arg1
    + ", Name:" + arg2 + ", Type:" + arg3 + ", Type4:" + arg4
    + ", Type5:" + arg5);
 }

 


 /** Query listener`s  */
 public void queryAnswered(DNSSDService query, int flags, int ifIndex,
   String fullName, int rrtype, int rrclass, byte[] rdata, int ttl) {
   TXTRecord txtRecord = new TXTRecord(rdata);
   System.out.println("\n+++txtRecord Size is :"+txtRecord.size()+"\n");
   System.out.println("\t(Query) txtRecord is : ");
   for (int i = 0; i < txtRecord.size(); i++) {
    String key = txtRecord.getKey(i);
    String value = txtRecord.getValueAsString(i);
    if (key.length() > 0) {
     
     System.out.println("\t\t" + key + "=" + value);
    }
   }
 }

 
 /** Resolve listener`s  */
 public void serviceResolved(DNSSDService resolver, int flags, int ifIndex,
   String fullName, String hostName, int port, TXTRecord txtRecord) {
  System.out.print("\t(Resolve)Service Resolved: " + hostName + ":" + port);
  System.out.println(" Flags: " + flags + ", ifIndex: " + ifIndex + ", FQDN: " + fullName);

  // Now that we've got a resolve result,
  // start monitoring the TXT record and stop the resolve call.
  try {
   monitorQ = DNSSD.queryRecord(0, ifIndex, fullName, 16, 1, this);
  } catch (Exception e) {
   e.printStackTrace();
   System.exit(-1);
  }
 
  /*try {
   Thread.sleep(1);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }*/
  
  resolver.stop();
 }
 
 /** all listener`s  */
 @Override
 public void operationFailed(DNSSDService service, int errorCode) {
  System.out.println("listener failed " + errorCode);
  System.exit(-1);
 }

}

 

 

  • [결과] 

TestBrowse Starting
TestBrowse Running
 (Browsing) Service Found : browser:com.apple.dnssd.AppleBrowser@31731334, flags:2, iflndex:11, serviceName:min_test, regType:_min._tcp., domain:local.
TestResolve Starting==================================
TestResolve Running
 (Resolve)Service Resolved: min.local.:22 Flags: 0, ifIndex: 11, FQDN: min_test._min._tcp.local.

+++txtRecord Size is :4

 (Query) txtRecord is :
  ID=cozy--
  NAME=min
  AGE=26
  COR=Gluesys
TestBrowse Stopping
TestResolve Stopping===================================

 

 


 

  • 간략 설명

BrowseListener,  ResolveListener, QueryListener 가 구현되어있다.

 

BrowseListener로는  (serviceFound )

browser:com.apple.dnssd.AppleBrowser@31731334, flags:2, iflndex:11, serviceName:min_test, regType:_min._tcp., domain:local.

를 얻는다.

 

ResolveListener로는 (serviceResolved)

(Resolve)Service Resolved: min.local.:22 Flags: 0, ifIndex: 11, FQDN: min_test._min._tcp.local.

 

☞ QueryListener는 단일 txtRecord를 얻는데 사용된다. 멀티라인의 txtRecord를 얻기위해선 QueryListener를 사용해야 한다. 위의 소스는 단지 Query에 이용되는 fullname(serviceName+regType+domain = min_test._min._tcp.local.)인자가 무엇인지 확인한다.

를 얻는다

 

 

멀티라인의 txtRecord를 얻기위해

QueryListener를  (queryAnswered ) 사용하여 아래값을 얻는다.

 ID=cozy--
NAME=min
AGE=26
COR=Gluesys

 

 

자세한 내용은 javadoc을 참고 한다.

 

 

 

  • 오픈소스 JBonjourBrowser 스샷

 

다운 로드 : https://wiki.cs.columbia.edu/display/res/JBonjourBrowser

BonjourBrowser와 다르게 service Type으로 묶어서 표시한다.

 



[참고]

avahi service type 확인

http://linux.die.net/man/5/avahi.service

 

DNSSD javadoc

https://developer.apple.com/library/mac/documentation/Java/Reference/DNSServiceDiscovery_JavaRef/com/apple/dnssd/DNSSD.html

 

Bonjour browser download

http://hobbyistsoftware.com/bonjourbrowser

 


posted by cozyboy
:
학습자료/Java 2012. 8. 14. 15:01

+ split 정규식 & regualar Expressions

- http://www.tobearchitect.com/entry/Java-String의-split-함수의-재발견
- http://www.vogella.com/articles/JavaRegularExpressions/article.html


정규표현식 문법

^ : 문자열의 시작을 나타냄. 

$ : 문자열의 종료를 나타냄.

. : 임의의 한 문자를 나타냄. (문자의 종류는 가리지 않는다)

| : or를 나타냄. 

? : 앞 문자가 없거나 하나있음을 나타냄. 

+ : 앞 문자가 하나 이상임을 나타냄. 

* : 앞 문자가 없을 수도 무한정 많을 수도 있음을 나타냄. 

[] : 문자 클래스를 지정할 때 사용한다. 문자의 집합이나 범위를 나타내며 두 문자 사이는 '-' 기호로 범위를 나타낸다. 

      []내에서 ^ 가 선행하여 나타나면 not 를 나타낸다. 

{} : 선행문자가 나타나는 횟수 또는 범위를 나타낸다. 

a{3} 인 경우 a가 3번 반복된 경우를 말하며, a{3,}이면 a가 3번 이상 반복인 경우를 말한다. 또한 a{3,5}인 경우 

a가 3번 이상 5번 이하 반복된 경우를 나타낸다. 

( ): 소괄호 ‘( )’ 특수문자는 ‘( )’ 특수문자 안의 글자들을 하나의 문자로 봅니다. 예를 들어 ‘gu(gg){2}le’ 와 같은 패턴을 작성하게 되면    

     ‘guggggle' 문자열이 문자열에 포함되어 있어야 됩니다.

|: 패턴 안에서 OR연산을 사용할 때 사용합니다. 예를 들어 'hi|hello' 는 hi 나 hello 가 포 함되어있는 문자열을 의미합니다.

\w : 알파벳이나 숫자

\W : 알파벳이나 숫자를 제외한 문자

\d : 숫자 [0-9]와 동일

\D : 숫자를 제외한 모든 문자

\: 위의 각 기능에서 벗어납니다(escape).

(?i): 앞 부분에 (?i) 라는 옵션을 넣어주면 대소문자를 구분하지 않는다 (물음표+소문자i(아이))

 

기본적인 문자열 검증 정규식

 

^[0-9]*$  :  숫자만

^[a-zA-Z]*$  :  영문자만

^[가-힣]*$  :  한글만

^[a-zA-Z0-9]*$  :  영어/숫자만

.+ : 한문자 이상의 전체문자를 표시한다.

 

정규식 표현 예제

이메일 : ^[a-zA-Z0-9]+@[a-zA-Z0-9]+$  or  ^[_0-9a-zA-Z-]+@[0-9a-zA-Z-]+(.[_0-9a-zA-Z-]+)*$ 

휴대폰 :  ^01(?:01[6-9]) - (?:\d{3}\d{4}) - \d{4}$ 

일반전화 : ^\d{2,3} - \d{3,4} - \d{4}$

주민등록번호 : \d{6} \- [1-4]\d{6}

IP 주소 : ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3})

파일확장자: ([^\s]+(\.(?i)(jpg|png|gif|bmp))$)

 

 

클래스 사용 예.

A typical invocation sequence is thus  

Pattern p = Pattern.compile("a*b"); 

Matcher m = p.matcher("aaaaab"); 

boolean b = m.matches();

 

A matches method is defined by this class as a convenience for when a regular expression is used just once. 

This method compiles an expression and matches an input sequence against it in a single invocation. The statement  

 

boolean b = Pattern.matches("a*b", "aaaaab");

 

 

참고 사이트

자바, javascript, oracle 정규식: http://litlhope.springnote.com/pages/1786498

자바 정규식 간단 설명: http://twinstarbox.tistory.com/entry/Java-%EC%A0%95%EA%B7%9C%EC%8B%9D%EC%9D%B4%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80

URL 정규식으로 분리하기: http://goodidea.tistory.com/86


출처 - http://blog.naver.com/beabeak?Redirect=Log&logNo=50126941465


posted by cozyboy
:
학습자료/Java 2012. 8. 14. 14:43

Jdk 5.0 에서 새로 선보인 (Annotation) 어노테이션 이라는 겁니다.

 

자바 언어로 표현할수 없지만 프로그램 전체적으로 표현해야할 테이터를 기술하는 방법을 제공하죠.

다시말하면, 어노테이션을 사용하면 프로그램에서 컴파일러가 테스트하고 검증해야하는 부가 정보를 정해진

형식으로 설명하는 것이 가능하게 됩니다. 또한 설명 파일이나 새로운 클래스 정의를 생성하여 공통코드를

작성하는 부담을 줄이는 용도로도 활용할 수 있죠.

 

가장 자주 쓰이는 어노테이션은

 

@Override

 : 기반 클래스의 메소드를 오버라이드한 것을 표시한다. 메소드 이름을 잘못 표기하거나 시그니처를 잘못 지정할

경우 컴파일 에러 발생

 

@Deprecated

 : 해당 요소가 사용될 경우 컴파일러가 경고를 발생 시킨다.

 

@SuppressWarning

 : 부적절한 컴파일러의 경고를 제거하기 위해 사용된다.

 

음..어노테이션은 자바 고급기술에 속하는 편이어서 그냥 이런게 있구나 하고 넘어가셔도 무방합니다만

좀더 자세히 알고 싶으시면 관련서적을 보시거나 검색해보시는 편이 나으실 겁니다^^

그밖에  

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

[펌]내사랑꿀떡 


java 1.5 이후에 generic type 에서 unchecked 라고 경고하는경우에.(이클립스 같은 ide에서) 또는 콘솔에서도 컴파일 할때 하는듯 하다.


@SuppressWarnings("unchecked")

이 annotation을 해당 메서드 앞에 또는 해당 멤버 변수에 얹어준다.


class Test(){

......


@SuppressWarnings("unchecked")

private List list;

....


@SuppressWarnings("unchecked")

public void setList(List list){

this.list = list;

}


}


또 지역변수에서 사용하는 경우가 있는데... 변수에 바로 할당하는 경우는 그위에 얹어도 되지만

변수를 할당하고 중간에 사용하면 안된다..  그러니까


public void method(){

....

@SuppressWarnings("unchecked")

List list = xxx.getList();

//이거는 되지만

}


public void method(){

....

List list = null;

....


@SuppressWarnings("unchecked")

list = xxx.getList();

//이거는 싫다고 한다. 

....

}


이클립스 노란느낌표 뵈기 싫어서.. ^^;;

---------------------------------------------------------------------------------------------------
@SuppressWarnings 어노테이션은 네이밍처럼 compile시 warnning을 체크하지 않기위한
용도로  사용됩니다.

argument의 "serial"은
java.io.Serializeable 인터페이스를 구현하는데 serialVersionUID 를 정의해 주지 않은 경우
나타나는 warnning을 체크하지 않겠다는 의미 입니다.

출처 : http://mykjy.tistory.com/7


posted by cozyboy
: