Programming/node.js2014. 9. 13. 11:44

메뉴얼 사이트

 - Application :  http://expressjs.com/api.html#express

 - Request : http://expressjs.com/api.html#req.params

 - Response :  http://expressjs.com/api.html#res.status

 - Router : http://expressjs.com/api.html#router

 - Middleware : http://expressjs.com/api.html#middleware.api


테스트 샘플자료 (자세한 내용은 위에 API 참조하면 방대함 정규식처리등 많음)

  1. var express = require('express'), http = require('http');
  2. var bodyParser = require('body-parser');
  3. var app = express();
  4. app.use(bodyParser());
  5. app.all('*', function( req, res, next){
  6. res.writeHead(200,{
  7. "Content-Type" : "text/plain"
  8. });
  9. next();
  10. });
  11. app.get("/", function( req, res){
  12. res.end("HOME DIR : /");
  13. });
  14. app.get("/test", function( req, res){
  15. res.end("HOME DIR : /test");
  16. });
  17. app.get("/params/:user", function( req, res){
  18. var sText = " Params : "+req.params.user; // OR req.param('user')
  19. sText += "\n GET : "+req.query.q; //search?q=test OR req.param('q')
  20. sText += "\n POST : "+req.param('name'); //POST name=tobi
  21. //sText += "Cookie : "+req.cookies.name; // Cookie: name=tj
  22. sText += "\n ip : "+req.ip; // req.ips When "trust proxy" is `true`, parse the "X-Forwarded-For"
  23. res.end(sText);
  24. });
  25. app.get("*", function( req, res){
  26. res.end("NOT PAGE");
  27. });
  28. http.createServer(app).listen(80, '127.0.0.1');
  29. console.log('HTTP URL : http://127.0.0.1:80/');


Posted by 시니^^
Programming/node.js2014. 9. 12. 16:42

자세한 내용은 메뉴얼 참조 http://nodejs.org/api/globals.html#globals_global


Global Objects

 - global

 - process

 - console

 - Class: Buffer

 - require()

 - require.resolve()

 - require.cache

 - require.extensions

 - __filename

 - __dirname

 - module

 - exports

 - setTimeout(cb, ms)

 - clearTimeout(t)

 - setInterval(cb, ms)

 - clearInterval(t)


변수류

__filename : 실행중인 경로포함 파일이름

__dirname : 실행중인 파일 경로까지만


실행한 Process 정보

 - http://nodejs.org/api/process.html#process_process_versions



Posted by 시니^^
Programming/JS/Jquery/Ajax2014. 9. 11. 12:05

jQuery Table Plugin 괜찮은 것 소개


메뉴얼 : http://mottie.github.io/tablesorter/docs/index.html


데모http://mottie.github.io/tablesorter/docs/index.html#Demo


tablesorter Bootstrap LESS theme 도 지원함


아래 샘플 보면 row 추가삭제에 대한 설명이나 페이징에 대한 설명도 잘 나와있다.

샘플설명자료http://mottie.github.io/tablesorter/docs/index.html#Examples


그리고 다양한 추가 플로그인 존재하여서 관리툴 개발시 상당히 유용함

Plugins / Widgets
 these widgets are included in the jquery.tablesorter.widgets.js file (except for extra filter formatter functions) 
 this widget is included with the plugin core.


Posted by 시니^^
Programming/PHP2014. 9. 4. 15:43


Anonymous functions - http://php.net/manual/ro/functions.anonymous.php


있다는 것만 알지.. 사용하지 않았다.. 

그런데 구글링 중 괜찮은 활용 방법을 찾아서!! 왠지 jquery 하는듯한 느낌은 뭐지...;;

 - 특정 배열값 파싱하거나 재구성할때 for문 안돌리고 array_map 이용할때 괜찮은듯함.

예) http://stackoverflow.com/questions/13435747/how-can-i-remove-the-file-extension-from-each-string-in-a-php-array


  1. <?php
  2. # your array
  3. $slike = array('1.jpg','253455.jpg','32.jpg','477.jpg');
  4. # if you have PHP >= 5.3, I'd use this
  5. $slike = array_map(function($e){
  6. return pathinfo($e, PATHINFO_FILENAME);
  7. }, $slike);
  8. # if you have PHP <= 5.2, use this
  9. $slike = array_map('pathinfo', $slike, array_fill(
  10. 0, count($slike), PATHINFO_FILENAME
  11. ));
  12. # dump
  13. print_r($slike);
  14. /*print
  15. Array
  16. (
  17. [0] => 1
  18. [1] => 253455
  19. [2] => 32
  20. [3] => 477
  21. )
  22. */
  23. ?>


