Sunday, March 31, 2013

event.preventDefault(); in javascript


this Method means prevent event from tag's basic event.
I can show you sample below
A href's basic function removed
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>
<script>
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
</script>
</body>
</html>

Wednesday, March 27, 2013

make sequences in mysql



create table mysql_sequences(
seq_name varchar(10) not null,
seq_currval Bigint unsigned not null,
primary key (seq_name)
)engine=MyISAM;





DELIMITER ;;

CREATE FUNCTION nextval()
returns bigint unsigned
modifies sql data
sql security invoker
begin
insert into mysql_sequences
set seq_name='default', seq_currval=(@v_current_value:=1)
on duplicate key
update seq_currval=(@v_current_value:=seq_currval+1);

return @v_current_value;
end ;;

Tuesday, March 26, 2013

Create Scheduler in Mysql


Repeactable Scheduler

CREATE EVENT daily_ranking
on SCHEDULE EVERY 1 DAY STARTS '2011-05-16 01:00:00' ENDS '2013-04-01 12:59:59'
DO
INSERT INTO SCHEDULER_TEST VALUES (NOW(), 'DONE');


every day on 01:00:00 doing insert in period

Only one time Scheduler 


CREATE EVENT daily_ranking
on SCHEDULE at CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
INSERT INTO SCHEDULER_TEST VALUES (NOW(), 'DONE');




blow line is test and Query



CREATE EVENT daily_ranking
on SCHEDULE EVERY 1 DAY STARTS '2011-05-16 01:00:00' ENDS '2013-04-01 12:59:59'
DO
INSERT INTO SCHEDULER_TEST VALUES (NOW(), 'DONE');


CREATE EVENT daily_ranking_AT4
on SCHEDULE at CURRENT_TIMESTAMP + INTERVAL 1 MINUTE
DO
INSERT INTO SCHEDULER_TEST VALUES (NOW(), 'Test2');


SELECT * FROM INFORMATION_SCHEMA.EVENTS;

SELECT * FROM SCHEDULER_TEST;

SELECT NOW();

SELECT db, name, interval_value, interval_field, status, on_completion, time_zone, execute_at, starts, ends, last_executed, created, modified
from mysql.event;

SELECT event_schema, event_name, interval_value, interval_field, status, on_completion, time_zone, execute_at, starts, ends, last_executed, created, last_altered
from information_schema.events;


show global variables like '%sche%';

set global event_scheduler = 1 ;

process kill in mysql

kill only query from thread
mysql>kill query 1000;

kill query with thread
mysql> kill 1000;

Phonegap file uploader in android


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>File Transfer Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
    <script type="text/javascript" charset="utf-8">

        // Wait for PhoneGap to load
        //
        // document.addEventListener("deviceready", onDeviceReady, false);
  function imageObject(){
        var options,
        fileEntry,
        ft,
        imageURI        
        };
       
        imageObject.prototype = {
        // 기본 셋팅
        initUpload : function(imageURI){
        console.log("initUpload");
        image.options = new FileUploadOptions();
        window.resolveLocalFileSystemURI(imageURI, image.onSuccessFile, image.onFailFile);
        image.imageURI = imageURI;
       
        image.options.fileKey="file";
            image.options.fileName=image.fileEntry.name;          
            image.options.mimeType="image/jpeg";
        image.ft = new FileTransfer();
        },
        // 파일전송
        send : function(){
        image.ft.upload(image.imageURI, "http://203.233.82.229/non/test/file.json", win, fail, image.options);
        },
        onSuccessFile : function(f){
        console.log("getFile");
        image.fileEntry = f;
        alert(f.name);
        },
        onFailFile : function(f){
       
        }
        }
        var image = new imageObject();
       

        // PhoneGap is ready
        //
        function readImageFile() {

            // Retrieve image file location from specified source
            navigator.camera.getPicture(image.initUpload,
                                        function(message) { alert('get picture failed'); },
                                        { quality: 50,
                                        destinationType: navigator.camera.DestinationType.FILE_URI,
                                        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
                                        mediaType: Camera.MediaType.ALLMEDIA }
                                        );

        };
       
        function win(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
            alert("status : " + JSON.parse(r.response).status);
        }

        function fail(error) {
            alert("An error has occurred: Code = " = error.code);
        }    
     

        </script>
</head>
<body>
    <h1>Example</h1>
    <p>With PhoneGap API</p>
    <button onclick="readImageFile()">Open Image</button>
    <button onclick="image.send()">Send To Server</button>
    <br>
    <br>
    <p>With Original Form</p>
    <form method='POST' enctype='multipart/form-data' action='http://203.233.82.229/non/test/file.json'>
