2014년 6월 30일 월요일

Spring - factory method, factory bean 사용

1. 스태틱으로 선언하여 클래스 메서드로 만듦
<bean id="객체ID" class="팩토리클래스" factory-method="생성메서드명">


2. 인스턴스 메서드로 만듦
<beam id="팩토리ID" class="팩토리클래스">
(--> static 메서드가 아니라 객체 먼저 생성 필요)

<bean id="객체ID" factory-bean="팩토리ID" factory-method="생성메서드명">


3. AbstractFactoryBean 상속 받아서 클래스 생성
- 단점 : Spring에서만 사용가능
- 장점 : 팩토리 메서드 지정 불필요. 직접 만들어보면 내부 동작 이해에 도움이 됨.

public class TestFactoryBean extends AbstractFactoryBean<Test> {

    @Override
    public Class<?> getObjectType() {
        ...
    }

    @Override
    protected Tire createInstance() throws Exception {
        ...
    }
...
}

<bean id="객체ID" class="팩토리빈클래스">



Java와 JavaScript의 삼항연산자 다른점 (Ternary Operator in Java, JavaScript)

*JavaScript
var a = 3;
var b = 2;
var max;

max = a > b ?  a : b; - 가능
a > b ? max = a : max = b; - 가능



*Java
int a = 1;
int b = 2;
int max;

max = a > b ?  a : b;         - 가능
a > b ? max = a : max = b;    - 문법 오류 (x)



Spring - Map, Properties 값 설정

*Map과 Properties의 차이
- Map : key나 value로 문자열 및 다른 타입의 객체도 사용 가능
- Properties : Map의 일종이지만, key나 value로 문자열을 다룰 때 주로 사용


*java.util.Properties 타입 :
<props>
<prop key="키1">값1</prop>
<prop key="키2">값2</prop>
...
</props>


*java.util.Map 타입 :
<map>
<entry>
<key>
<value>키1</value>
</key>
<value>값1</value>
</entry>
<entry key="키2">
<ref bean="값2의id"/>
</entry>
<entry key="키3" value="값3" />
<entry key="키4" value-ref="값4의id" />
</map>



Difference between Set, List and Map in Java

Set provides uniqueness guarantee i.e.g you can not store duplicate elements on it, but it's not ordered.
List is an ordered Collection and also allowes duplicates.
Map is based on hashing and stores key and value in an Object called entry. It provides O(1) performance to get object, if you know keys, if there is no collision.

Another key difference between Set, List and Map are that Map doesn't implement Collection interface, while other two does.

Popular impelmentation of Set is HashSet, of List is ArrayList and LinkedList, and of Map are HashMap, Hashtable and ConcurrentHashMap.


-------------------------------------------------------------------
- Set : 중복이 불가해서 고유성은 보장되지만, 순서 유지 불가능
- List : 순서가 유지되고, 중복 가능
- Map : key와 value로 entry라 불리는 Object를 저장하고 찾는다. 키를 알고 있고, 충돌이 없다면, object를 얻는데 performance가 가장 좋다


- Set, List는 Collection 인터페이스를 구현했지만, Map은 아니다.

- 구현체 중 많이 쓰이는것
> Set : HashSet
> List : ArrayList, LinkedList
> Map : HashMap, Hashtable, ConcurrentHashMap.



출처 :
http://javarevisited.blogspot.kr/2011/11/collection-interview-questions-answers.html

Checking Types in JavaScript

* typeof operator

TypeResult
Undefined"undefined"
Null"object"
Boolean"boolean"
Number"number"
String"string"
Host object (provided by the JS environment)Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms)"function"
Any other object"object"
typeof 3 // "number"
typeof "abc" // "string"
typeof {} // "object"
typeof true // "boolean"
typeof undefined // "undefined"
typeof function(){} // "function"
typeof [] // "object"
typeof null // "object"

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

* instanceof operator

function Animal(){}
var a = new Animal()
a instanceof Animal // true
a.constructor === Animal // true

function Cat(){}
Cat.prototype = new Animal
Cat.prototype.constructor = Cat
var felix = new Cat
felix instanceof Cat // true
felix instanceof Animal // true
felix.constructor === Cat // true
felix.constructor === Animal // false

felix = null
felix instanceof Animal // true
felix.constructor === Animal // throws TypeError