※ 단 PHP 5.3 이상부터 가능함!

Posted by 시니^^
DB/NoSQL/Mysql2014. 9. 4. 11:23


※  DISTINCT 와 GROUP BY 의 경우 처리방식은 비슷하지만 사용하는 성향에 따라서 조금씩 이용하는 곳이 다르다.

     그리고 가장 큰 차이는 GROUP BY 의 경우 정렬이 일어나는 것이다.

     아래의 예시를 보면 file sort가 일어나는 것을 볼 수 있다.


CREATE TABLE `asd` (
  `idx` int(11) NOT NULL AUTO_INCREMENT,
  `id` varchar(20) NOT NULL DEFAULT '',
  `data` varchar(20) NOT NULL DEFAULT '',
  PRIMARY KEY (`idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into asd (id,data)values('a',100);
insert into asd (id,data)values('a',100);
insert into asd (id,data)values('c',100);
insert into asd (id,data)values('d',100);
insert into asd (id,data)values('c',100);
insert into asd (id,data)values('c',100);
insert into asd (id,data)values('d',100);
insert into asd (id,data)values('d',100);


※ id 컬럼에 index가 걸려있다면 filesort가 나지 않지만 걸려 있지 않다면 아래와 같이 filesort가 일어난다.

   해당 쿼리가 비번하게 일어난다면 filesort의 경우 성능에 큰 차이를 보일 수 있다. 

   그래서 정렬이 필요하지 않을 경우에는 order by null를 입력해서 filesort를 막을 수있다.


mysql> explain select * from asd group by id;
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra                           |
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
|  1 | SIMPLE      | asd   | ALL  | NULL          | NULL | NULL    | NULL |    8 | Using temporary; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
1 row in set (0.00 sec)
mysql> explain select * from asd group by id order by null;
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra           |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------+
|  1 | SIMPLE      | asd   | ALL  | NULL          | NULL | NULL    | NULL |    8 | Using temporary |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------+
1 row in set (0.00 sec)


※ 해당 내용은 아래 블로그를 참조 하였으며 자세한 내용은 아래 블로그에서 설명을 볼 수 있습니다.

DISTINCT 와 GROUP BY의 차이 - http://intomysql.blogspot.kr/2011/01/distinct-group-by.html

GROUP BY의 Filesort 작업 제거 - http://intomysql.blogspot.kr/2010/12/group-by-filesort.html



Posted by 시니^^
SERVER/Nginx2014. 8. 29. 15:28
IE나 크롬 개발자 도구로 Response Headers 보게 되면  아래와 같이 서버버젼과 PHP버젼이 적나하게 보이는 경우가 있다
항상 버젼 업데이트를 한다고 하면 문제 없겠지만 늘 버그/보안취약점이 나와서 버젼 업데이트가 되고 있는 중에 
해당 버젼을 확인하고 취약점을 해킹하는 경우가 발생한다 그래서 해당 정보의 경우 숨기는 게 보다 안전하다고 생각된다.

  1. Cache-Control:
    no-store, no-cache, must-revalidate, post-check=0, pre-check=0
  2. Connection:
    keep-alive
  3. Content-Type:
    text/html; charset=UTF-8
  4. Date:
    Fri, 29 Aug 2014 06:22:59 GMT
  5. Expires:
    Thu, 19 Nov 1981 08:52:00 GMT
  6. Pragma:
    no-cache
  7. Server:
    nginx/1.6.1
  8. Transfer-Encoding:
    chunked
  9. X-Powered-By:
    PHP/5.5.15


※ X-Powered-By:PHP/5.5.15 삭제

vi /etc/php.ini

expose_php = Off <== OFF로 변경


※ Nginx 숨기기

http://wiki.nginx.org/HttpCoreModule#server_tokens

vi /etc/nginx/nginx.conf

server_tokens off; <==내용추가함


=> php와 nginx수정하였다면 php-fpm과 nginx 재시작해줘야됨


※ Nginx라는 서버이름을 바꾸고 싶을때

1. HttpHeadersMoreModule 추가모듈설치 하여서 셋팅

http://wiki.nginx.org/HttpHeadersMoreModule#Installation

※ 소스설치시 추가하면됨

./configure --prefix=/opt/nginx --add-module=/path/to/headers-more-nginx-module

※ set the Server output header 

    more_set_headers 'Server: my-server';


2. 컴파일전에 소스코드에서 해당내용 삭제 또는 변경 

http://forum.nginx.org/read.php?11,1646

vi /path/to/nginx-0.*/src/http/ngx_http_header_filter_module.c lines 48 and 49:

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

static char ngx_http_server_string[] = "Server: nginx" CRLF;

static char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;

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


※ Apache 경우

vi /etc/httpd/conf/httpd.conf

ServerTokens Prod

ServerSignature Off

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

ServerTokens Prod[uctOnly] => Server: Apache
ServerTokens Major => Server: Apache/2
ServerTokens Minor => Server: Apache/2.0
ServerTokens Min[imal] => Server: Apache/2.0.41
ServerTokens OS : Server => Apache/2.0.41 (Unix)
ServerTokens Full : Server => Apache/2.0.41 (Unix) PHP/4.2.2 MyMod/1.2


Posted by 시니^^
Programming/JS/Jquery/Ajax2014. 8. 21. 18:51

※ Jquery용 tablesorter 

http://mottie.github.io/tablesorter/docs/index.html


※ 설명가이드가 상당히 잘되어있음(페이징설명되어있음)

http://mottie.github.io/tablesorter/docs/index.html#Demo

http://mottie.github.io/tablesorter/docs/index.html#Examples


※ 부스트랩테마도 지원

http://mottie.github.io/tablesorter/docs/example-widget-bootstrap-theme.html


Posted by 시니^^
Programming/JAVA2014. 7. 31. 16:06

서버 환경

CentOS 6.5

TOMCAT 7

java version "1.7.0_55"


1. 간단하게 vi catalina.sh 또는 vi setenv.sh 설정함

----------------------------------------

CATALINA_OPTS="$CATALINA_OPTS

-Djava.rmi.server.hostname=xxx.xxx.xxx.xxx 

-Dcom.sun.management.jmxremote

-Dcom.sun.management.jmxremote.port=9080

-Dcom.sun.management.jmxremote.rmi.port=9081

-Dcom.sun.management.jmxremote.authenticate=false

-Dcom.sun.management.jmxremote.ssl=false"

----------------------------------------


2. 인증 방식 넣기 (설정시 access,password파일 추가등록)

------------------------------------------------

CATALINA_OPTS="$CATALINA_OPTS

-Djava.rmi.server.hostname=xxx.xxx.xxx.xxx 

-Dcom.sun.management.jmxremote

-Dcom.sun.management.jmxremote.ssl=false

-Dcom.sun.management.jmxremote.port=9080

-Dcom.sun.management.jmxremote.rmi.port=9081

-Dcom.sun.management.jmxremote.authenticate=true

-Dcom.sun.management.jmxremote.access.file=$CATALINA_HOME/conf/jmxremote.access

-Dcom.sun.management.jmxremote.password.file=$CATALINA_HOME/conf/jmxremote.password

------------------------------------------------


※ 계정등록 ( 구글링해보니까 LDAP 연동 방법도 있는 듯 필요시 구글링해볼것!! )

https://code.google.com/p/tungsten-replicator/source/browse/trunk/commons/conf/sample.jmxremote.access?spec=svn1148&r=1148


vi jmxremote.access ( 계정에 맞게 readonly 또는 readwrite )

------------------------------------------------

admin readwrite \

      create javax.management.moitor.*,javax.management.timer.* \

      unregister

------------------------------------------------


vi jmxremote.password

------------------------------------------------

admin password

------------------------------------------------




3. 에러발생시 처리 방안

※ Error: Exception thrown by the agent : java.net.MalformedURLException: Local host name unknown: java.net.UnknownHostException: dev-was01: dev-was01: Name or service not known

 => vi /etc/hosts 아래 host 추가하면됨

     127.0.0.1   localhost dev-was01

※ shutdown시 Error: Exception thrown by the agent : java.lang.NullPointerException

 => CATALINA_OPTS 아닌 JAVA_OPTS 에 넣으면 Exception 에러발생


※ catalina-jmx-remote.jar 필요시 톰캣사이트에서 다운르도 후 lib폴더에 넣기!

 => http://archive.apache.org/dist/tomcat/tomcat-7/v7.0.53/bin/extras/




4. Apache 메뉴얼 listener was configured in server.xml 추가하는 방법


URL : http://tomcat.apache.org/tomcat-7.0-doc/config/listeners.html

AttributeDescription
rmiRegistryPortPlatform

The port to be used by the JMX/RMI registry for the Platform MBeans. This replaces the use of thecom.sun.management.jmxremote.port system property that should not be set when using this listener.

rmiServerPortPlatform

The port to be used by the Platform JMX/RMI server.

rmiBindAddress

The address of the interface to be used by JMX/RMI server. This option is incompatible with setting the system propertycom.sun.management.jmxremote.ssl to true.

useLocalPorts

Should any clients using these ports be forced to use local ports to connect to the the JMX/RMI server. This is useful when tunnelling connections over SSH or similar. Defaults to false.

Using file-based Authentication and Authorisation

If this listener was configured in server.xml as:

  <Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener"
          rmiRegistryPortPlatform="10001" rmiServerPortPlatform="10002" />

with the following system properties set (e.g. in setenv.sh):

  -Dcom.sun.management.jmxremote.password.file=$CATALINA_BASE/conf/jmxremote.password
  -Dcom.sun.management.jmxremote.access.file=$CATALINA_BASE/conf/jmxremote.access
  -Dcom.sun.management.jmxremote.ssl=false

$CATALINA_BASE/conf/jmxremote.password containing:

admin letmein

$CATALINA_BASE/conf/jmxremote.access containing:

admin readwrite

then opening ports 10001 (RMI Registry) and 10002 (JMX/RMI Server) in your firewall would enable jconsole to connect to a Tomcat instance running behind a firewall using a connection string of the form:

service:jmx:rmi://<hostname>:10002/jndi/rmi://<hostname>:10001/jmxrmi

with a user name of admin and a password of letmein.



Posted by 시니^^
Programming/JAVA2014. 6. 25. 14:27

개발후 배포시 war로 압축해서 배포하는 그때


서버환경(개발/운영)에 따라서 DB접근 정보나 기타 cfg 설정이 다른 경우가 있다


그런 경우 PropertyPlaceholderConfigurer등 설정 정보를 다르게 보게 해야되는 데


구글링 해보니까 아래 Stackoverflow 몇가지를 제시하고있다. 


http://stackoverflow.com/questions/11735526/spring-loading-application-properties-based-on-tomcat-servlet-contect-definition


그중에 괜찮다고 생각되는 두가지 방안


1. 아래 방법처림 배포될 서버에 예상해서 설정해서 여러개로 구성하는 방법

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:your-production-config.properties</value>
            <value>file:C:/Users/${user.name}/test-application.properties</value>
        </list>
    </property>
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
    <property name="ignoreResourceNotFound" value="true"/>
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>        
</bean>


2. ${catalina.home} 변수 이용한 Tomcat 디렉토리의 conf에 설정을 따로 구성해두는 방안

<context:property-placeholder location="file:${catalina.home}/conf/myFirst.properties" ignore-unresolvable="true" />
<context:property-placeholder   location="classpath:second.properties"  ignore-unresolvable="true"  />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
    <value>file:${catalina.home}/conf/dbpool.properties</value>
</property>
</bean>


개발환경에서 한개 서버에 버젼에 따라서 여러 톰캣을 띄워야 할 경우에는 2번 방법이 괜찮은 것 같다.

Posted by 시니^^
Programming/JAVA2014. 6. 24. 11:56

form / Ajax 통해서 URL or Get 데이터 encodeURIComponent 보낼때에


한글이 제대로 인코딩이 안된다고하면


web.xml에 아래 해당 filter 정보를 입력해준다


그리고 filter-name의 정보를 해당 url pattern에 mapping 해주면된다 servlet에 따라서 mapping 해줄것!!

일반적으로 전체가 다 UTF-8 환경이라면 /* 하면될듯하다.


  
    encodingFilterUTF8
    org.springframework.web.filter.CharacterEncodingFilter 
    
        encoding
        UTF-8
    
  
  
    encodingFilterUTF8
    /*
  
  
Posted by 시니^^