2013년 10월 21일 월요일

java - implements Object.toString() methods

0. Implements toString() methods
JAVA에서 System.out.println()으로 객체를 출력하면 해당 객체의 toString() method가 호출되어 출력이 됩니다. 해당 method를 override 하지 않았다면 객체의 이름과 Hashcode가 출력이 됩니다. 객체의 맴버 변수가 많을 때 편하게 toString()을 override 해보죠.
Apache commons project에 해당 내용이 있습니다.

1. The Commons Lang Package
http://commons.apache.org/proper/commons-lang/

The standard Java libraries fail to provide enough methods for manipulation of its core classes. Apache Commons Lang provides these extra methods.
Lang provides a host of helper utilities for the java.lang API, notably String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization and System properties. Additionally it contains basic enhancements to java.util.Date and a series of utilities dedicated to help with building methods, such as hashCode, toString and equals.

2. Class ToStringBuilder
아래는 API 문서의 내용입니다. (http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/ToStringBuilder.html)
Assists in implementing Object.toString() methods.
This class enables a good and consistent toString() to be built for any class or object. This class aims to simplify the process by:
  • allowing field names
  • handling all types consistently
  • handling nulls consistently
  • outputting arrays and multi-dimensional arrays
  • enabling the detail level to be controlled for Objects and Collections
  • handling class hierarchies
 이렇게 간단하게 사용하면 됩니다. 이건 JAVA reflection을 사용한 예제 입니다. reflection 이란 쉽게 말해 runtime에 java object의 정보를 가공하거나 가져올 수 있는 기능입니다. JAVA Framework Spring의 dependency injection, eclipse의 자동 완성 기능 같은 것도 이런 reflection API를 JAVA가 제공하기 때문에 가능한 것이죠.
public String toString() {
    return ToStringBuilder.reflectionToString(this);
}
이런 형식으로 출력되죠.
Person@7f54[name=Stephen,age=29,smoker=false]
 다만 explicitly 하게 사용하는게 성능상 좋다고 합니다.
Alternatively, there is a method that uses reflection to determine the fields to test. Because these fields are usually private, the method, reflectionToString, uses AccessibleObject.setAccessible to change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are set up correctly. It is also slower than testing explicitly.

2013년 10월 17일 목요일

excel - File formats that are supported in Excel

0. JAVA Excel API
 JAVA Excel API크게 두가지가 있다.
1. Exception in thread "main" java.lang.IllegalArgumentException: Sheet index (0) is out of range (0..-1)
 그런데 위 API를 사용하던 중 위 에러를 만나게 되었는데, 삽질도 이런 삽질이 없다. -_-; 
 원인은 Excel 2007 부터 다양한 포맷을 지원하기 때문인데 POI의 overview를 보면..
HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
 위와 같이 나와 있는데 결국은 OOXML 파일 포맷을 지원한다는 말이다.
 즉 파일 확장자는 xls 이지만 파일 포멧을 확인하지 않고 작업을 하면 위의 에러를 만나게 된다.

2. File formats that are supported in Excel
http://office.microsoft.com/en-us/excel-help/file-formats-that-are-supported-in-excel-HP010014103.aspx
 위 사이트를 방문해 보면 Excel도 크게 Excel formats, Text formats, Other formats, Clipboard formats 이렇게 나눠져 있는 것을 알수 있다. 작업할 excel 파일을 열고 save as 해보면 어떤 포맷으로 저장되어 있는지 확인 할 수 있다.

3. JAVA HTML Parser
저의 경우 Excel 파일을 가장한 HTML 파일이더군요. 그래서 이번에는 HTML Parser가 필요합니다. jsoup 이라는 library가 있네요.
jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.
http://jsoup.org/

2013년 10월 15일 화요일

aes - java, actionscript(flex), javascript

0. AES 
Web Server/Client 간 암호화된 메시지를 전달하기 위하여 AES (Advanced Encryption Standard)를 사용하였습니다. 암호화 방법은 AES/ECB/PKCS5Padding을 기준으로 합니다.

Java, Javascript, Actionscript(FLEX) AES example download --> Click

1. JAVA
javax.crypto.*의 함수를 사용했습니다.