-------------------------------------------------
[1, 2, 3] instanceof Array // true
/abc/ instanceof RegExp // true
({}) instanceof Object // true
(function(){}) instanceof Function // true

null instanceof Boolean // false
undefined instanceof Array // false

3 instanceof Number // false
true instanceof Boolean // false
'abc' instanceof String // false
(3).constructor === Number // true
true.constructor === Boolean // true
'abc'.constructor === String // true



출처 :
http://tobyho.com/2011/01/28/checking-types-in-javascript/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

2014년 6월 27일 금요일

Node.js - Error connection lost the server closed the connection

Error: Connection lost: The server closed the connection.


var db_config = {
  host: 'localhost',
    user: 'root',
    password: '',
    database: 'example'
};

var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connection.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      handleDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

handleDisconnect();



출처 :
http://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed-the-connection

2014년 6월 26일 목요일

[Spring] Spring web 프로젝트 준비 (Eclipse, Gradle)

*Eclipse Marketplace 플러그인 준비
- groovy -> Groovy/Grails Tool Suite (GGTS) for ... 설치
- gradle -> Gradle Integration for Eclipse ... 설치


*프로젝트 생성 과정
1. New Gradle Project 생성
(Sample project : Java Quickstart)

2. Gradle 설정 파일 (build.gradle) 수정
apply plugin: 'java'
apply plugin: 'eclipse-wtp' // WTP(Web Tools Platform) -> 웹 프로젝트로 인식하도록
apply plugin: 'war'

compileJava.options.encoding = 'UTF-8' // 지정하지 않으면 OS 기본 인코딩으로 간주
sourceCompatibility = 1.7 // 빌드시 해당 버전으로 자바 문법 검사
version = '1.0'

eclipse {
wtp {
facet {
facet name: 'jst.web', version: '3.0' // Servlet Spec Version 지정, 미 지정시 2.4
facet name: 'jst.java', version: '1.7' // Java Version 지정
}
}
}

3. 스프링 라이브러리
www.spring.io > Projects > Spring Framework > Quick Start >
 compile 'org.springframework:spring-context:4.0.5.RELEASE'
를 Gradle 설정파일 dependencies에 복사

4. src 폴더 정리 (4개 폴더 남기고 하위 예제 제거)
src/main/java
src/main/resources
src/test/java
src/test/resources

5. Project> Properties> Java Complier
- Enable project specific settings 체크 해제
  (해당 프로젝트 컴파일러를 별도로 설정하는 옵션)

6. Project> Run As> Gradle Build...
:clean
:cleanEclipse
:eclipse

Run 실행


7. Gradle 프로젝트로 재 설정 (.project 파일)
<nature>org.springsource.ide.eclipse.gradle.core.nature</nature>
- 를 <natures> 태그의 첫번째 항목으로 추가



java.math.BigDecimal 활용 Discount, Tax

public class Calc2 {
  public static void main(String args[]) {
    BigDecimal amount = new BigDecimal("100.05");
    BigDecimal discountPercent = new BigDecimal("0.10");
    BigDecimal discount = amount.multiply(discountPercent);
    discount = discount.setScale(2, RoundingMode.HALF_UP);
    BigDecimal total = amount.subtract(discount);
    total = total.setScale(2, RoundingMode.HALF_UP);
    BigDecimal taxPercent = new BigDecimal("0.05");
    BigDecimal tax = total.multiply(taxPercent);
    tax = tax.setScale(2, RoundingMode.HALF_UP);
    BigDecimal taxedTotal = total.add(tax);
    taxedTotal = taxedTotal.setScale(2, RoundingMode.HALF_UP);
    System.out.println("Subtotal : " + amount);
    System.out.println("Discount : " + discount);
    System.out.println("Total : " + total);
    System.out.println("Tax : " + tax);
    System.out.println("Tax+Total: " + taxedTotal);
  }
}



http://www.yunsobi.com/blog/227

2014년 6월 25일 수요일

JavaScript Object Length 구하기

getObjLength = function(obj) {
    var size = 0, key = null;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;

};



출처 :

Touch Event Support for jQuery UI (draggable 등 mobile device에서 사용하기)

jQuery UI listens to mouse events not touch events
- jQuery UI는 마우스 이벤트로 설정되어 터치 이벤트로는 동작하지 않는다.