File to upload: <input type="file" name="file"><br>
Notes about the file: <input type="text" name="note"><br>
<br>
<input type="submit" value="Press"> to upload the file!
</form>
   
</body>
</html>

Thursday, March 21, 2013

FullText in mysql

Engine = myisam

index = fulltext key fx_article (acolumn, bcolumn)

ex)
select doc_id doc_title, doc_body
from ft_article where match(doc_title, doc_body) against('list' in boolean mode);


ft_min_word_len : minimum length of searching word
ft_stopword_file : engine consider it not word, Skip
ft_max_word_len : maximum length of searching word



in Natural Language Mode
ex) searching by word

select doc_id, doc_title, doc_body
from ft_article
where match(doc_title, doc_body) against('hash key' in natural language mode);


in Boolean Mode

+ : AND
-: Not
nothing : OR

Query Profile in mysql

show variables like 'profiling';

set profiling = 1;

show variables like 'profiling';

select * from employees where emp_no =10001;


show profiles;

show profile cpu for query [query number];


Wednesday, March 20, 2013

How to remove 8443 port in URL in tomcat

tomcat's Default https port is 8443

if we connect to 8443 Port

example https://www.xxxx.com:8443/web.........

as you can see 8443 exist in URL

The soulution to hide is
use Default https port : 443




server.xml


<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="443" />




<Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true" keystoreFile="xxxxx" keystorePass="xxxx" keystoreType="xxxx"
               clientAuth="false" sslProtocol="TLS" />
 

Tuesday, March 19, 2013

use row_number in Mysql

select emp_no , @i:=@i +1 as result  from employees, (select @i:=0) temp order by emp_no;

ibatis get pk key after insert in mysql

<insert id="user.insertUserAndGetId" parameterClass="user">
    <![CDATA[
        INSERT INTO t
        (
            name
        )
        VALUES
        (
            #name#
        )
    ]]>
    <selectKey keyProperty="id" resultClass="Integer">
        SELECT LAST_INSERT_ID()
    </selectKey>
</insert>



UserVO user = new UserVO();
user.setName("Bob");

System.out.println("Index of user " + user.getName() + " is " + user.getId() + " (before insert)");
int id = ((Integer) sqlMap.insert("user.insertUserAndGetId")).intValue();
System.out.println("Index of user " + user.getName() + " is " + user.getId() + " (after insert)");

Monday, March 18, 2013

Anti join in mysql

create table tab_tset1 (id INT, PRIMARY KEY(id));
create table tab_test2(id INT);
insert into tab_test1 values (1), (2), (3), (4);
insert into tab_test2 values (1), (2);

select t1.id from tab_test1 t1
where t1.id not in (select t2.id from tab_test2 t2);

select t1.id from tab_Test1 t1
where not exists
(select 1 from tab_tetst2 t2 where t2.id=t1.id);

select t1.id
from tab_test1 t1
left outer join tab_test2 t2 on t1.id=t2.id
where t2.id is null;


choose one thing that you want

if there are a lot of datas i prefer to use third way

Sunday, March 17, 2013

DATE_FORMAT, STR_TO_DATE


-- datetime, date to str

SELECT DATE_FORMAT(REG_DATE, '%Y-%m-%d %H:%i:%s') FROM TB_FILE;

SELECT DATE_FORMAT(REG_DATE, '%Y-%m-%d %H:%i:%s') FROM TB_FILE;

-- str to datetime

select STR_TO_DATE('2011-04-30 15:13:25', '%Y-%m-%d %H:%i:%s');

--

SELECT NOW();

SELECT DATE_ADD(NOW(), INTERVAL -1 DAY);

Saturday, March 16, 2013

linux ip setting


 vi /etc/sysconfig/network-script/ifcfg-eth0

 DEVICE=eth0
 BOOTPROTO=none
 HWADDR=08:00:27:02:c5:aa
 ONBOOT=yes
 NETMASK=255.255.255.0
 IPADDR=192.168.0.200
 GATEWAY=192.168.0.1
 TYPE=Ethernet

and 

service network restart

Thursday, March 14, 2013

tomcat 7 auth

http://www.avajava.com/tutorials/lessons/how-do-i-use-basic-authentication-with-tomcat.html?page=1

Wednesday, March 13, 2013

string to datetime in mysql

http://www.geeksengine.com/database/single-row-functions/conversion-functions.php

Spring Properties get in class

test.properties
application.file.home = fileHomeString
spring.xml


      
        classpath:/properties/test.properties
      


Bean class
public PropertyTest class{

  @Value("${" + "application.file.home" + "}")
  private String propertiValue;

}

