java

반응형

깜빡 하면서 실행되지 않는다

최신 버전의 이클립스를 사용하다가 플러그인이 지원을 하지 않아 구 버전(Neon) 이클립스를 받아서 실행하였다

그런데 실행이 되지 않는다. 또 한참을 삽질을 했다.

이 현상을 해결하기 위해 구글링을 해보면 eclipse.ini 파일 수정하라는 얘기가 제일 많이 나온다

-vm 에 자바 경로를 추가해라..

java.se.ee 였나 이거 추가해라.. 등등이 있는데 전혀 해결되지 않았다

결론은 자바 버전이 문제였다

자바를 11.0.2 최신 버전을 설치했었는데 이게 이클립스 구버전에서 지원이 안되는 것이었나보다.

자바를 지우고 구버전 JDK 1.8.0을 설치하였따

그랬더니 단번에 해결..

오늘도 역시나 최신 업데이트는 함부로 하는게 아니라는 진리를 깨달았다..

반응형
반응형

String 배열을 사용해서 콤보박스에 값들을 보여줬었는데

ArrayList를 사용해서 콤보박스에 보여주고 싶었따.

스트링 배열은 String[] account1 = { id,id1,id2}

이런식으로 콤마로 이루어진 값이었는데 ArrayList는 배열마다 각 값을 가지고 있기 때문에 나중에 관리하기 편할 것 같았다.

기존 String 배열(account1)을 콤보박스에 넣었을 때 코드

JComboBox<?> comboBox = new JComboBox<Object>(account1);

ArrayList(account1)를 콤보박스에 넣을 때 코드

JComboBox<?> comboBox = new JComboBox(account1.toArray(new String[account1.size()]));

이렇게 하면 account1 배열의 사이즈만큼 알아서 콤보박스에 값이 노출되었다

반응형
반응형




JAVA

driver.manage().window().maximize(); //브라우저 확장

Python

driver.maximize_window()


JAVA

Thread.sleep(500); //단위 ms

Python

import time #(import 필요)

time.sleep(0.5)     # 단위 s


JAVA

Alert alert = driver.switchTo().alert(); //얼럿 창으로 스위칭

Python

alert = driver.switch_to_alert()


JAVA

alertText = alert.getText(); //얼럿 창 메시지 추출

Python

alertText = alert.text


JAVA

driver.find_element_by_id('user_id').sendKeys('id'); //id 요소 찾기와 입력값 채우기

Python

driver.find_element_by_id('user_id').send_keys('id')


JAVA

driver.quit();

Python

driver.close()


Python

driver.find_element_by_xpath('//*[@id="content"]/div/div[3]/button[2]').click() //xpath 클릭


표 출처 : https://wkdtjsgur100.github.io/selenium-xpath/


node

반응형
반응형

참고링크


http://blog.naver.com/battledocho/220035925900

반응형
반응형

subString 함수사용

subString(시작위치,끝위치);

예를 들어 애국가에서 

하느님이 ~ 우리나라만세 사이에 텍스트를 추출하고 싶다면

String song = "하느님이 보우하사 우리나라만세";

int start = song.indexOf("하느님이"); //하느님이 위치 추출

int end = song.indexOf("우리나라만세"); //우리나라만세 추출

String parseText = song.subString(start,end);

이런 방법도 있다



반응형
반응형



또 이상한 에러가 발생.. 이클립스가 이상한건가..

에러 내용은 이러하다

java.lang.SecurityException: class "org.hamcrest.Matchers"'s signer information does not match signer information of other classes in the same package

at java.lang.ClassLoader.checkCerts(ClassLoader.java:895)

at java.lang.ClassLoader.preDefineClass(ClassLoader.java:665)

at java.lang.ClassLoader.defineClass(ClassLoader.java:758)

at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)

at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)

at java.net.URLClassLoader.access$100(URLClassLoader.java:73)

at java.net.URLClassLoader$1.run(URLClassLoader.java:367)

at java.net.URLClassLoader$1.run(URLClassLoader.java:361)

at java.security.AccessController.doPrivileged(Native Method)

at java.net.URLClassLoader.findClass(URLClassLoader.java:360)

at java.lang.ClassLoader.loadClass(ClassLoader.java:424)

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)

at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

at NaverAPITest.NAPITest.test.test(test.java:35)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:483)

at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)

at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)

at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)