다운로드 :
http://touchpunch.furf.com/

MyBatis 개요

*라이브러리 파일 준비
- https://github.com/mybatis > mybatis-3 > download
라이브러리 다운로드 후 WEB-INF/lib로  복사


*핵심 컴포넌트
1. SqlSessionFactoryBuilder
- mybatis 설정 파일의 내용으로 SqlSessionFactory 생성
2. SqlSessionFactory
- SqlSession 객체를 생성
3. SqlSession
- 실제 SQL 실행하는 객체, JDBC 드라이버 사용
4. SQL 맵퍼 파일
- SQL 문을 담고 있는 파일. SqlSession 객체가 참조함


*SqlSession 주요 메서드
1. selectList()
- SELECT 실행. 객체(Object) 목록을 반환

2. selectOne()
- SELECT 실행. 객체 하나를 반환

3. insert()
- INSERT 실행. 추가된 갯수(int) 반환

4. update()
- UPDATE 실행. 변경된 갯수 반환

5. delete()
- DELETE 실행. 삭제된 갯수 반환


*사용
- DAO : List<E> selectList(String sqlId, 매개변수)
  (sqlId ==> 맵퍼이름 + sql아이디)

- mapper :
<mapper namespace="맵퍼이름">
<select id="sql아이디" parameterType="객체명">
SQL문
VALUES (#{프로퍼티명},  #{프로퍼티명}, ...)
- #{프로퍼티}명 - 은 객체의 getter/setter를 사용
- 매개변수가 int 등 기본 데이터 형인 경우 프로퍼티 명은 아무 이름이나 써도 상관없다.

2014년 6월 18일 수요일

Web SQL error handling (에러 처리)

function db_errorCB(transaction, e) {
console.log(e);
console.log("e.message :" + e.message);
}



참고 :
http://stackoverflow.com/questions/16559832/how-to-get-the-context-of-a-web-sql-error

10 이하일때 0 추가해서 출력하기 (시:분:초 출력 등)

function gb_timeText(i) {
if (i < 10) i = '0' + i;
return i;
}



Tomcat Server에 JDBC DataSource 설정

1. context.xml 파일에 <Resource> 태그 추가
(=> Tomcat 서버가 해당 자원을 관리 하도록 설정)

<Resource name="jdbc/스키마명" auth="Container" type="javax.sql.DataSource"
maxActive="10" maxIdle="3" maxWait="10000"
username="사용자명" password="암호"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://도메인/스키마명"
closeMethod="close"/>

name="JNDI 이름"
maxActive="꺼낼 수 있는 커넥션 최대 갯수 (기본값 8)"
maxIdle="유휴 커넥션 최대 갯수 (기본값 8)"
maxWait="최대 커넥션 발급 상태에서 추가 요청이 들어왔을때 기다리는 초. 이후 예외 Throw(기본값 -1 == 반납 될 때 까지 기다림)"


2. web.xml (Deloyment Descriptor == DD 파일)에 선언
(=> 설정 된 서버 자원을 해당 웹 앱에서 참조하도록)

<resource-ref>
<res-ref-name>jdbc/스키마명</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>



JSTL (JSP Standard Tag Library) 사용

- jstl.java.net에서 JSTL API와 Implementation 구현체 다운로드 필요

- 선언
<%@ taglib uri="라이브러리 URI" prefix="접두사" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

1. <c:out>
 - 출력문 만드는 태그
<c:out value="출력할 값" default="기본값" /> 또는
<c:out value="출력할 값">기본값"</c:out>
- value가 null이면 기본값 출력, 기본값도 없다면 빈 문자열 출력

2. <c:set>
 - 변수를 생성하거나 기존 값을 덮어 씀
<c:set var="변수명" value="값" scope="page|request|session|application"/> 또는
<c:set var="변수명" scope="page|request|session|application">값</c:set>
- scope 생략시 page(JspContext)에 저장 됨
- 클래스에 정의된 셋터 메서드의 리턴타입이 void 여야 함

3. <c:if>
<c:if test="조건" var="변수명" scope="스코프">
컨텐츠
</c:if>

4. <c:choose>
<c:choose>
<c:when test="조건(참 거짓 값)"></c:when>
<c:when test="조건(참 거짓 값)"></c:when>

...
<c:otherwise></c:otherwise>
</c:choose>

5. <c:forEach>
1) 리스트 반복
<c:forEach var="변수명" items="목록데이터" begin="시작인덱스" end="종료인덱스">
${변수명}
</c:forEach>