Spring Mvc jsp Exception Page

Web.xml
  
  java.lang.Exception
  /WEB-INF/pages/error.jsp
  
error.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR" isErrorPage="true"
    pageEncoding="EUC-KR"%>
<%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>





Insert title here


${hello} This is an error page <%= exception %>


HandlerExceptionResolver class
public class SnsHandlerExceptionResolver implements HandlerExceptionResolver

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception error) {

     if (request.getRequestURI().contains(".htm")) {
request.setAttribute("javax.servlet.error.exception", error);
request.setAttribute("hello", "hello");
final ModelAndView view = new ModelAndView();
return view;
}

}
If servlet Exception Occured this error.jsp page will called

Tuesday, March 12, 2013

Index list depending on Engine in mysql

MyISAM : B-Tree, R-tree, fulltext-index
InnoDB :  B-Tree
Memory : B-Tree, Hash
TokuDB : Fractal-Tree

'cascade on delete' in mysql


what mean cascade on delete ??

this means if parent record deleted, the child records referencing parent pk also deleted


create table tb_parent (
 id int not null,
fd varchar(100) not null,
primary key (id)
)ENGINE = INNODB;

create table tb_child(
id int not null,
pid int default null,
fd varchar(100) default null,
primary key (id),
key ix_parentid(pid),
constraint child_ibfk_1 foreign key (pid) references tb_parent (id) on delete cascade
) ENGINE = INNODB;

insert into tb_parent values (1, 'parent-1'), (2, 'parent-2');

insert into tb_child values(100, 1, 'childe-100');


match against in mysql


