자바스크립트 배열

 

자바스크립트 배열이 다른 언어와 다른 점 2가지
1 배열 내부의 데이터 타입이 서로 다를 수 있다.
2 배열의 크기는 동적으로 변경될 수 있다.

 


배열 생성

// 배열 생성 (빈 배열)
var arr = []; 
혹은
var arr = new Array(); 

// 배열 생성 (초기 값 할당)
var arr = ['zero', 'one', 'tow']; 

 


배열 추가 

Array.push(), Array.unshift(), Array.splice()

arr.push('d'); // 배열의 끝에 요소를 추가
arr.unshift('d'); // 배열의 앞쪽에 요소를 추가
arr.splice(2, 0, 'd'); // index 2 ('c')의 위치에 요소를 추가

 


배열 삭제 

Array.pop(), Array.shift(), Array.splice()

 

arr.pop(); // 배열의 마지막 요소를 제거
var popped = arr.pop(); // 제거한 요소를 반환 받을 수 있음
arr.shift(); // 배열의 첫번째 요소를 제거
var shifted = arr.shift(); // 제거한 요소를 반환 받을 수 있음
arr.splice(1, 2); // index 1 부터 2개의 요소를 제거
removed = arr.splice(1, 2); // 제거한 요소를 반환 받을 수 있음


 

'JavaScript' 카테고리의 다른 글

JSON  (0) 2021.08.09
자바스크립트 객체(생성, 접근, 삭제)  (0) 2021.08.09
javascript 문자열, 숫자 형변환  (0) 2021.05.16
javascript 현재 날짜 구하기  (0) 2021.05.16
자바스크립트의 변수  (0) 2021.01.17

자바스크립트 객체

 

자바스크립트에서 원시 타입을 제외한 모든 데이터 타입(객체, 함수, 배열, 정규표현식 등)은 객체다.
객체는 여러가지 값을 가질 수 있으며, 함수도 가질 수 있다.

 

객체가 보유한 값을 '프로퍼티'라고 하며, 객체가 보유한 함수를 '메서드'라고 한다.
(둘다 프로퍼티라고 하기도 한다)

 

객체의 프로퍼티와 메서드들은 '키값'으로 구분된다.

var object ={ key1: value1, key2: value2, ... }

 


객체 생성하는 법

 

 

1. 중괄호 { } 안에 key:value를 쉼표(,)로 구분하여 만든다.

var myObj = { name: '조', age: 20, hello: function(){ 
	return `이름은 ${this.name}이고, 나이는 ${this.age}입니다.`; }
};
console.log(myObj); // { name: '조', age: 20, hello: [Function: hello] }

 

2. new 연산자를 통해 Object객체의 생성자함수를 호출한다.

var myObj = new Object(); 
myObj.name = '조'; 
myObj['age'] = 20; 
myObj.hello = function(){ 
	return `이름은 ${this.name}이고, 나이는 ${this.age}입니다.`; 
}; 
console.log(myObj); // { name: '조', age: 20, hello: [Function] }

 

3. 중괄호 { }를 사용하여 빈 객체 생성

var myObj = {};
myObj['name'] = '조';

 


객체 접근하는 법

 

마침표로 프로퍼티에 접근하거나
대괄호[ ] 사이에 키값을 '문자열'로 넣어 접근한다.

myObj.name; // '조' 
myObj.age; // 20 
myObj.hello(); // '이름은 조이고, 나이는 20입니다.'

myObj['name']; // '조'
myObj['age']; // 20
myObj['hello'](); // '이름은 조이고, 나이는 20입니다.'

 


객체 프로퍼티 생성하는 법

 

마침표로 프로퍼티를 생성하거나 대괄호[ ] 사이에 키값을 '문자열'을 넣어 생성한다.

myObj.name1= '조1';
myObj.age1=21;
myObj.hello1 = function(){return 'hello1'};