2) 특정 횟수 반복
<c:forEach var="변수명" begin="숫자" end="숫자">
${변수명}
</c:forEach>

6. <c:forTokens>
- 특정 구분자(delimiter)로 분리 및 반복
- & 구분자 로 파라미터 분리 등에 활용
<c:forTokens var="변수명" items="문자열" delims="구분자">
${변수명}
</c:forTokens>

7. <c:url>
<c:url var="변수명" value="주소">
<c:param name="파라미터명" value="값">
<c:param name="파라미터명" value="값">
...
</c:url>

8. <c:import>
1) 출력
<c:import url="주소"/>
2) 저장
<c:import var="변수명" url="주소"/>

9. <c:redirect>
<c:redirect url="주소"/>

10. <fmt:parseDate>
- 문자열을 패턴으로 분석하여 java.util.Date 객체를 생성
<fmt:parseDate var="변수명" value="2014-05-05" pattern="yyyy-MM-dd"/>

11. <fmt:formatDate>
<fmt:formatDate var="${가져올변수명}" pattern="yy/MM/dd" />

EL (Expression Language) 사용

${} - 즉시 적용 (immediate evalution)
- 객체의 프로퍼티 값을 꺼내거나 메서드를 호출

#{} - 지연 적용{deferred evaluation)
- 사용자가 입력한 값을 객체의 프로퍼티에 담는 용도로 주로 사용
- JSF(javaServer Faces)에서 UI를 만들때 사용

- 사용 예 :
${ 스코프.객체명.프로퍼티 }
${ 객체명.프로퍼티 }

- 스코프가 없을 때 보관소 찾는 순서
1) pageScope => JspContext
2) requestScope => ServletRequest
3) sessionScope => HttpSession
4) applicationScope => ServletContext
5) 모두 없다면 null 리턴

- 기본 객체
${pageScope.객체명}
${requestScope.객체명}
${sessionScope.객체명}
${applicationScope.객체명}

${param.매개변수명} - 값 조회
${paramValues.매개변수명} - 값 배열 조회
${header.헤더명} - HTTP 헤더 값 조회
${headerValues.헤더명} - HTTP 헤더 값 배열 조회
${cookie.쿠키명}
${initParam.매개변수명}

${pageContext} - 내장 객체 중 유일하게 map이 아님
${pageContext.servletContext.객체명}
${pageContext.session.객체명}
${pageContext.request.객체명}



2014년 6월 17일 화요일

서블릿 초기화 매개변수 사용

1. web.xml에 설정
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>

2. 사용
ServletContext sc = this.getServletContext();
sc.getInitParameter("driver");

Servlet Filter

- 서블릿 실행 전/후 공통으로 필요한 작업을 수행
> 사전작업 (문자 집합 설정, 사용 권한 확인 등)
> 사후작업 (응답 데이터 암호화 등)
- 모든 요청에 적용하거나, 특정 url 요청에만 적용도 가능함


사용 :
1. 필터 클래스 생성 (implements Filter) 및 구현
2. @WebFilter 또는 web.xml 파일에 패치 설정



JSP 액션 태그 사용

<jsp:useBean>
- 자바 인스턴스를 준비함
- 보관소에서 인스턴스를 꺼내거나, 없으면 새로 만들어 저장
- 사용 예 : <jsp:useBean id="test" scope="session" class="package.test"/>

<jsp:setProperty> / <jsp:getProperty>
- setter / getter 메서드 호출

<jsp:include> / <jsp:forward>
- 사용 예 : <jsp:include page="/header.jsp"/>

<jsp:param>
- <jsp:include>, <jsp:forward>, <jsp:params> 의 자식 태그로 사용
- ServletRequest 객체에 매개변수를 추가하는 코드를 생성



Servlet 구동 기본

1. GenericServlet 상속 받아서 Servlet 클래스 생성 (+ 구현)
2. @WebServlet 애노테이션이나 web.xml 파일로 배치 설정
3. 서버 구동