at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)

at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)

at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)

at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)

at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)

at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)



찾아보니 라이브러리 중복으로 인해 발생된다고 한다.

Junit의 라이브러리가 문제라는데..

org.hamcrest.Matchers

아무튼 JUnit4 저걸 통째로 remove하여 제거하였다.


그리고 다시 실행했더니 웬 에러???

pom.xml을 가봤더니 Junit 3.8.1 로 되어있었다. 


그래서 저걸 지워버리고

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

</dependency>

이걸 추가해주었더니 에러가 사라졌다!

이제 실행하니 잘되었따




반응형
반응형




버거킹 영수증을 받아보면 하단에 설문조사코드가 있습니다.


설문을 마치면 단품으로 세트를 먹을 수 있는 코드를 발급받게 되는데요


설문조사를 하는 것도 은근히 시간이 걸리는 것 같아 한번 시도해보았습니다.


Selenium 을 사용하였고 스윙으로 UI를 대충 만들어보았습니다.


설문이 끝나면 발급코드가 표시되는 간단한 프로그램입니다.


자바 환경 설치가 필수로 되어 있어야 하며


C: 또는 D: 드라이브 경로에 

chromedriver.exe가 존재해야 합니다.


chromedriver.exe






시연 영상



http://youtu.be/NtjBOtUwknM



셀레니움 부분 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package com.burger.king;
 
import java.io.File;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
 
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.Condition.*;
 
@FixMethodOrder (MethodSorters.NAME_ASCENDING)
 
public class survey {
    private static WebDriver driver;
    
    static String receiptNum="";
    static String url="https://kor.tellburgerking.com";
    
    
    public void inputNumber(String number){
          // 텍스트 필드값 가져오기
        receiptNum = number;
    }
 
 
    @BeforeClass
    public static void setUp() throws Exception {
        
        File file = new File("c:/chromedriver.exe");
        File file2 = new File("d:/chromedriver.exe");
           if(file.isFile()){         
               System.setProperty("webdriver.chrome.driver""c:/chromedriver.exe"); //크롬 드라이버 파일 경로설정
        }else if(file2.isFile()){
            System.setProperty("webdriver.chrome.driver""d:/chromedriver.exe"); //크롬 드라이버 파일 경로설정    
        }else{
            //안내문
            runner.labelIntroduce.setText("C 또는 D드라이브에 chromedriver가 없습니다.\n");
        }
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //응답시간 5초설정
        driver.get(url); 
        
         driver.manage().window().maximize();
    }
    
    public static void login() throws InterruptedException   {
        boolean boo = true;
        WebElement NextButton = driver.findElement(By.id("NextButton"));
        NextButton.click();   
        
        driver.findElement(By.id("CN1")).sendKeys(receiptNum);  //ID
        Thread.sleep(1000);
        driver.findElement(By.id("NextButton")).click();
        
        
        int i = 0;
        while(boo){
            try{
                
                boolean radioButtonHolder = driver.findElements(By.className("radioButtonHolder")).size() > 0;
                boolean checkboxBranded = driver.findElements(By.className("checkboxBranded")).size() > 0;
                boolean radioBranded = driver.findElements(By.className("radioBranded")).size() > 0;
                boolean checkCode = driver.findElements(By.className("ValCode")).size() > 0;
                boolean Next = driver.findElements(By.id("NextButton")).size() > 0;
                 if(radioButtonHolder){
                     driver.findElement(By.className("radioButtonHolder")).click();
                 }
                 else if(checkboxBranded){
                     driver.findElement(By.className("checkboxBranded")).click();
                 }
                 else if(radioBranded){
                     driver.findElement(By.className("radioBranded")).click();
                 }
                 if(Next)
                     driver.findElement(By.id("NextButton")).click();
                 if(checkCode)
                     boo = false;
                 System.out.println(i++);
            }catch (NoSuchElementException e){
                
            }
           
        }
        
        String checkCode = driver.findElement(By.xpath("//*[@id='FNSfinishText']/div/p[2]")).getText();
 
        runner.labelIntroduce.setText(checkCode);
    }
    
 
    @Test
    public static void run() throws Exception {
        login();
        Thread.sleep(500);
    }
 
    @AfterClass
    public static void tearDown() throws Exception {
        driver.quit();
    }
 
}
cs



스윙UI 부분


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package com.burger.king;
 