myObj['name2'] = '조2';
myObj['age2']=  22;
myObj['hello2'] = function(){return 'hello2'};

 


객체 프로퍼티 삭제하는 법

 

delete 연산자를 사용하여 객체의 프로퍼티나 메서드를 제거한다.

delete myObj.name1;
delete myObj.age1;
delete myObj.hello1;

delete myObj['name2'];
delete myObj['age2'];
delete myObj['hello2'];

'JavaScript' 카테고리의 다른 글

JSON  (0) 2021.08.09
자바스크립트 배열(생성, 추가, 삭제)  (0) 2021.08.09
javascript 문자열, 숫자 형변환  (0) 2021.05.16
javascript 현재 날짜 구하기  (0) 2021.05.16
자바스크립트의 변수  (0) 2021.01.17

 

문자로 검색

SELECT * FROM table WHERE name LIKE CONCAT('%', '문자', '%');

 

오늘자만 검색

SELECT * FROM table WHERE reg_date > CURRENT_DATE()

'SQL' 카테고리의 다른 글

MyBatis(parameterType,resultType,resultMap)  (0) 2021.01.17

난독화를 하는 데 사용되었던 코드를 기록.     (자바)   (SVN, 난독화 관련)

 

 

요약

1. SVN 로그인, 해당 파일 다운로드 JAVA 코드

2. window 혹은 linux에 CLI 명령어 입력하는 JAVA코드

3. 파일에 text입력하는 JAVA 코드

4. 원하는 파일만 문자열로 받아 나머지는 삭제하는 JAVA코드 

5. 빈폴더 삭제하는 JAVA코드 

6. 압축하여 다운로드 받는 JAVA코드

 

 

 


 

            DAVRepositoryFactory.setup();
            String url = ---------url--------------;
            String name =---------id------------;
            String password = -----------pw----------;
            SVNRepository repository = null;
            try {
                repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
                ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
                repository.setAuthenticationManager(authManager);
                repository.testConnection();
            } catch (SVNAuthenticationException e) {
                return -1;
            } catch (SVNCancelException e) {
                return -2;
            }

자바 구현체에 url, id, pw를 받아서 SVN에 로그인이 가능한지 확인하는 코드.

(아이디가 없으면 -1을 return한다.)

 

 

 


 

        SVNURL url = -----------------url----------------------;
        SVNClientManager clientManager = SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(true), id, pw);
        File localRepositoryDir = new File(-----------directory---------------------);
        try {
            long checkoutRevision = clientManager.getUpdateClient().doCheckout(url, localRepositoryDir, SVNRevision.HEAD, SVNRevision.HEAD, SVNDepth.INFINITY, true);
        } catch (SVNAuthenticationException e) {
            result = -1;
        } catch (SVNCancelException e) {
            result = -2;
        }

지정된 SVN url에 권한이 있는지 확인 후 해당 url의 파일들을 directory경로에 다운로드 받아줌.