4. 클라이언트 요청
- 해당 서블릿이 없다면 클래스로딩 > init() > service()
- 해당 서블릿이 있다면 service() 만 호출
=> 웹 앱 종료 전까지 서블릿 객체는 한 번만 생성, 이후 유지 됨




JavaScript 초 -> 시간 분 초 형태로

if (sec < 60) {
sec = sec + '초';
} else if (sec < 3600){
sec = Math.floor(sec%3600/60) + '분 ' + sec%60 + '초';
} else {
sec = Math.floor(sec/3600) + '시간 ' + Math.floor(sec%3600/60) + '분 ' + sec%60 + '초';
}

Javascript String replaceAll

str.replace(/foo/g, "bar")

or

String.prototype.replaceAll = function(str1, str2, ignore) {
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}



2014년 6월 16일 월요일

Web SQL search on dates

select * from dates
where dte = date('now')
;

select dtm from datetimes
where dtm >= datetime(date('now'))
and dtm < datetime(date('now', '+1 day'))
;

select datetime(dtm, 'unixepoch', 'localtime') from unix
where dtm >= strftime('%s', date('now'))
and dtm < strftime('%s', date('now', '+1 day'))
;



https://gist.github.com/dwurf/8929425

SQLite Syntax Documentation

http://sqlite.org/lang.html

Web SQL error handling

db.transaction(function(tx) {
tx.executeSql(query, values, successHandler, errorHandler);
});

function errorHandler(tx, e) {
console.log(e);
console.log("e.message :" + e.message);

JavaScript String Object Methods

concat()
- Joins two or more strings, and returns a copy of the joined strings

indexOf()
- Returns the position of the first found occurrence of a specified value in a string

replace()
- Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced

split()
- Splits a string into an array of substrings

substring()
- Extracts the characters from a string, between two specified indices

trim()
- Removes whitespace from both ends of a string



http://www.w3schools.com/jsref/jsref_obj_string.asp
http://icoon22.tistory.com/219

Web SQL get last row

SELECT * FROM table ORDER BY column DESC LIMIT 1;



http://stackoverflow.com/questions/9902394/how-to-get-last-record-from-sqlite

2014년 6월 13일 금요일

JavaScript key, value Array Sort

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});

var status = new Array();
status.push({name: 'BOB', val: 10});
status.push({name: 'TOM', val: 3});
status.push({name: 'ROB', val: 22});
status.push({name: 'JON', val: 7});
status.sort(function(a,b) {
    return a.val - b.val;
});



http://www.w3schools.com/jsref/jsref_sort.asp
http://stackoverflow.com/questions/12788051/how-to-sort-an-associative-array-by-value

JavaScript key value Array

There are two ways to add new properties to an object:

var obj = {
    key1: value1,
    key2: value2
};
Using dot notation:

obj.key3 = "value3";
Using square bracket notation:

obj["key3"] = "value3";



http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object-literal

jQuery click 이벤트 호출

.trigger( eventType [, extraParameters ] );



http://api.jquery.com/trigger/

window.load vs document.ready

 $(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready
 alert("document is ready");
});


$(window).load(function() {
 // executes when complete page is fully loaded, including all frames, objects and images
 alert("window is loaded");
});



http://stackoverflow.com/questions/8396407/jquery-what-are-differences-between-document-ready-and-window-load

2014년 6월 12일 목요일

Web SQL INSERT OR ...

"INSERT OR IGNORE" (="INSERT ON CONFLICT IGNORE")
> 초기값 셋팅에 활용

"INSERT OR UPDATE"
> 중복시 값 변경에 활용



http://www.sqlite.org/lang_conflict.html

Web SQL 여러줄 삽입

insert multiple rows at a time in an SQLite database

MySQL example:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
  ('data1', 'data2'),
  ('data3', 'data4'),
  ('data5', 'data6'),
  ('data7', 'data8');

This can be recast into SQLite as:
INSERT INTO 'tablename'
      SELECT 'data1' AS 'column1', 'data2' AS 'column2'
UNION SELECT 'data3', 'data4'
UNION SELECT 'data5', 'data6'
UNION SELECT 'data7', 'data8'



http://stackoverflow.com/questions/1609637/is-it-possible-to-insert-multiple-rows-at-a-time-in-an-sqlite-database