2. Actionscript
as3crypto라는 프로젝트 (https://code.google.com/p/as3crypto/)를 참고했습니다.
제가 첨부한 코드를 사용하기 위해서는 위 사이트에서 as3crypto.swc lib를 다운받아 프로젝트에 추가해야 합니다.

3. Javascript
crypto-js 프로젝트 (https://code.google.com/p/crypto-js/) 를 참고 했습니다.
For the key, when you pass a string, it's treated as a passphrase and used to derive an actual key and IV. Or you can pass a WordArray that represents the actual key. If you pass the actual key, you must also pass the actual IV.
주의하실 부분이 위 내용처럼 string을 key로 넣게 되면 자동 생성되기 때문에 고정된 key를 사용할 수 없게 됩니다.  그래서 아래 처럼 사용했습니다.
var key = CryptoJS.enc.Hex.parse('6b6579'); // "key"

2013년 10월 6일 일요일

ria - flex vs html5

0. RIA - Rich Internet Applilcation
 rich Internet application (RIA) is a Web application that has many of the characteristics of desktop application software, typically delivered by way of a site-specific browser, a browser plug-in, an independent sandbox, extensive use of JavaScript, or a virtual machine. 
1. FLEX vs HTML5
 아래는 구글링을 통해서 제가 나름 정리한 FLEX/HTML5의 pros and cons 입니다.

FLEXHTML5
Maturitysince 2004WIP (work in progress)
Accuracyvery accuratestill a bit cumbersome
Toolsfamiliar tools for java developers (eclipse)not as advanced as FLEX
ThreadSingle threaded
(network IO requests are asynchronous and non-blocking, and hence this issue is not as significant as it first sounds )
Multithreaded
Pluginyesno
BrowseriOS most likely will never ship Flash player in Safari
(educated guess)
Maximum reach (browser / OS / platform)
- supported by mobile browsers
- Features not present in old browsers
Designernot muchCSS / HTML are designer friendly
Skills availabilitynot muchmany
WeightHeavyweight – Flex libraries required No plugin = lightweight
Interaction with HTMLrequires JavaScriptHTML5

Maturity/Accuracy - FLEX는 2004년 부터 출시 되어 다양한 분야에서 검증된 plugin 입니다. 아무래도 상용이다 보니 깔끔한 디자인과 다양한 라이브러리들이 제공되어 디테일한 화면 처리에 HTML5 보다는 강점이 있습니다.

Tools - FLEX는 Flash builder라는 개발 툴을 제공하는데, eclipse plugin 형식으로 되어 있어서 기존 java 개발자라면 익숙하게 개발을 진행할 수 있습니다.

Thread - 이쪽은 어떤 쪽으로 영향이 있을지 잘 모르겠습니다.

Plugin/Weight - FLEX는 browser plugin 형식으로 동작합니다. 그래서 처음 접속하게 되면 flash player가 설치가 되어 실행됩니다. 따라서 브라우저의 flash player의 버전에도 영향을 받게 됩니다. 또한 최초 실행시에 swf파일을 다운로드하게 됩니다. (flash player가 swf파일을 실행하는 구조) 이런점 때문에 아무래도 HTML5 보다는 무거워 지는 원인이 됩니다.

Browser - 잡스가 flash는 좋아하지 않았죠, safari에서는 동작안합니다.

Designer/Skills/Interaction with HTML - 이런 점들은 어떤 기술을 적용해야 하나 고민해야하는 관리자들이 고려해 보아야 할 부분입니다. 일단 FLEX 디자이너나 개발자들은 상대적으로 소수이기 때문에 적재 적소에 필요한 사람을 구하기 힘듭니다. 또한 기존 시스템(기존 페이지등)과 연동하기 위해서 FLEX와 별개로 JavaScript를 추가로 개발해야 될지도 모릅니다.
얼마전까지만 해도 FLEX를 사용하기 위해서 Flash Builder를 구입해야 했지만, 지금은 Apache project로 편입되어 무료가 되었는지도 확인이 필요합니다.

2013년 9월 26일 목요일

visual svn - backup script

1. backup script
echo off  
echo BACKUP SVN TO D:\SVN_BACKUP\DUMP 
pushd c:\svn_data 
for /d %%i in (*) do echo dump %%i & svnadmin dump %%i > d:\svn_backup\dump\%%i_%date%.dump 
popd

c:\svn_data에 repository가 있는 거고, d:\SVN_BACKUP\DUMP 폴더로 백업하는 SCRIPT 입니다.

2. restore
svnadmin create xxx 
svnadmin load xxx<yyy.dump

2013년 9월 23일 월요일

android - TextWatcher

0. TextWatcher
 User input을 처리할 때 phone number를 어떻게 처리하면 좋을까?
예를 들어 01112345678을 입력으로 받았을 때 011-1234-5678 이렇게 보여주고 싶다면? 안드로이드에서 기본적으로 PhoneNumberFormattingTextWatcher class를 제공해 주고 있다.
아래 코드 처럼 간단하다
    
    etPhone.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
1. Customize TextWatcher
 price를 입력한다고 했을 때 쉼표를 넣어 주는 것을 고려해 보자. 이것은 android에서 제공하지 않기 때문에 아래와 같이 만들어 보았다.
    
public class PriceFormattingTextWatcher implements TextWatcher{
    /**
     * Indicates the change was caused by ourselves.
     */
    private boolean mSelfChange = false;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        if (mSelfChange)
            return;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (mSelfChange)
            return;
    }

    @Override
    public synchronized void afterTextChanged(Editable s) {
        if (mSelfChange) {
            // Ignore the change caused by s.replace().
            return;
        }
        
        String formatted = null;
        
        if(s.length() > 0){
            NumberFormat nf = NumberFormat.getInstance();
            String userInput= ""+s.toString().replaceAll("[^\\d]", "");
            formatted = String.valueOf(nf.format(Float.parseFloat(userInput)));
        }
        if (formatted != null) {
            mSelfChange = true;
            s.setFilters(new InputFilter[]{});
            s.replace(0, s.length(), formatted, 0, formatted.length());
            mSelfChange = false;
        }
    }
}

1,234 에서 2를 삭제했을 때 제일 먼저 beforeTextChanged()가 호출 되고 이때 값은 1,234이다. 이후 onTextChanged() 가 호출되고 이때 값은 1,34이다. 

2. 주의사항

public abstract void afterTextChanged (Editable s)

Added in API level 1
This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively.
 사용자가 변경한 내용이 다시 callback 함수를 호출하여 무한 루프에 빠질 수 있으니 코드 작성에 주의해야 한다. 위 예제에서 mSelfChange 변수를 주목하자.

2013년 9월 5일 목요일

android - place fragments into the tabs (provided by action bar)

0. tab 속으로 fragment layout 넣기
  • http://developer.android.com/guide/topics/ui/actionbar.html#Tabs를 참고하면 action bar에 tabs을 추가하는 방법이 나와 있는데, 이대로 예제를 따라가다가 각 탭에 UI를 집어 넣어 보면 control들이 탭 속에 들어오는게 아니라 전체 activity 화면 위에 위치하게 된다.
1. How?
  • 문서의 예제인데 FragmentTransaction.add() 메소드를 호출할 때 layout에  android.R.id.content 를 넣어 줘서 그렇다. 이 부분을 fragment를 담을 layout으로 지정하면 tab 속에 fragment가 들어간다. 예를 들어 아래와 같이 activity layout xml파일에 추가한 R.id.fragment_container를 넣어주면 된다.
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:layout_gravity="center">
    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </LinearLayout>
</LinearLayout>

2013년 8월 30일 금요일

android - backward compatibility

0. Support library

The Android Support Library package is a set of code libraries that provide backward-compatible versions of Android framework APIs as well as features that are only available through the library APIs. Each Support Library is backward-compatible to a specific Android API level. This design means that your applications can use the libraries' features and still be compatible with devices running Android 1.6 (API level 4) and up. 
Android의 Design Principles은 http://developer.android.com/design/ 에 잘 나와 있는데, 이러한 디자인 철학은 Ice Cream Sandwich - Android 4.0 부터 적용이 되기 때문에 app을 기획하고 개발할 때 하위 호환성(backward compatibility)이 고민된다. 
다행히 support library를 통해서 상위 버전의 api를 사용할 수 있게 해준다.

1. Adding Support Libraries

Some Support Libraries contain resources beyond compiled code classes, such as images or XML files. For example, the v7 appcompat and v7 gridlayout libraries include resources. 
설정하는 건 http://developer.android.com/tools/support-library/setup.html 에 잘 나와 있다. 
위 내용 처럼 resource를 포함하는 library도 있는데, 이 경우 문서에 빠진 내용이 있어 삽질을 좀 했다.

 기본적으로 android-support-v7-appcompat라는 library project를 생성한 후 나의 project의 build-path에 추가하는 내용인데 아래 중 1번과 2번 사이에 Android property를 선택하라는 내용이 빠져있다 ㅠㅠ Java Build Path에서 해매질 마시길 ..


 * eclipse에서 library project가 현재 project와 다른 workspace에 있으면 참조가 안된다. 주의!!!!!!

2013년 8월 20일 화요일

oracle - drop user (schema)

0. drop oracle schema

schema export/import를 위해 schema를 삭제하려면?
SQL> drop user schema_name cascade;

 ORA-01940: cannot drop a user that is currently connected 발생시?
SQL> select sid, serial#, username, status from v$session where schemaname='schema_name'
SQL> alter system kill session 'sid, serial#' immediate;
1. create user
SQL> create user schema_name identified by passwd;
        SQL> grant dba to schema_name;

2013년 8월 16일 금요일

oracle - export, import (export data pump)

0. overview

  • database를 export/import 하는 방법이다. 이건 backup/restore랑 다르다. 예를 들어 postgreSQL에서는 backup/restore를 통해서 database migration이 가능한데, oracle은 export/import 해줘야 한다.
  • 과거에는 exp/imp 를 사용했는데, 이제는 expdp/impdp(oracle data pump)를 사용해 준다.
Oracle Data Pump is a newer, faster and more flexible alternative to the "exp" and "imp" utilities used in previous Oracle versions. In addition to basic import and export functionality data pump provides a PL/SQL API and support for external tables.
  • oracle documentation 을 좀 살펴보자. 사실 export/import는 간단한데 중간 중간에 여러 걸림돌이 있어서 찾아가면서 하는데 많이 힘들었다.
  • expdp/impdp 에 관한 매뉴얼도 역시 찾기 힘들었는데, 해당 메뉴얼은 document home > Information integration > Additional features > Utilites 문서에 나와 있다. 영어가 익숙하지 않아서 그런지 상상도 못한 곳에 문서가 있었다 -_-;

1. create user & grant DBA role

  • 처음 oracle을 설치한 환경이다. 설치 후 user를 생성해 준다.
sqlplus / as sysdba
SQL> create user username identified by password;
  •  권한을 준다. 권한에 대한 내용은 oracle documentation의 security 파트에 잘 나와 있다. 간편하게 모든 system 권한을 준다.
SQL> grant dba to username; 
  • DBA role 참고 
Provides all system privileges that were created with the ADMIN option.
This role is provided for compatibility with previous releases of Oracle Database. You can determine the privileges encompassed by this role by querying the DBA_SYS_PRIVS data dictionary view.
Note: Oracle recommends that you design your own roles for database security rather than relying on this role. This role may not be created automatically by future releases of Oracle Database.

2. DATA_PUMP_DIR

  • data pump를 사용할 때 oracle에서 사용하는 dir를 확인한다.
select * from dba_directories;
  • dump 파일의 위치는 위 조회 명령을 사용하면 나온다. directory_name이 data_pump_dir로 되어 있다.  

3. export

  • 간단하다. 당연히 관련 privilege 체크는 먼저 해줘야 한다.
expdp file=xxx.dmp log=xxx.log
  • 이 정도만 해주면 된다. option으로 table space, schema 등 어떤 레벨로 할지를 정할 수 있는데, 디폴트는 schema다.
  • data_pump_dir에 dmp 파일을 확인한다. 

4. import 

  • dmp 파일을 data_pump_dir에 copy 한다.
 impdp file=xxx.dmp

5. oracle documentation

  • http://www.oracle.com/pls/db112/homepage
  • 왼쪽 메뉴를 잘 봐야 한다. 현재 페이지는 getting started 페이지이고 여기 있는 문서들은 개요가 대부분이다. 예를 들어 dba essentials 에 있는 내용은 enterprise manager를 이용한 GUI 사용법들이다. 
  • sql 명령을 알고 싶다. 그러면 supporting documentation의 sql language reference를 본다.
  • 사실 predefined role, privilege 등을 보고 싶었는데 이 페이지의 문서에는 나와 있지 않다. 그럴때 왼쪽 메뉴의 database administration 하위의 security 페이지로 이동하여 문서를 찾는다. 
  • 아오!!

6. issue

  • 기존 database에 해당 동일한 schema가 있는 경우는 drop user 후 impdp 한다. 이때 version이 다른 경우 error가 발생할 수 있다.
  • 테스트 환경에서 발생한 문제로 11.2.0.1.0 --> 11.2.0.2.0 으로 impdp 할 때 timezone file이 달라 impdp가 안되었다. 이런 경우 zoneinfo 폴더의 timezlrg_xx.dat, timezone_xx.dat를 복사해서 넣어주면 해결된다. 버전은 아래와 같이 확인 가능하다.
select * from database_properties
  • 이러한 정보는 logfile=xxx.log 옵션을 주면 힌트를 얻을 수 있다.

2013년 7월 31일 수요일

postgreSQL - backup script

0. The password file

"The file .pgpass in a user's home directory or the file referenced by PGPASSFILE can contain passwords to be used if the connection requires a password (and no password has been specified otherwise). On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile)
This file should contain lines of the following format:"
hostname:port:database:username:password
-  backup을 위해서 password 파일을 참고해야 하며, 나의 경우: C:\Documents and Settings\Administrator\Application Data\postgresql에 있다.

- 혹은 파일을 복사해서 사용해도 된다. (아래 script에서는 d:\pgpass.conf로 복사해서 사용함)

1. pg_dump.bat

Everyday db dump script

  @echo off
   for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
     set dow=%%i
     set month=%%j
     set day=%%k
     set year=%%l
   )
   set datestr=%month%_%day%_%year%
   echo datestr is %datestr%
   
   set FILE=pgdump_%date%.backup
   echo backup file name is %FILE%
   SET PGPASSFILE=D:\pgpass.conf
   echo on
   pg_dump -i -U username -Fc -b -v -f %FILE% dbname