CREATE TABLE `articles` (
  `id` int(11) NOT NULL DEFAULT '0',
  `title` varchar(65) DEFAULT NULL,
  `topic` varchar(25) NOT NULL DEFAULT '',
  `author` varchar(25) NOT NULL DEFAULT '',
  `ondate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `body` text NOT NULL,
  KEY `index_id` (`id`),
  FULLTEXT KEY `title` (`title`,`body`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8$$



select id,title FROM articles WHERE
    MATCH(title) AGAINST ('+cvs' IN BOOLEAN MODE) limit 1000;

what you have to consier is depending on DB Engine

Monday, March 11, 2013

MYSQL EXPLAIN QUERY


Explain 정보보는법

인덱스가 적절히 사용되고 있는지 검토
나열된 순서는 MYSQL 이 쿼리처리에 사용하는 순서대로 출력
EXPLAIN 의 각 행 설명
1. id : SELECT 번호, 쿼리내의 SELECT 의 구분번호
2. select_type : SELECT 의 타입
  • SIMPLE: 단순 SELECT (UNION 이나 서브쿼리를 사용하지 않음)
  • PRIMARY: 가장 외곽의 SELECT
  • UNION: UNION 에서의 두번째 혹은 나중에 따라오는 SELECT
  • DEPENDENT UNION: UNION 에서의 두번째 혹은 나중에 따라오는 SELECT, 외곽쿼리에 의존적
  • UNION RESULT: UNION 의 결과물
  • SUBQUERY: 서브쿼리의 첫번째 SELECT
  • DEPENDENT SUBQUERY: 서브쿼리의 첫번째 SELECT, 외곽쿼리에 의존적
  • DERIVED: SELECT 로 추출된 테이블 (FROM 절 내부의 서브쿼리)
3. table : table명
4. type : 조인타입, 우수한 순서대로… 뒤로갈수록 나쁜 조인형태
  • system
    테이블에 단 하나의 행만 존재(시스템 테이블). const join 의 특수한 경우
  • const
    많아야 하나의 매치되는 행만 존재할 때
    PRIMARY KEY 나 UNIQUE index 를 상수와 비교할 때
    각 컬럼값은 나머지 연산에서 상수로 간주, 처음 한번만 읽어들이면 되므로 매우 빠름
  • eq_ref
    조인수행을 위해 각 테이블에서 하나씩의 행만이 읽히는 경우
    조인연산에 PRIMARY KEY 나 UNIQUE index 인덱스가 사용되는 경우
    인덱스된 컬럼이 = 연산에 사용되는 경우
  • ref
    이전 테이블과의 조인에 사용될 매치되는 인덱스의 모든행이 이 테이블에서 읽혀질 때
    leftmost prefix 키만을 사용하거나 사용된 키가 PRIMARY KEY 나 UNIQUE 가 아닐때
    (즉 키값으로 단일행을 추출할수 없을때)
    사용된 키가 적은수의 행과 매치되면 이것은 적절한 조인 타입
    ref 는 인덱스된 컬럼과 = 연산에서 사용됨
  • ref_or_null
    ref 와 같지만 NULL 값을 포함하는 행에대한 검색이 수반될 때
    서브쿼리 처리에서 대개 사용됨
  • index_merge
    인덱스 병합 최적화가 적용되는 조인 타입
    이 경우, key 컬럼은 사용된 인덱스의 리스트를 나타내며
    key_len 컬럼은 사용된 인덱스중 가장 긴 key 명을 나타냄
  • unique_subquery
    몇몇 IN 서브쿼리 처리에서 ref 타입대신 사용됨
    unique_subquery 는 성능향상을 위해 서브쿼리를 단순 index 검색 함수로 대체함
  • index_subquery
    unique_subquery 와 마찬가지로 IN 서브쿼리를 대체
    단, 서브쿼리에서 non-unique 인덱스가 사용될때 동작 함
  • range
    인덱스를 사용하여 주어진 범위 내의 행들만 추출
    key 컬럼: 사용된 인덱스
    key_len: 사용된 가장 긴 key 부분
    ref 컬럼: 이 타입의 조인에서 NULL
    키 컬럼이 상수와 =, <>, >, >=, <, <=, IS NULL, <=>, BETWEEN 또는 IN 연산에 사용될때 적용됨
  • index
    인덱스가 스캔된다는걸 제외하면 ALL 과 같음
    일반적으로 인덱스 파일이 데이타파일보다 작기 때문에 ALL 보다는 빠름
    MySQL 은 쿼리에서 단일 인덱스의 일부분인 컬럼을 사용할때 이 조인타입을 적용함
  • ALL
    이전 테이블과의 조인을 위해 풀스캔
    (조인에 쓰인) 첫번째 테이블이 고정이 아니라면 비효율적
    대부분의 경우에 아주 느린 성능
정리:
system – const – eq_ref – ref – ref_or_null – index_mergy – unique_subquery – index_subquery – range – index – ALL
5. possible_keys : MySQL 이 해당 테이블의 검색에 사용할수 있는 인덱스들
possible_keys 에 나타난 인덱스들이 결과에 나타난 테이블 순서에서 실제 사용할 수 없을수도 있음
6. key :  MySQL 이 실제 사용한 key(index)
7. key_len : MySQL 이 사용한 인덱스의 길이, key 컬럼값이 NULL 이면 이값도 NULL
key_len 값으로 MySQL 이 실제 복수컬럼 키중 얼마나 많은 부분을 사용할 것인지 알 수 있음
8. ref : 행을 추출하는데 키와 함께 사용된 컬럼이나 상수값
9. rows : 쿼리 수행에서 MySQL 이 예상하는 검색해야할 행수
10. Extra : MySQL 이 쿼리를 해석한 추가적인 정보를 나타냄
  • Distinct: MySQL 이 매치되는 첫행을 찾는 즉시 검색을 중단한다는 의미
  • Not exists: MySQL 이 LEFT JOIN 을 수행함에 매치되는 한 행을 찾으면 더이상 매치되는 행을 검색x
  • range checked for each record (index map: #): MySQL 이 사용할 좋은 인덱스가 없음 의미
  • Using filesort: MySQL 이 정렬을 위해 추가적인 과정을 필요로 함
  • Using index: 컬럼정보가 실제 테이블이 아닌 인덱스트리에서 추출, 쿼리에서 단일 인덱스된 컬럼들만을 사용하는 경우
  • Using temporary: MySQL 이 결과의 재사용을 위해 임시테이블을 사용, 쿼리 내에 GROUP BY 와 ORDER BY 절이 각기 다른 컬럼을 사용할때 발생
  • Using where: WHERE 절이 다음 조인에 사용될 행이나 클라이언트에게 돌려질 행을 제한하는 경우 테이블의 모든 행을 검사할 의도가 아니면 ALL 이나 index 라면 쿼리사용이 잘못된 것임
  • Using sort_union(…) , Using union(…) , Using intersect(…)
  • Using index for group-by: Using index 와 접근방식이 같으며, 추가적인 디스크 접근 없이 GROUP BY 나 DICTINCT 쿼리에 사용된 모든 컬럼에 대한 인덱스를 찾았음을 의미
정리:
쿼리를 가능한 한 빠르게 하려면, Extra 값의 Using filesort 나 Using temporary 에 주의해야 함
EXPLAIN 의 출력내용중 rows 컬럼값들을 곱해봄으로써 얼마나 효과적인 join 을 실행하고 있는지 알 수 있다

'show processlist' in mysql

you can see process list

Friday, March 8, 2013

LOG setting in mysql

vi /etc/my.cnf

#general Query
log=mysql-general.log


#slow Query
slow-query-log = 1
long_query_time = 1
log_slow_queries = mysql-slow.log


restart mysql





Wednesday, March 6, 2013

count(*) over(order by no range between 2 preceding and 4 following)

select no, name, count(*)
over(order by no range between 2 preceding and 4 following) as sim_cnt
from pt_test

before -2 after 4 from your no


NO,NAME,SIM_CNT
-21,hello,1
1,hello2,4
4,hello2,3
4,hello,3
5,hello,3
10,hello,1

sum over() in oracle >> really good


select * from pt_test

NO,NAME
-21,hello
4,hello
1,hello2
4,hello2
5,hello
10,hello


select no, name, sum(no) over (partition by name ) value ,
sum(no) over (partition by name order by no range unbounded preceding) preceding from pt_test


NO,NAME,VALUE,PRECEDING
-21,hello,-2,-21
4,hello,-2,-17
5,hello,-2,-12
10,hello,-2,-2
1,hello2,5,1
4,hello2,5,5


rank, dense_rank, row_number difference


select * from pt_test



NO,NAME
-21,hello
4,hello
1,hello2
4,hello2
5,hello
10,hello



select no, name, rank() over(order by no desc) all_rank,
                 row_number() over(order by no desc) row_number,
                 dense_rank() over(order by no desc) dense_rank
from pt_test


NO,NAME,ALL_RANK,ROW_NUMBER,DENSE_RANK
10,hello,1,1,1
5,hello,2,2,2
4,hello,3,3,3
4,hello2,3,4,3
1,hello2,5,5,4
-21,hello,6,6,5




window function < rank() over >in oracle

select * from pt_test


NO,NAME
-21,hello
4,hello
1,hello2
4,hello2
5,hello
10,hello


select no, name, rank() over(order by no desc) all_rank,
 rank() over(partition by name  order by no desc) no_rank 
from pt_Test


NO,NAME,ALL_RANK,ALL_RANK_1
10,hello,1,1
5,hello,2,2
4,hello,3,3
4,hello2,3,1
1,hello2,5,2
-21,hello,6,4

Tuesday, March 5, 2013

How to use Connect by oracle


first create table


create table node(
em varchar(100),
ma varchar(100)
)


insert into node (em, ma) values(upper('a'), null)
insert into node (em, ma) values(upper('b'), upper('a'))
insert into node (em, ma) values(upper('c'), upper('a'))
insert into node (em, ma) values(upper('d'), upper('c'))
insert into node (em, ma) values(upper('e'), upper('c'))


commit;

select * from node




select level, lpad(' ', 4 * (level-1)) || em 사원, ma 관리자, connect_by_isleaf isleaf
from node
start with ma is null
connect by prior em = ma

select connect_by_root em 루트사원, sys_connect_by_path(em, '/') 경로, em, ma
from node
start with ma is null
connect by prior em = ma




Monday, March 4, 2013

Oracle Range Partition

// create partiton table

create table pt_test(
NO NUMBER NOT NULL,
NAME VARCHAR2(10) NULL
)
PARTITION BY RANGE(no)
(
PARTITION PT_DUMMY VALUES LESS THAN (-1)
);


//add partition
alter table PT_TEST ADD PARTITION PT_1 VALUES LESS THAN (5);

alter table PT_TEST ADD PARTITION PT_2 VALUES LESS THAN (11);

//TEST DATA INSERT
INSERT INTO PT_TEST VALUES (1 , 'A');
INSERT INTO PT_TEST VALUES (2 , 'B');
INSERT INTO PT_TEST VALUES (3 , 'C');
INSERT INTO PT_TEST VALUES (4 , 'D');
INSERT INTO PT_TEST VALUES (5 , 'E');
INSERT INTO PT_TEST VALUES (6 , 'F');
INSERT INTO PT_TEST VALUES (7 , 'G');
INSERT INTO PT_TEST VALUES (8 , 'H');
INSERT INTO PT_TEST VALUES (9 , 'I');
INSERT INTO PT_TEST VALUES (10 , 'J');
INSERT INTO PT_TEST VALUES (11 , 'K');



//Tset

SELECT * FROM PT_TEST
SELECT * FROM PT_TEST PARTITION (PT_1);
SELECT * FROM PT_TEST PARTITION (PT_2);



//drop partition

ALTER TABLE pt_test DROP PARTITION pt_1;



// change partition name

ALTER TABLE pt_test RENAME PARTITION pt_1 TO pt_one;



//  TRUNCATE partition data

ALTER TABLE pt_test TRUNCATE PARTITION pt_1;