2016년 8월 21일 일요일

java 파일 .txt 작성 및 폴더, 파일 관리 jUnit

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.junit.After;
import org.junit.Test;

public class ListFilesUtilTest {
    /**
     * 디렉토리에 존재하는 폴더와 파일들의 리스트
     * @param directoryName
     */
    public void listFilesAndFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            System.out.println(file.getName());
        }
    }
    /**
     * 디렉토리에 존재하는 모든 파일 리스트
     * @param directoryName
     */
    public void listFiles(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getName());
            }
        }
    }
    /**
     * 디렉토리에 존재하는 모든 폴더 리스트
     * @param directoryName
     */
    public void listFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isDirectory()){
                System.out.println(file.getName());
            }
        }
    }
    /**
     * 디렉토리 하위의 파일들과 하위 디렉토리 내에 존재하는 모든 파일들의 리스트
     * @param directoryName
     */
    public void listFilesAndFilesSubDirectories(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()){
                listFilesAndFilesSubDirectories(file.getAbsolutePath());
            }
        }
    }
    public void readText() {
   
            File file = new File("/Users/yisang/Documents/dev/spring/upload/filename.txt");
            StringBuffer contents = new StringBuffer();
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                String text = null;
                // repeat until all lines is read
                while ((text = reader.readLine()) != null) {
                    contents.append(text)
                        .append(System.getProperty(
                            "line.separator"));
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
           
            // show file contents here
            System.out.println(contents.toString());
       
    }
  //파일을 존재여부를 확인하는 메소드
    public static Boolean fileIsLive(String isLivefile) {
     File f1 = new File(isLivefile);
   
     if(f1.exists())
     {
      return true;
     }else
     {
      return false;
     }
    }
   
    //파일을 생성하는 메소드
    public static void fileMake(String makeFileName) {
    File f1 = new File(makeFileName);
    try {
    f1.createNewFile();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
   
    //파일을 삭제하는 메소드
    public static void fileDelete(String deleteFileName) {
    File I = new File(deleteFileName);
    I.delete();
    }
   
    //파일을 복사하는 메소드
    public static void fileCopy(String inFileName, String outFileName) {
     try {
      FileInputStream fis = new FileInputStream(inFileName);
      FileOutputStream fos = new FileOutputStream(outFileName);
     
      int data = 0;
      while((data=fis.read())!=-1) {
       fos.write(data);
      }
      fis.close();
      fos.close();
     
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   
    //파일을 이동하는 메소드
    public static void fileMove(String inFileName, String outFileName) {
     try {
      FileInputStream fis = new FileInputStream(inFileName);
      FileOutputStream fos = new FileOutputStream(outFileName);
     
      int data = 0;
      while((data=fis.read())!=-1) {
       fos.write(data);
      }
      fis.close();
      fos.close();
     
      //복사한뒤 원본파일을 삭제함
      fileDelete(inFileName);
     
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   
    //디렉토리의 파일 리스트를 읽는 메소드
    public static List<File> getDirFileList(String dirPath)
    {
     // 디렉토리 파일 리스트
     List<File> dirFileList = null;
   
     // 파일 목록을 요청한 디렉토리를 가지고 파일 객체를 생성함
     File dir = new File(dirPath);
   
     // 디렉토리가 존재한다면
     if (dir.exists())
     {
      // 파일 목록을 구함
      File[] files = dir.listFiles();
     
      // 파일 배열을 파일 리스트로 변화함
      dirFileList = Arrays.asList(files);
     }
   
     return dirFileList;
    }
   
   
    @Test
    public void main (){
        ListFilesUtilTest listFilesUtil = new ListFilesUtilTest();
        final String directoryLinuxMac ="/Users/yisang/Documents/dev/spring/upload";
        //Windows directory example
        final String directoryWindows ="C://test";
        listFilesUtil.listFiles(directoryLinuxMac);
    }
   
    @After
    public void writeTxt() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();

String content = "[" + dateFormat.format(date) + "] hey hey hey 안녕하니? /n ㅁㄴㅇㄹㅂ135-061243#@$!#$%@$^@$%^";

File file = new File("/Users/yisang/Documents/dev/spring/upload/filename.txt");

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

if (!file.exists()) {
file.createNewFile();
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
}else{


PrintWriter print_line = new PrintWriter(fw);
print_line.printf("%s" + "%n", content);
print_line.flush();
print_line.close();


// 파일의 쓰기/읽기 권한 체크
          if(file.canWrite()) System.out.println(file.getName() + "은 쓸 수 있습니다.");
          if(file.canRead()) System.out.println(file.getName()+ "은 읽을 수 있습니다.");
             
                // 객체의 파일, 폴더 여부 체크
                if(file.isFile()){
                    System.out.println(file.getName() + "은 파일입니다.");
                }else if(file.isDirectory()){
                    System.out.println(file.getName() + "은 폴더입니다.");
                }else{
                    System.out.println(file.getName() + "은 파일도 폴더도 아닙니다.");
                }
}

System.out.println("Done");

readText();
           
} catch (IOException e) {
e.printStackTrace();
}
}
}

2015년 1월 19일 월요일

MySql INT형 데이터 범위


MySQL INT형에 데이터입력시 범위초과 에러가 발생하여 INT형에 대해 정리해보았다.



type                   byte                  min                                       max
------------------------------------------------------------------------------------
TINYINT          1     -128                                   127   
SMALLINT       2     -32768                                32767
MEDIUMINT     3     -8388608                            8388607
INT                4     -2147483648                       2147483647
BIGINT           8      -9223372036854775808     9223372036854775807

=======================================================

2014년 12월 24일 수요일

CentOS에서 sudo 명령어 사용

CentOS는 일반사용자가 루트권한을 일시적으로 획득하는 sudo 명령어가 비활성 상태이다.
/etc/sudoers 파일을 수정하면 CentOS에서도 sudo를 이용할 수 있다.


[root@cet dev]$ ls -al /etc/sudoers
-r--r----- 1 root root 3381  3월 11  2014 /etc/sudoers

[root@cet dev]$ chmod u+w /etc/sudoers

[root@cet dev]$ ls -al /etc/sudoers
-rw-r----- 1 root root 3381  3월 11  2014 /etc/sudoers


[root@cet dev]# tail /etc/sudoers
## Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL

## Allows members of the users group to mount and unmount the
## cdrom as root
# %users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

## Allows members of the users group to shutdown this system
# %users  localhost=/sbin/shutdown -h now

/etc/sudoers 파일에 설정 추가

[root@cet ~]$ vi /etc/sudoers

# 특정 사용자가 sudo를 사용할 수 있도록 설정.
dev   ALL=(ALL)       ALL

# 그룹내에 모든 사용자가 이용할 수 있도록 설정.
%wheel  ALL=(ALL)       ALL

# 비밀번호 없이 사용
%wheel  ALL=(ALL)       NOPASSWD: ALL
dev   ALL=(ALL)       NOPASSWD: ALL

/etc/sudoers 파일의 퍼미션은 440이어야 하며 퍼미션 조정이 되어 있지 않으면 아래와 같은 에러가 발생.
[dev@cet ~]$ sudo tail /etc/sudoers
sudo: /etc/sudoers is mode 0640, should be 0440
sudo: no valid sudoers sources found, quitting

root 계정으로 로그인 후 퍼미션 조정
[dev@cet ~]$ su -
[root@cet ~]# chmod u-w /etc/sudoers

2014년 12월 14일 일요일

MacVim 관련 단축키



.vimrc에 직접 설정한 단축키

noremap <c-tab> :tabnext<cr> = vim의 탭이동 ( ctrl + tab )
noremap <c-n> :NERDTreeToggle<CR> = NERDTree 토글 단축키 (ctrl + n)


Vim command모드 단축키

i : insert모드로 변경(커서앞)
a : insert모드로 변경(커서뒤)
A : insert모드로 변경(라인마지막)
x : 커서에 있는 문자 삭제
dd : 한개 라인 삭제
yy : 라인 복제
p : 삭제했거나 복제한 라인 붙여넣기(커서뒤)
P : 삭제했거나 복제한 라인 붙여넣기(커서앞)

/ : /뒤에 오는 문자열 검색
G : 문서의 마지막 라인으로 이동
     1G : 문서의 첫라인으로 이동
     100G : 100번째 라인으로 이동
:wq : 저장하고 나가기
:q! : 저장안하고 바로 나가기


NERDTree

T - NERDTree에서 탭 생성 
t - NERDTree 화면이 없는 탭 생성
gT, gt - Tab 이동


ctrl + q + w - 열려있는 창 닫기
ctrl + ww / ctrl wh - 창 간의 이동



2014년 12월 13일 토요일

iTerm + MacVim + python-mode

django의 잦은 command line 이용때문에 eclipse pydev 에디팅 대신 MacVim을 이용하기로 했다.

환경은 iTerm + MacVim + python-mode + 기타 번들 인스토

현재까지 작성된 .vimrc

"한글깨짐 방지
set enc=UTF-8

set fileencodings=UTF-8

set nocompatible              " be iMproved, required

filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

call pathogen#infect()
call pathogen#helptags()

" alternatively, pass a path where Vundle should install bundles
"let path = '~/some/path/here'
"call vundle#rc(path)

" let Vundle manage Vundle, required
Bundle 'gmarik/vundle'

" The following are examples of different formats supported.
" Keep bundle commands between here and filetype plugin indent on.
" scripts on GitHub repos
Bundle 'tpope/vim-fugitive'
Bundle 'Lokaltog/vim-easymotion'
Bundle 'tpope/vim-rails.git'
" The sparkup vim script is in a subdirectory of this repo called vim.
" Pass the path to set the runtimepath properly.
Bundle 'rstacruz/sparkup', {'rtp': 'vim/'}
" scripts from http://vim-scripts.org/vim/scripts.html
Bundle 'L9'
Bundle 'FuzzyFinder'
" scripts not on GitHub
Bundle 'git://git.wincent.com/command-t.git'
" git repos on your local machine (i.e. when working on your own plugin)
" python lint
Bundle 'klen/python-mode'
" directory
Bundle 'scrooloose/nerdtree'
" powerline
Bundle 'Lokaltog/powerline', {'rtp': 'powerline/bindings/vim/'}


filetype plugin indent on     " required
syntax on

noremap <c-tab> :tabnext<cr>
noremap <c-n> :NERDTreeToggle<CR>

" Python-mode
" Activate rope
" Keys:
" K             Show python docs
" <Ctrl-Space>  Rope autocomplete
" <Ctrl-c>g     Rope goto definition
" <Ctrl-c>d     Rope show documentation
" <Ctrl-c>f     Rope find occurrences
" <Leader>b     Set, unset breakpoint (g:pymode_breakpoint enabled)
" [[            Jump on previous class or function (normal, visual, operator modes)
" ]]            Jump on next class or function (normal, visual, operator modes)
" [M            Jump on previous class or method (normal, visual, operator modes)
" ]M            Jump on next class or method (normal, visual, operator modes)
let g:pymode_rope = 1

" Documentation
let g:pymode_doc = 1
let g:pymode_doc_key = 'K'

"Linting
let g:pymode_lint = 1
let g:pymode_lint_checker = "pyflakes,pep8"
" Auto check on save
let g:pymode_lint_write = 1

" Support virtualenv
let g:pymode_virtualenv = 1

" Enable breakpoints plugin
let g:pymode_breakpoint = 1
let g:pymode_breakpoint_key = '<leader>b'

" syntax highlighting
let g:pymode_syntax = 1
let g:pymode_syntax_all = 1
let g:pymode_syntax_indent_errors = g:pymode_syntax_all
let g:pymode_syntax_space_errors = g:pymode_syntax_all

" Don't autofold code
let g:pymode_folding = 0


2014년 11월 27일 목요일

Mac의 eclipse에 pydev3.x를 설치했는데도 메뉴에 나타나지 않는 문제

맥의 매버릭 이후 eclipse에 pydev3.x를 설치했으나 메뉴에 나타나지 않는 문제가 발생
JDK 1.7 설치로 해결



    1. Unistall PyDev
    2. Under Eclipse > preferences > Installed JREs you probably only see Java SE 6
    3. Download and install JDK 1.7 from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
    4. open terminal and run "/usr/libexec/java_home -v 1.7"
      this will return the directory in which JDK 1.7 reside, something like /Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home
    5. Under Eclipse > preferences > Installed JREs click "add", select "MacOS X VM", click "next"
    6. in JRE Home paste your version of /Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home, give it a name and click "Finish"
    7. Restart Eclipse and re-install PyDev.
http://stackoverflow.com/a/23671271


JDK를 잘못 설치했을 경우

#cd /Library/Java/JavaVirtualMachines
#sudo rm -rf jdk1.7.0_06.jdk

2014년 11월 25일 화요일

CentOS + Apache + mod_wsgi + python + django + mysql


1.django 프레임웍 설치

$ git clone https://github.com/django/django.git
$ cd django
$ python setup.py install
$ python
>>> import django
>>> print django.get_version()
1.7

2. django 프로젝트 생성 및 설정

설치 후 생성된 django-admin.py를 프로젝트 생성을 원하는 폴더로 이동 후 프로젝트 생성

$ python django-admin.py startproject samplepro

프로젝트명을 samplepro로 하였다. 다음처럼 디렉토리가 구성된다.

samplepro/
      manage.py
      samplepro/
          __init__.py
          settings.py
          urls.py
          wsgi.py

생성된 프로젝트를 django 자체서버를 통해 테스트
$ cd samplepro
$ python manage.py runserver 
  Validating models...

  0 errors found
  Django version 1.7, using settings 'samplepro.settings'
  Development server is running at http://127.0.0.1:8000/

  Quit the server with CTRL-BREAK.

웹 브라우져로 http://127.0.0.1:8000/ 에서 웹페이지를 확인


mysql을 사용하기 위한 python 인터페이스(MySql_python) 설치.

$ yum install mysql-devel
$ pip install mysql_python

프로젝트의 settings.py파일에 mysql 접속정보 입력
$ vi settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB명',                       
        'USER': 'USER명',                 
        'PASSWORD': '비밀번호',
        'HOST': '127.0.0.1',  
        'PORT': '3306', 
    }

  }

INSTALL_APPS
settings.py 파일을 보면 django 설치시에 기본적으로 설치된 프로그램이 표시된다.
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',

    'django.contrib.staticfiles',
)

django에 기본적으로 설치된 application을 사용하기 위해 데이터베이스 테이블을 사용할수 있게끔 설정이 필요

$ python manage.py syncdb
  Creating tables ...
  Creating table auth_permission
  Creating table auth_group_permissions
  Creating table auth_group
  Creating table auth_user_user_permissions
  Creating table auth_user_groups
  Creating table auth_user
  Creating table django_content_type
  Creating table django_session
  Creating table django_site

데이터베이스 테이블 생성이 완료되면 관리자 아이디/패스워드 설정을 한다.

  You just installed Django's auth system, which means you don't have any superusers defined.
  Would you like to create one now? (yes/no): yes
  Username (leave blank to use 'root'): 
  E-mail address: 
  Password:
  Password (again):
  Superuser created successfully.


3. mod_wsgi를 이용한 apache 연동

가. 웹서비스를 위한 아파치와의 연동을 위해 아파치의 apxs를 이용하여 mod_wsgi를 설치

# cd /usr/local/src/mod_wsgi-3.3
# ./configure --with-apxs=/usr/local/httpd/bin/apxs --with-python=/usr/local/python2.7/bin/python

# make && make install


나. 프로젝트 디렉토리에 django.wsgi 파일 생성

import os
import sys

sys.path.append('/home/newsb/public_html/sb_community')
sys.path.append('/home/newsb/public_html')

#os.environ['PYTHON_EGG_CACHE'] = '/home/newsb/public_html/.python-egg'
os.environ['DJANGO_SETTINGS_MODULE'] = 'sb_community.settings'

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


다. apache httpd.conf 모듈 추가와 프로젝트에 작성된 wsgi path 추가

# vi /usr/local/httpd/conf/httpd.conf

LoadModule wsgi_module modules/mod_wsgi.so


<VirtualHost *:80>
    ------------
    WSGIScriptAlias / /home/newsb/public_html/sb_community/django.wsgi
    <Directory /home/newsb/public_html/sb_community>
      Order allow,deny
      Allow from all

    </Directory>

</VirtualHost>          

$ /etc/rc.d/init.d/httpd restart

웹 접속확인.


4. django application 생성

 $ python manage.py startapp sample_app

그 결과 다음과 같은 구조로 파일들이 생성된다.

samplepro/
      manage.py
      samplepro/
            __init__.py
            settings.py
            urls.py
            wsgi.py
      sample_app/
            __init__.py
            models.py
            tests.py

            views.py


settings.py파일에 새로 생성한 application을 추가한다.

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sample_app',

)

application의 model 설정

application의 models.py 파일을 열어 django의 ORM(Object Relational Mapping) 기능을 이용하여 실제 데이터베이스 테이블과 맵핑하기 위한 모델을 작성한다

$ vi models.py

from django.db import models

class CommBoard(models.Model):
      subject = models.CharField(max_length=50, blank=True)
      name = models.CharField(max_length=50, blank=True)
      memo = models.CharField(max_length=200, blank=True)
      hits = models.IntegerField(null=True, blank=True)

      created_date = models.DateField(null=True, blank=True)

마이그레이션 작업내용을 만든다.
$ python manage.py makemigrations 
Migrations for 'sample_app':
  0001_initial.py:
    - Create model CommBoard

마이그레이션 작업내용을 실행시켜 mysql 테이블을 생성시킨다.
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, contenttypes, board, auth, sessions
Running migrations:
  Applying board.0001_initial... OK