2.  pg_dumpall.bat

"The above mechanism is cumbersome and inappropriate when backing up an entire database cluster. For this reason the pg_dumpall program is provided. pg_dumpall backs up each database in a given cluster, and also preserves cluster-wide data such as users and groups." 
SET PGPASSFILE=D:\pgpass.conf
"PostgreSQL_PATH\bin\pg_dumpall.exe" -U username > .\db.out postgres"

2013년 7월 30일 화요일

tomcat - clear tomcat shutdown errors

0. Tomcat shutdown errors?


- tomcat shutdown.bat 실행했는데 tomcat console 창이 닫히지 않는다. 

 - console log를 살펴 보면 "심각: The web application [] appears to have started a thread named ......" 이라고 찍혀있는데 대부분 user thread 처리에 대한 내용이다.

 - 사실 shutdown 시 발생하는 에러는 심각한 내용이 아니라서 그냥 넘어 갈수도 있는데, nightly build script 작성시 골치가 아프다.

1. Java Thread (Thread VS. Daemon Thread)

- Java thread에 대한 이해가 선행되어야 한다.

- "JVM doesn’t wait for any daemon thread to finish before exiting"

- 아래는 shutdown 후 java process를 확인해 봤다. 아직 종료되지 않은 user thread가 3개가 있다. 