import javax.swing.*;
 
import com.burger.king.runner;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
 
class runner extends Thread{
    Simulator simul = new Simulator();
    public static    JLabel labelIntroduce;
    public static survey survey = new survey();
    public  static  JTextField tf_receiptNum;
    public static JLabel submit,number;
    public boolean check = true
    public void run(){
        // 텍스트 필드값 가져오기
        String receiptNum = tf_receiptNum.getText();
        try {
            survey.setUp();
        } catch (Exception e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        survey.inputNumber(receiptNum);
        try {
            survey.run();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    
}
 
class JPanel033 extends JPanel{        
    runner thread = new runner();
    
    // 클래스 멤버 필드 설정
    private    JLabel name;
    private    JLabel id;
            
    
    private    JButton buttonSave;
    private    JButton buttonStop;
    public boolean check = true
    
    public JPanel033() {         
        
        setLayout(null);
        
        // 라벨
        name = new JLabel("by. yonoo");
        name.setSize(10020);   
        name.setLocation(20);
        
        id = new JLabel("설문조사코드: ");
        id.setBounds(10,30,100,20);
        
        // 텍스트 필드
        runner.tf_receiptNum = new JTextField();             
        runner.tf_receiptNum.setBounds(100,30,200,20);
        
        thread.labelIntroduce = new JLabel("=");
        thread.labelIntroduce.setBounds(10,50,280,20);
       
            
        // 버튼        
        buttonSave = new JButton("시작");
        buttonSave.setBounds(80,80,100,20);
        buttonSave.addActionListener(new EventHandlerSave());   
        
        buttonStop = new JButton("정지");
        buttonStop.setBounds(220,80,100,20);
        buttonStop.addActionListener(new EventHandlerStop());   
        
        add(name);
        add(thread.labelIntroduce);
        
        add(id);
        add(thread.tf_receiptNum);
        
        add(buttonSave);
        add(buttonStop);
        
    }
    
    class EventHandlerSave implements ActionListener{     // 
        public void actionPerformed(ActionEvent e){
//            try {
//                thread.start();    
//            } catch (Exception e1) {
//                // TODO Auto-generated catch block
//                e1.printStackTrace();
//            }
            
            if(check){
                thread.start();    
            }else{
                runner thread = new runner();
                thread.start();    
                check = true;
            }
        }
    }   
    class EventHandlerStop implements ActionListener{     // 
        public void actionPerformed(ActionEvent e){
            check = false;
            System.out.println(check);
            thread.interrupt();
            System.out.println("정지!");
//            System.exit(1);
            
        }
    } 
    
}
 
 
public class Simulator extends JFrame{
    
    public JPanel033 jpanel03 = null;
   
    public static void main(String[] args) {
        Simulator win = new Simulator();
        
        win.setTitle("BurgerKing Survey Automation");
        win.jpanel03 = new JPanel033();
        
        URL imageURL = Simulator.class.getClassLoader().getResource("burger.png");
        System.out.println(imageURL);
        ImageIcon img = new ImageIcon(imageURL);
        win.setIconImage(img.getImage());
        
        win.add(win.jpanel03);
 
        win.setSize(400,150);
        win.setVisible(true);
        win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
        
    }
    
}
 
cs

반응형
반응형




자바 스윙에서 JPasswordField 필드를 사용하면 암호입력시 * 별표로 표시할 수 있는데 이 가려지 값을 가져오는 방법



tf_pw = new JPasswordField();       
tf_pw.setEchoChar('*');



이런 식으로 암호 입력시 * 별표로 가려지게 한다음



 String pw = "";
  
//tf_pw 필드에서 패스워드를 얻어옴, char[] 배열에 저장
char[] secret_pw = tf_pw.getPassword(); 

//secret_pw 배열에 저장된 암호의 자릿수 만큼 for문 돌리면서 cha 에 한 글자씩 저장
     for(char cha : secret_pw){         
         Character.toString(cha);       //cha 에 저장된 값 string으로 변환
       //pw 에 저장하기, pw 에 값이 비어있으면 저장, 값이 있으면 이어서 저장하는 삼항연산자
         pw += (pw.equals("")) ? ""+cha+"" : ""+cha+"";   
     }



이렇게 저장한 후 System.out.println(pw)로 찍어보면 입력된 암호가 나타난다.



반응형

+ Recent posts