(아이디 혹은 권한이 없으면 -1 반환)

 

 

 


 

    public static void execute(String cd, String path, String command, String source, String output, String savePath, String domain) {
        Process process = null;
        Runtime runtime = Runtime.getRuntime();
        StringBuffer successOutput = new StringBuffer(); // 성공 스트링 버퍼
        StringBuffer errorOutput = new StringBuffer(); // 오류 스트링 버퍼
        BufferedReader successBufferReader = null; // 성공 버퍼
        BufferedReader errorBufferReader = null; // 오류 버퍼
        String msg = null; // 메시지

        List<String> cmdList = new ArrayList<String>();

        // 운영체제 구분 (window, window 가 아니면 무조건 linux 로 판단)
        if (System.getProperty("os.name").indexOf("Windows") > -1) {
            cmdList.add("cmd");
            cmdList.add("/c");
        } else {
            cmdList.add("/bin/sh");
            cmdList.add("-c");
        }

        cmdList.add(cd + " " + path + " " + "&&" + " " + command + " " + source + " " + output + " " + savePath + " " + " " + domain);

        String[] array = cmdList.toArray(new String[cmdList.size()]);

        try {

            // 명령어 실행
            process = runtime.exec(array);

            // shell 실행이 정상 동작했을 경우
            successBufferReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "EUC-KR"));

            while ((msg = successBufferReader.readLine()) != null) {
                successOutput.append(msg + System.getProperty("line.separator"));
            }

            // shell 실행시 에러가 발생했을 경우
            errorBufferReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "EUC-KR"));
            while ((msg = errorBufferReader.readLine()) != null) {
                errorOutput.append(msg + System.getProperty("line.separator"));
            }

            // 프로세스의 수행이 끝날때까지 대기
            process.waitFor();

            // shell 실행이 정상 종료되었을 경우
            if (process.exitValue() == 0) {
                System.out.println("성공");
                System.out.println(successOutput.toString());
            } else {
                //shell 실행이 비정상 종료되었을 경우
                System.out.println("비정상 종료");
                System.out.println(successOutput.toString());
            }
            // shell 실행시 에러가 발생
            if (errorOutput.length() > 0) {
                //shell 실행이 비정상 종료되었을 경우
                System.out.println(errorOutput.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                process.destroy();
                if (successBufferReader != null)
                    successBufferReader.close();
                if (errorBufferReader != null)
                    errorBufferReader.close();

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

window 혹은 linux에 CLI 명령어를 입력하는 코드.

 

 


 

 

        String obFile = ----------필요한 파일들 파일명---------------;

        File f = new File(--------svn에서 받아온 파일들 경로----------------);
        ArrayList<String> subFiles = new ArrayList<String>();

        if (!f.exists()) {
            return -1;
        }
        //하위 디렉토리 검색
        findSubFiles(f, subFiles);

        File file = null;

        //파일 화이트리스트에 없으면 삭제
        for (String filePath : subFiles) {
            file = new File(filePath);
            if (file.exists() && file.isFile()) {
                try {
                    if (obFile.contains(file.getName())) {

                        //JS에 주석달기 start----------------------------------------------
                        String dummy = ""; // 새로 써지는 텍스트 저장 변수

                        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                        Date time = new Date();
                        String dt = format1.format(time);

                        String c_dt = "/*20210314*/";
                        String c_obIp = "/*100.000.000*/";
                        String c_obProjectNm = "/*jodonggu*/";
                        String c_userId = "/*jodongddng*/";

                        try {
                            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

                            String line;

                            for (int i = 0; i < 50000; i++) { // 5만줄까지 제한
                                line = br.readLine(); // 읽으며 이동

                                if (null == line) { // 읽을 것이 없으면 break
                                    break;
                                }

                                String temp_text = "";

                                if (i == 0) { // 첫번째 줄이라면
                                    temp_text = line;
                                    line = c_userId + "\r\n" + c_obProjectNm + "\r\n" + c_obIp + "\r\n" + c_dt + "\r\n" + temp_text; // 새 문장을 넣고 기존문장은 아랫줄에
                                }
                                dummy += (line + "\r\n"); // dummy에 저장
                            }

                            FileWriter fw = new FileWriter(file.getCanonicalPath());
                            fw.write(dummy);

                            fw.close();

                            br.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                      //JS에 주석달기 end----------------------------------------------
                    } else {
                        //삭제
                        File deleteFile = new File(file.getCanonicalPath());
                        deleteFile.delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

 

폴더 구조에서 필요한 js파일은 맨 윗줄에 주석을 달아 남기고 

필요 없는 파일은 삭제를 하는 재귀 코드

 

 

 

 

 

 

        //디렉토리에 파일 없으면 삭제
        for (String filePath : subFiles) {
            file = new File(filePath);
            if (file.exists() && file.isDirectory()) {
                try {
                    File fileList = new File(file.getCanonicalPath());
                    String[] files = fileList.list();

                    if (files.length > 0) {
                    } else {
                        fileList.delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

그 후 디렉토리에 파일이 없다면 디렉토리를 삭제하여 빈 폴더를 정리 

 

 

 

 

        // 압축
        String zipPath = --------------압축할 zip파일 경로---------------;

        ZipUtil.pack(new File(zipPath), new File(zipPath + ".zip"));

그 후 정리된 폴더를 압축.

압축은 ZipUtil이라는 라이브러리를 다운받아 사용

 

 

 

 

    public void dwFile(Map<String, Object> params) throws Exception {

        OutputStream outStream = null;
        FileInputStream fis = null;
        StringBuffer sb = new StringBuffer();
        sb.append(--------------zip경로 -----------------------);
        sb.append(File.separator);
        String target = ---------zip 파일 이름 -------------------------;
        try {
            outStream = response.getOutputStream();
            File file = new File(sb.toString() + target + ".zip");
            fis = new FileInputStream(file);
            response.setContentType("application/zip");
            DownloadUtils.setDisposition(target + ".zip", request, response);
            //response.setHeader("Content-Transfer-Encoding", "binary");
            String downFileNm = new String(target.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + downFileNm + ".zip;");
            FileCopyUtils.copy(fis, outStream);
            outStream.flush();
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");

        } catch (Exception e) {
            LOGGER.error("파일 다운로드 오류");
            throw new BusinessException("파일 다운로드에 실패하였습니다.");

        } finally {
            if (fis != null) {
                fis.close();
            }
            if (outStream != null) {
                outStream.close();
            }
        }
    }

마지막으로 zip 파일 다운로드 받기 

'Project > obfuscator' 카테고리의 다른 글

javascript-obfuscator 난독화 1  (0) 2021.05.16

https://velog.io/@ifyouseeksoomi/CS-Operating-System-Unix-Linux-Ubuntu-macOS-windows

 

[CS] Operating System (Unix, Linux, Ubuntu, macOS, windows)

201206 - 운영 체제 1

velog.io

Unix, Linux, Ubuntu, macOS, windows
--------------------------------------------------------------------------------------------------------------

Xshell ?????
텔넷/ SSH 프로토콜로 리눅스 원격 호스트에 접속할 수 있는 윈도우용 터미널 에뮬레이터

국내 기업에서 개발된 프로그램으로 제품 한글화는 물론이고 ssh 접속 시 유니코드(utf-8)지원으로 한글로 설정된 리눅스에도 문제없이 접속 할 수 있다.



SSH???
SSH란 Secure Shell Protocol, 즉 네트워크 프로토콜 중 하나로 컴퓨터와 컴퓨터가 인터넷과 같은 Public Network를 통해 서로 통신을 할 때 보안적으로 안전하게 통신을 하기 위해 사용하는 프로토콜입니다. 



xftp ???????
파일 전송 클라이언트
https://jootc.com/p/20170529246

 

Xftp 파일전송 클라이언트로 간편하게 서버에 파일 전송하기 - JooTC

Xftp 인터페이스가 편리하고 어렵지 않게 쓸만한 국내 기업인 넷사랑컴퓨터의 FTP 클라이언트 입니다. Xftp는 여타 파일전송 프로그램과 다를 것 없이 FTP/SFTP 프로토콜을 지원하며 직관적이고 편리

jootc.com

 

 

System.out.println("UTF-8 -> EUC-KR        : " + new String(msgName.getBytes("UTF-8"), "EUC-KR"));
System.out.println("UTF-8 -> KSC5601       : " + new String(msgName.getBytes("UTF-8"), "KSC5601"));
System.out.println("UTF-8 -> X-WINDOWS-949 : " + new String(msgName.getBytes("UTF-8"), "X-WINDOWS-949"));
System.out.println("UTF-8 -> ISO-8859-1    : " + new String(msgName.getBytes("UTF-8"), "ISO-8859-1"));
System.out.println("UTF-8 -> MS949         : " + new String(msgName.getBytes("UTF-8"), "MS949"));
 
System.out.println("ISO-8859-1 -> EUC-KR        : " + new String(msgName.getBytes("ISO-8859-1"), "EUC-KR"));
System.out.println("ISO-8859-1 -> KSC5601       : " + new String(msgName.getBytes("ISO-8859-1"), "KSC5601"));
System.out.println("ISO-8859-1 -> X-WINDOWS-949 : " + new String(msgName.getBytes("ISO-8859-1"), "X-WINDOWS-949"));
System.out.println("ISO-8859-1 -> UTF-8         : " + new String(msgName.getBytes("ISO-8859-1"), "UTF-8"));
System.out.println("ISO-8859-1 -> MS949         : " + new String(msgName.getBytes("ISO-8859-1"), "MS949"));
 
System.out.println("EUC-KR -> UTF-8         : " + new String(msgName.getBytes("EUC-KR"), "UTF-8"));
System.out.println("EUC-KR -> KSC5601       : " + new String(msgName.getBytes("EUC-KR"), "KSC5601"));
System.out.println("EUC-KR -> X-WINDOWS-949 : " + new String(msgName.getBytes("EUC-KR"), "X-WINDOWS-949"));
System.out.println("EUC-KR -> ISO-8859-1    : " + new String(msgName.getBytes("EUC-KR"), "ISO-8859-1"));
System.out.println("EUC-KR -> MS949         : " + new String(msgName.getBytes("EUC-KR"), "MS949"));
 
System.out.println("KSC5601 -> EUC-KR        : " + new String(msgName.getBytes("KSC5601"), "EUC-KR"));
System.out.println("KSC5601 -> UTF-8         : " + new String(msgName.getBytes("KSC5601"), "UTF-8"));
System.out.println("KSC5601 -> X-WINDOWS-949 : " + new String(msgName.getBytes("KSC5601"), "X-WINDOWS-949"));
System.out.println("KSC5601 -> ISO-8859-1    : " + new String(msgName.getBytes("KSC5601"), "ISO-8859-1"));
System.out.println("KSC5601 -> MS949         : " + new String(msgName.getBytes("KSC5601"), "MS949"));
 
System.out.println("X-WINDOWS-949 -> EUC-KR     : " + new String(msgName.getBytes("X-WINDOWS-949"), "EUC-KR"));
System.out.println("X-WINDOWS-949 -> UTF-8      : " + new String(msgName.getBytes("X-WINDOWS-949"), "UTF-8"));
System.out.println("X-WINDOWS-949 -> KSC5601    : " + new String(msgName.getBytes("X-WINDOWS-949"), "KSC5601"));
System.out.println("X-WINDOWS-949 -> ISO-8859-1 : " + new String(msgName.getBytes("X-WINDOWS-949"), "ISO-8859-1"));
System.out.println("X-WINDOWS-949 -> MS949      : " + new String(msgName.getBytes("X-WINDOWS-949"), "MS949"));
                
System.out.println("MS949 -> EUC-KR        : " + new String(msgName.getBytes("MS949"), "EUC-KR"));
System.out.println("MS949 -> UTF-8         : " + new String(msgName.getBytes("MS949"), "UTF-8"));
System.out.println("MS949 -> KSC5601       : " + new String(msgName.getBytes("MS949"), "KSC5601"));
System.out.println("MS949 -> ISO-8859-1    : " + new String(msgName.getBytes("MS949"), "ISO-8859-1"));
System.out.println("MS949 -> X-WINDOWS-949 : " + new String(msgName.getBytes("MS949"), "X-WINDOWS-949"));

코드를 난독화 하는 프로젝트를 하게 되었다.

 

그 일련의 과정들 

 

(CLI로 하였을 때)


1. 난독화를 하기 위해 난독화 오픈소스 사용

https://github.com/javascript-obfuscator/javascript-obfuscator

 

javascript-obfuscator/javascript-obfuscator

A powerful obfuscator for JavaScript and Node.js. Contribute to javascript-obfuscator/javascript-obfuscator development by creating an account on GitHub.

github.com


2.  오픈소스를 위해 Ubuntu에 npm 설치

https://jjeongil.tistory.com/1275
https://d2fault.github.io/2018/04/30/20180430-install-and-upgrade-nodejs-or-npm/


3. 파일을 난독화 후 압축하여 다운로드를 하기 위해 ZIP 설치

https://araikuma.tistory.com/120


4. 설치를 다 하였지만 명령어가 실행되지 않음

https://stove99.github.io/nodejs/2019/09/30/yarn-global-command-not-found/ 

yarn 을 사용해 global 로 패키지 설치 후 설치한 패키지를 커맨드창에서 실행했을때 명령어를 찾을 수 없다면서 command not found 에러가 나는 경우가 있다.

npm i -g 와는 다르게 yarn 을 추가적으로 설정이 살짝 필요하다.

.bashrc 수정

.bashrc 파일 맨 끝에 PATH 추가

vi ~/.bashrc

# 맨 끝에 PATH 추가

export PATH="$PATH:`yarn global bin`"

# 저장후 나오기

# 변경내용 적용

source ~/.bashrc

 

이건 yarn을 사용할 때 하는 방법 


5. 그러나 여전히 안됨 (다시 npm으로 시도)

증상 : javascript-obfuscator: command not found


/root/node_modules/javascript-obfuscator/bin 위치에  javascript-obfuscator 파일이 있는 것을 발견

 

vi ~/.bashrc
export PATH="/root/node_modules/javascript-obfuscator/bin:$PATH"

source ~/.bashrc


https://asung123456.tistory.com/30

 

-명령어 등록 성공 -

 


6. 한글이 깨져서 다운로드 경로를 못찾음 

 

https://huskdoll.tistory.com/74
String downFileNm = new String(target.getBytes("UTF-8"), "ISO-8859-1");

 

자바단에서 Encoding 해줌 

 


7. SVN에 로그인을 해서 파일을 받아오는데 연결이 안됨

 

https://m.blog.naver.com/PostView.nhn?blogId=amabile29&logNo=221522544699&proxyReferer=https:%2F%2Fwww.google.com%2F

 

telnet명령어를 써서 연결이 안되는 것을 확인하고 방화벽이 막혀있는 것을 알게됨

내부 아이피를 알아내서 내부 아이피로 연결함 

 

 


8. 난독화를 할 때 사용자에게 이메일을 보내야 하는데 로컬에서 잘 되던게 was서버에서는 안됨

error :

이메일 정보 확인이 필요합니다.

Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate). Failed messages: javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)

 

 

해결

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> 
<property name="host" value="smtp.gmail.com" /> 
<property name="port" value="465" /> <!-- 587 -->
<property name="username" value="${mailSender.gmailId}" /> 
<property name="password" value="${mailSender.gmailPw}" /> 
<property name="javaMailProperties"> 
<props> 
                <prop key="mail.smtp.auth">true</prop> 
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.smtp.ssl.enable">true</prop>
                <prop key="mail.smtp.ssl.protocols">TLSv1.2</prop>
</props> 
</property> 
</bean>

 

port를 465로 prop key를 

                true</prop key="mail.smtp.ssl.enable">
                TLSv1.2</prop key="mail.smtp.ssl.protocols">

두 줄 추가 


 

 

 

특정 element 의 display 속성이 none 인지 아닌지 판단 할때 아래와 같이 사용

$('#myDiv').is(':visible');

display: none 일때는 false 를 반환 한다.

'라이브러리 > Jquery' 카테고리의 다른 글

jquery click event (선택자 1개 vs 2개)  (0) 2021.05.16
jquery .trigger() 함수  (0) 2021.05.16
제이쿼리 선택자, 함수  (0) 2021.05.16

+ Recent posts