2. A thread named [Timer-0]

문제가 되는 code snippet이다. 한 번 살펴보자.

public class xxx {
public static void init(){
Timer t= new Timer();
t.scheduleAtFixedRate(new xxxTask (), new Date(), 1000);
}
}
public class xxxTask extends TimerTask {
@Override
public void run() {
......
}
}
- 원인: 위 코드는 TimerTask를 이용하여 user thread를 시작했으나 중지 하는 코드가 없다.

해결 방법: tomcat 종료 시 callback 호출을 통해 user thread를 중지시킨다.

- web.xml에 servlet context listener 등록하고
<listener>
    <listener-class>pkg.xxx</listener-class>
</listener>

- ServletContextListener 구현하면 된다.

public class xxx implements ServletContextListener{ @Override
public void contextInitialized(ServletContextEvent arg0) {
t= new Timer();
t.scheduleAtFixedRatenew xxxTask(), new Date(), 1000);
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {             t.cancel();
            xxxTask.cancel();
}
}

3. A thread named [pool-17-thread-1]

- 문제가 되는 서버는 MINA를 사용하고 있다. 아래는 MINA Architecture다.
이따가 계속

2013년 7월 25일 목요일

github - android + egit + github

0. overview

  •  this article gives you some ideas how to integrate GitHub with Android development environment.
  • I tried to make it simple as possible. I didn't use any of unnecessary tools like GitHub client, Git bash shell etc.
  • EGit has a few bugs. (like pushing to remote error) I recommend you to do exactly same procedure as shown.

