2016년 12월 1일 목요일

Junit MultiThread Test code


import org.junit.Test;

import junit.framework.TestCase;
import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;
import net.sourceforge.groboutils.junit.v1.TestRunnable;

public class TestThread extends TestCase{
 
 private static int THREAD_SIZE = 20;
 
 /*
  * Test class should have exactly one public zero-argument constructor이므로
  * TestCase 클래스를 extends 하고 GroboUtils의 클래스인 TestRunnable을 상속받은 클래스를 이너클래스로 사용하였다.
  */
 
 public class MultiThreadTest extends TestRunnable {
  
  private int i = 0;
  
  
  public MultiThreadTest(int i){
   this.i = i;
  }
  
  @Override
  public void runTest() throws Throwable {
   Thread.sleep(1000);
   
   System.out.println(Thread.currentThread().getName() + " : [" + i + "]");
  }
 }
 
 @Test
 public void test() throws Throwable{
  TestRunnable[] t = new TestRunnable[THREAD_SIZE];
  
  for(int index=0; index < THREAD_SIZE; index++){
   t[index]=new MultiThreadTest(index);
  }
  
  MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(t);
  mttr.runTestRunnables();
  
  System.out.println("main end.........................");
 }
}

2016년 9월 29일 목요일

Windows 환경에서 Python Selenium 설치

precodition : python3.5 설치 및 path 설정

(1) python selenium 라이브러리 설치


C:\PYTHON_HOME\..\Scripts
pip install -U selenium
실행 시 SSL 오류가 발생하였음

 Could not fetch URL https://pypi.python.org/simple/selenium/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) - skipping
  Could not find a version that satisfies the requirement selenium (from versions: )
No matching distribution found for selenium

[해결방안]

  1. pip upgrade(pip 버전 확인 pip --version)
  2. easy_install pyopenssl 실행
  3. pip install --upgrade --trusted-host pypi.python.org selenium








출처 : http://selenium-python.readthedocs.io/installation.html


Python if __name__ == "__main__" 정리, 설명

if __name__ == "__main__" 의미
파이썬에서 일반적으로 import 방식으로 다른 코드를 불러오는데, 파이썬이 스크립트 언어이기에 그때마다 불려온 파일에 있는 메소드와 클래스를 실행 시킨다면 원하는대로 사용하기가 힘들기에

if __name__ == "__main__" 구문을 통해 실행될 코드와 그냥 참조 대기상태로 존재할 코드를 구분할 수 있다.
__name__ 은 보통 해당 파일의 위치+이름으로 구성돼있다.
from django import db의 경우 db.__name__을 찍어보면 'django.db'가 나온다.

test.py

def say_hi():

    print("Hi")



if __name__=="__main__":

    say_hi()
test.py 파일을 python test.py 로 실행한다면 say_hi() 메소드가 실행된다. 직접 실행되는 파일의 __name__은 __main__으로 설정된다.
그러나 다른 파일에서 import test 로 위 파일을 불러온다면 say_hi()는 실행되지 않는다. 기본적으로 test.py의 __name__ 은 그냥 'test'이다. (파일명)

2016년 1월 5일 화요일

jar 파일을 자신의 로컬 레포지토리에 등록하는 방법

mvn install:install-file -Dfile=c:\kaptcha-2.3.jar -DgroupId=com.google.code -DartifactId=kaptcha -Dversion=2.3 -Dpackaging=jar

인스톨 한 후 pom.xml에 dependency 걸어주면 된다.

2015년 10월 28일 수요일

Maven에서 Dependency Version Range


Range
Meaning
1.0
"Soft" requirement on 1.0 (just a recommendation - helps select the correct version if it matches all ranges)
(,1.0]
x <= 1.0
(,1.0],[1.2,)
x <= 1.0 or x >= 1.2. Multiple sets are comma-separated
(,1.1),(1.1,)
This excludes 1.1 if it is known not to work in combination with this library
[1.0,2.0)
1.0 <= x < 2.0
[1.0]
Hard requirement on 1.0
[1.2,1.3]
1.2 <= x <= 1.3
[1.5,)
x >= 1.5

2015년 7월 9일 목요일

Java MVC model

Observer
public interface Observer {
   public void update(int data);
}

Model
public class CalculatorModel {
 private int data;
 private ArrayList list = new ArrayList();
 
 public void addTwoNumber(int firstNumber, int secondNumber){
  data = firstNumber + secondNumber;
  notifyObservers();
 }
 
 public void registerObserver(Observer o){
  list.add(o);
 }
 
 public void notifyObservers() {
  for(Observer o : list){
   o.update(data);   
  }  
 }
}

Controller
public class CalculatorController implements ActionListener{
 private CalculatorModel model;
 private CalculatorView view;

 public CalculatorController(CalculatorModel model, CalculatorView view) {
  this.model = model;
  this.view = view;
  this.view.setCalculatorListener(this);
 }

 @Override
 public void actionPerformed(ActionEvent arg0) {
  try {
   int firstNumber = view.getFirstNumber();
   int secondNumber = view.getSecondNumber();
   model.addTwoNumber(firstNumber, secondNumber);
  } catch (RuntimeException e) {
   e.printStackTrace();
  }
 }
}

View
public class CalculatorView extends JFrame implements Observer{
 private JTextField firstNumber = new JTextField(10);
 private JLabel additionLabel = new JLabel("+");
 private JTextField secondNumber = new JTextField(10);
 private JButton calculateButton = new JButton("계산");
 private JTextField calcSolution = new JTextField(10);
 private JPanel calcPanel = new JPanel();

 public CalculatorView() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setSize(600, 200);
  setLayout(new BorderLayout());
  calcPanel.add(firstNumber);
  calcPanel.add(additionLabel);
  calcPanel.add(secondNumber);
  calcPanel.add(calculateButton);
  calcPanel.add(calcSolution);
  add(calcPanel, BorderLayout.CENTER);
 }

 public int getFirstNumber() {
  return Integer.parseInt(firstNumber.getText());
 }

 public int getSecondNumber() {
  return Integer.parseInt(secondNumber.getText());
 }

 public void setCalcSolution(int result) {
  calcSolution.setText(result +"");
 }

 public void setCalculatorListener(ActionListener listener){
  calculateButton.addActionListener(listener);
 }

 @Override
 public void update(int data) {
  setCalcSolution(data);
 }
}

Main Method
public class MVCTest {
 public static void main(String[] args) {
  CalculatorView view = new CalculatorView();
  CalculatorModel model = new CalculatorModel();
  model.registerObserver(view);
  
  @SuppressWarnings("unused")
  CalculatorController controller = new CalculatorController(model, view);
  view.setVisible(true);
 }
}

2015년 5월 13일 수요일

Java code에서 java 파일 생성 후 컴파일 하기


package junit_sample;

public class JavaCompileTest {
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception {
        // Prepare source somehow.
        String source = "package test; public class Test { " +
                "static { System.out.println(\"hello\"); } " +
                "public Test() { System.out.println(\"world\"); } }";

        // Save source in .java file.
        File root = new File("/java"); // On Windows running on C:\, this is C:\java.
        File sourceFile = new File(root, "test/Test.java");
        sourceFile.getParentFile().mkdirs();

        System.out.println("path: " + sourceFile.getParentFile());

        new FileWriter(sourceFile).append(source).close();

        // Compile source file.
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        compiler.run(null, null, null, sourceFile.getPath());

        // Load and instantiate compiled class.
        URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
        Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".
        Object instance = cls.newInstance(); // Should print "world".
        System.out.println(instance); // Should print "test.Test@hashcode".
    }
}