1. Android 

With a single download, the ADT Bundle includes everything you need to begin developing apps:


  • Eclipse + ADT plugin
  • Android SDK Tools
  • Android Platform-tools
  • The latest Android platform
  • The latest Android system image for the emulato
    • plus EGit! (eclipse git plugin)

    2. GitHub

    • Make a new repository on GitHub
    https://help.github.com/articles/create-a-repo

    3. EGit (Git eclipse plugin)

    • create a local git repository (from Git Repository Exploring perspective)
    • create new android project
    • share (Team > Share Project > Git > )
    workspace is changed !! you need to adjust java build path.
    •  commit (Team > Commit)
     you can skip Add To Index.
    •  create remote (with GitHub repo URL)

    •  push to remote (Team > Remote > Push)

    4. visit GitHub and check repository

    • or see show in history (Team > Show In History)

    2013년 7월 23일 화요일

    eclipse - flash builder plugin

    0. 개요 
     - Adobe FLEX는 Flash builder를 사용하여 개발하는데 java 코드와 함께 개발하기 위해서 두개의 IDE를 띄우는 건 불편하다. 
     - Flash builder를 eclipse의 plugin으로 설치하여 사용한다. 

    1. install 
     - Flash builder 4.5 부터는 flash builder 설치 폴더에 플러그 인 설치 파일이 있다. (즉 flash builder를 설치해야 eclipse plug-in을 설치할 수 있다.) 
     - run C:\Program Files\Adobe\Adobe Flash Builder 4.5\utilities\Adobe Flash Builder 4.5 Plug-in Utility.exe 

    2. 영문 모드 설정 
     - plug-in을 설치하면 한글 모드로 eclipse가 실행된다. 어째 더 불편하네.. 
     - Eclipse.ini에서 아래를 추가 
      -vm 
      -Duser.language=en -Duser.country=US 

    3. Flash player debug 버전 설치 
     - http://www.adobe.com/support/flashplayer/downloads.html

    4. Chrome 설정 (IE는 상관없음) 
     - Chrome은 flash player를 번들로 제공하면서 자체적으로 자동으로 업그레이드 하기 때문에 pc에 설치된 adobe player를 사용하지 않는다. 
    - chrome://plugins/ : 크롬 브라우저에 입력 
    - 오른쪽 상단의 세부 정보 클릭 --> "flash" 검색 
    - 크롬 폴더의 player는 ‘사용안함’ system의 player는‘사용' 으로 설정 (화면에 표시되는 건 반대니 주의)


    2013년 7월 18일 목요일

    apache - tomcat, jetty 연동

    0. overview











    - 위와 같은 구성의 Apache (Web) + Tomcat/Jetty (WAS) 연동을 위한 설정이다.

    1. Download Apache HTTP server
     - http://httpd.apache.org/download.cgi#apache22에서 httpd-2.2.22-win32-x86-openssl-0.9.8t.msi 파일 다운로드 후 디폴트 설치

    2. Download Apache Tomcat connector
     - http://apache.tt.co.kr/tomcat/tomcat-connectors/jk/binaries/windows/ 에서 tomcat-connectors-1.2.37-windows-i386-httpd-2.2.x.zip 파일을 다운로드 mod_jk.so 파일을 아파치 설치 폴더의 modules 폴더에 복사한다

    3. Apache web server configuration 
     - httpd.conf에서 아래와 같이 설정한다.
    ...
    Include conf/mod_jk.conf
    NameVirtualHost *:80
    <VirtualHost *:80>
                      ServerName 1.1.1.1
                      DocumentRoot "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs/root"
                      JkMount /*.jsp was
                      JkMount /servlet was               
                      JkMount /birt/* was
                     
                      JkMount /mobile/* mobile
    </VirtualHost>

    ProxyRequests Off
    <Proxy *>
    Order deny,allow
    Allow from all
    </Proxy>
    ProxyPass /jetty http://ip:port/jetty
    ProxyPreserveHost On

    ProxyStatus On
    ...

    3.1. Tomcat 연동
     - Include conf/mod_jk.conf : mod_jk configuration 파일을 include 한다
     - DocumentRoot : 아파치 root 폴더를 지정한다. http://x.x.x.x/index.html 로 접근한다면 DocumentRoot로 지정된 폴더의 index.html이 호출된다.
     - JkMount /*.jsp was: jsp 파일을 servlet container로 전달하는 설정이다. “was”는 worker.properties 파일에 정의 되어 있다

    3.2. Jetty 연동
     - Jetty 연동을 위한 방법은 아래 3가지 방법이 있다. Jetty 에서 권장하는 1번 방법으로 설정한다
    1. Using apache mod_proxy and an normal Jetty HTTP connector.
    2. Using apache mod_proxy_ajp and the Jetty AJP connector.
    3. Using apache mod_jk and the Jetty AJP connector

     - 설정 파일의 ProxyPass /jetty http://ip:port/jetty에 해당하는 부분이 proxy를 이용한 연동 설정이다. (reverse proxy 방법) jetty 만을 위한 설정은 proxy 설정으로 끝난다

    4. mod_jk.conf
    LoadModule jk_module modules/mod_jk.so
    <IfModule mod_jk.c>
                      JkWorkersFile conf/workers.properties
                      JkLogFile logs/mod_jk.log
                      JkLogLevel info
                      JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"
                      JkRequestLogFormat "%w %V %T"

    </IfModule>

     - 디폴트로 아파치 설치시에는 해당 파일이 없으므로 위 내용으로 파일을 작성한 후 conf 폴더에 저장한다. LoadModule 를 통해 해당 모듈을 load한 후 기타 설정을 한다. 중요한 부분은 workers.properties를 설정한 부분이다

    5. workers.properties
    worker.list=was, mobile
    worker.conv_bp.port=123
    worker.conv_bp.host=10.10.10.10
    worker.conv_bp.type=ajp13

    worker.mobile.port=321
    worker.mobile.host=20.20.20.20
    worker.mobile.type=ajp13

     - tomcat ajp13 프로토콜을 이용한 연동 설정이다. was, mobile 두개의 tomcat과 연동하는 설정이다. Tomcat server.xml ajp13 포트를 확인한 후 작성한다.

    6. ref

    2013년 7월 17일 수요일

    mssql - drop database (single user mode)

    0. 사용중인 database를 drop 하기 위해선 single_user 모드로 바꿔줘야 한다.

    1. single_user mode
    USE master;
    GO
    ALTER DATABASE AdventureWorks2012
    SET SINGLE_USER
    WITH ROLLBACK IMMEDIATE;
    GO
    ALTER DATABASE AdventureWorks2012
    SET READ_ONLY;
    GO
    ALTER DATABASE AdventureWorks2012
    SET MULTI_USER;
    GO
    
    2. 나 같은 경우 여전히 session에 물려있어 drop database 혹은 multi_user로 바뀌지가 않는다. 이럴 때 아래를 참고해서 session id를 찾아서 kill 해준 후 drop 해준다.

    select d.name, d.dbid, spid, login_time, nt_domain, nt_username, loginame
      from sysprocesses p inner join sysdatabases d on p.dbid = d.dbid
     where d.name = 'database_name'
    go
    
    
    kill 51 go

    3. ref
     - http://remidian.com/2008/01/remove-sql-server-database-from-single-user-mode/

    2013년 7월 3일 수요일

    literal ?

    0. JavaScript: The Good Parts by 
     - javascript 관련 서적 중 가장 많이 추천되고, 실제로도 잘 쓰여진 책이다.
     - 책에 보면 literal이라는 용어가 많이 나오는데 이게 멀까? syntax랑 머가 다를까?

    1. literals in java
     - java의 primitive data type은 아래와 같다












     - literal이라는 것은 이러한 data type에 값을 대입할 때의 값 자체를 말한다. (네이버에는 상수로 번역이 되어 있는데 흔히 말하는 constant variable과는 구분 되어야 될 것 같다.) 

     - 다만 number 26을 decimal, hexadecimal, binary로 표기하면 각각 26, 0x1a, 0b11010 (java se7 and later)이 되는데, 표기법만 다르지 값 자체는 같다. 즉 값을 어떻게 표기하는가 하는 것이 literal이 되겠다. (앞의 예는 java tutorial의 integer literals의 예시다)

     - 표기법엔 여러가지가 있다. 0x1a처럼 prefix를 사용하거나, 0.0f 처럼 suffix를 사용하거나, null 처럼 예약어를 사용할 수도 있다.

     - JAVA SE 7 부터는 아래도 가능하다고 하니 관심 있으면 (Using Underscore Characters in Numeric Literals) 챕터를 참고 하면 되겠다.
    long creditCardNumber = 1234_5678_9012_3456L;

    2. literals in javascript












     - douglas crockford의 책에 보면 위의 그림이 나온다.

     - Javascript에서는 아래와 같이 변수에 object나 function도 대입이 가능하다. 그리고 script 언어이기 때문에 따로 compile 되지 않는다. 그래서 literal이라는 용어를 사용한 것 같다. 






    3. summary
     - syntax, grammar 이렇게 쓰면 이해가 쉽게 되는데, literal이라고 하니 이해가 힘들어서 정리를 좀 했는데, 사실 literal이라는 것도 값 자체를 나타내는 표기법이니 구문, 문법의 일종이라고 생각하면 속 편하겠다.


    * ref

    2013년 6월 24일 월요일

    javadoc - ant script

    0. install JAutodoc eclipse plug-in
     - it helps you to auto generate javadoc comments

    1. create javadoc in eclipse

    2. run ant script
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <project default="javadoc">
        <target name="javadoc">
            <javadoc package="java" access="package"
            additionalparam=" -encoding UTF-8 -charset UTF-8 -docencoding UTF-8"
            author="true"
            classpath="libraries.jar"
            destdir="doc"
            doctitle="title"
            nodeprecated="false"
            nodeprecatedlist="false"
            noindex="false"
            nonavbar="false"
            notree="false"
            packagenames="packagenames"
            source="1.6"
            sourcepath="src/main/java;"
            splitindex="true"
            use="true"
            version="true"/>
        </target>
    </project>

    3. then you can see your documents in the doc folder

    subversion - install subversion server in centos

    0. yum install subversion

    1. mkdir /home/svn

    2. svnadmin create trunk
     - create repository (trunk... whatever) then,
     - move to the trunk

    3. svnserve.conf
     - anon-access = none
     - auth-access = write
     - password-db = passwd
     - realm =  repo-xxx

    4.  repo/conf/passwd
     - create user

    5. svnserve -d -r /home/svn
     - run daemon
     - checkout url: svn://ipaddress/trunk/

    2013년 6월 19일 수요일

    jsessionid - tomcat, jetty 세션 공유

    0. 하나의 서버에 tomcat, jetty 두개의 WAS를 서비스 하는 경우 세션을 공유하는 문제가 발생한다. 이건 JSESSIONID 때문에 발생하는 문제다.
     - 세션을 공유? 동일한 브라우저에서 tomcat 세션 생성 --> jetty 세션 생성 --> tomcat에 다시 접근하면 이전에 생성된 세션이 날라간다.

    1. JSESSIONID?
     - JSESSIONID is a cookie generated by Servlet container like Tomcat or Jetty and used for session management in J2EE web application for http protocol.
     - 즉 tomcat 이건 jetty 건 J2EE web application 이라 디폴트로 JSESSIONID 라는 이름으로 쿠키를 관리한다. 
     - 따라서, 한 쪽에서 이름을 바꿔서 사용하면 세션을 공유하는 문제를 해결할 수 있다.

    2. jetty 설정 방법
     - web.xml
      <context-param>
        <param-name>org.mortbay.jetty.servlet.SessionCookie</param-name>
        <param-value>JSESSIONID2</param-value>
      </context-param>

    3. 참고
     - Examples of the names that some programming languages use when naming their cookie include JSESSIONID (JSP), PHPSESSID (PHP), and ASPSESSIONID (Microsoft ASP).