2018. 4. 24.

Spring Schedule :: cron 표현식 정리

Spring Schedule 설정을 위해 시간/주기 등을 설정하는 표현식 입니다. 

하단에 출처 적어 놓았습니다.

cron 표현식
문자열의 좌측부터 우측까지 아래의 순서대로 의미가 있고 각 항목은 space 문자로 구분한다.
 순서
필드명
사용 가능한 값
 1
 seconds
 0~59 , - * /
 2
 minutes
 0~59 , - * /
 3
 hours
 0~23 , - * /
 4
 day of month
 1~31 , - * ? / L W
 5
 month
 1~12 or JAN-DEC , - * /
 6
 day of week
 1-7 or SUN-SAT , - * ? / L #
 7
 years (optional)
 1970~2099 , - * /

특수문자의 의미
 기호
의미 
 사용 예
 *
 모든 수를 의미
seconds에서 사용하면 매초, minutes에서 사용하면 매분, hours에서 사용하면 매시간 
 ?
 해당 항목을 사용하지 않음
day of month에서 사용하면 월중 날짜를 지정하지 않음. day of week에서 사용하면 주중 요일을 지정하지 않음 
 -
 기간을 설정
hours에서 10-12이면 10시, 11시, 12시에 동작
minutes에서 58-59이면 58분, 59분에 동작
 ,
특정 시간을 지정
day of week에서 2,4,6이면 월,수,금에만 동작함
 /
시작시간과 반복 간격 설정
seconds위치에 0/15로 설정하면 0초에 시작해서 15초 간격으로 동작 
minutes위치에 5/10으로 설정하면 5분에 시작해서 10분 간격으로 동작
 L
마지막 기간에 동작
day of month, day of week에서만 사용
day of month에서 사용하면 해당월 마지막 날에 수행
day of week에서 사용하면 토요일에 수행
 W
가장 가까운 평일 동작
day of month에만 사용 
15W로 설정하면 15일이 토요일이면 가장 가까운 14일 금요일에 실행
15W로 설정하고 15일이 일요일이면 16일에 실행
15W로 설정하고 15일이 평일이면 15일에 실행
 LW
L과 W의 조합 
그달의 마지막 평일에 동작 
 #
몇 번째 주와 요일 설정
day of week에 사용 
6#3이면 3 번째 주 금요일에 동작 
4#2이면 2번째 주 수요일에 동작

사용 예
 표현식
의미 
 0 0 12 * * *
매일 12시에 실행 
 0 15 10 * * *
매일 10시 15분에 실행 
 0 * 14 * * *
매일 14시에 0분~59분까지 매분 실행
 0 0/5 14 * * *
매일 14시에 시작해서 5분 간격으로 실행 
 0 0/5 14,18 * * *
매일 14시, 18시에 시작해서 5분 간격으로 실행 
 0 0-5 14 * * *
매일 14시에 0분, 1분, 2분, 3분, 4분, 5분에 실행 
 0 0 20 ? * MON-FRI
월~금일 20시 0분 0초에 실행 
 0 0/5 14 * * ?
아무요일, 매월, 매일 14:00부터 14:05분까지 매분 0초 실행 (6번 실행됨)
 0 15 10 ? * 6L
 매월 마지막 금요일 아무날이나 10:15:00에 실행
 0 15 10 15 * ?
아무요일, 매월 15일 10:15:00에 실행 
 * /1 * * * *
매 1분마다 실행
 * /10 * * * *
매 10분마다 실행 



이전 Task와 Delay 설정
 표현
의미 
 fixed-delay
 이전에 실행된 task의 종료시간으로부터 정의된 시간만큼 지난 후 다음 task를 실행
밀리세컨드 단위
 fixed-rate
 이전에 실행된 task의 시작 시간으로부터 정의된 시간만큼 지난 후 다음 task를 실행
밀리세컨드 단위


2018. 3. 27.

Amcharts excel/Image(png,jpg,svg) 기능 추가하기.

Amcharts의 Export 기능을 사용해 보자.
내보내기 기능을 사용하기 위해선 아래 소스를 적용 시켜야 한다.


<script src="//cdn.amcharts.com/lib/3/plugins/export/export.min.js">
<link href="//cdn.amcharts.com/lib/3/plugins/export/export.css" rel="stylesheet" type="text/css">


아래의 toCSV와 formats.CSV.mimeType을 엑셀이나 다른 형식으로 바꿔주면 CSV 외의 다른 형식으로 내보내기를 할 수 있다. 자세한 사항은 하단 링크를 참조!

    var exportArr = [];
    var chartData = 차트 데이터;

    var temp = {
        label: "temp_title",
        click: function(e,dt) {
            var realData = [], realTitle = "파일명";
            realData = chartData;
            chart.export.toCSV({
                data: realData
            }, function(data) {
                this.download(data, this.defaults.formats.CSV.mimeType, realTitle+".csv");
            });
        }
    }
    exportArr.push(temp);

AmCharts.makeChart( "chartdiv", {
    "export": {
        "enabled": true,
            "exportFields": [
            "logDate",
            "logVal",
        ],
            "columnNames": {
            "logDate": "logDate",
                "logVal": "Value",
        },
        menu:[{
            "class":"export-main",
            menu: [
                {
                    label: "Download CSV",
                    // class: "export-main",
                    menu: exportArr
                }
            ]
        }]
    }
});


참고 링크 - https://github.com/amcharts/export

2017. 11. 30.

JAVA BindingResult(ModelAttribute) 에러 확인하는법

종종 바인딩 값에 대한 에러 확인을 하고 싶을 경우가 발생한다.

그럴 경우 간단하게 아래와 같이 확인 할 수 있다.


public String name(@ModelAttribute vo vo,BindingResult errors) throws Exception {
 if (errors.hasErrors()) {
        System.out.println(":::::::::::::::::: 에러확인 시작 :::::::::::::::::");
        System.out.println(errors.getFieldError());
        System.out.println(":::::::::::::::::: 에러확인 끝 :::::::::::::::::");
 }
}


2017. 11. 28.

제이쿼리 Tabs 사용시 jQueryUI CSS 제거하기


제이쿼리 탭 사용할 경우 jQueryUI를 제거해야할 경우가 발생한다.

아래와 같이 스크립트 적용하면, 해당 CSS를 제거 할 수 있다.

var jQueryUiClass = [".ui-tabs", ".ui-tabs-nav", ".ui-tabs-panel", ".ui-widget", ".ui-widget-header", ".ui-widget-content", ".ui-corner-all", ".ui-corner-top", ".ui-corner-bottom", ".ui-helper-clearfix", ".ui-helper-reset", ".ui-state-default"];

$("#tabs").tabs().each(function(){
   $tabEle = $(this).find( jQueryUiClass.join(", ") ).andSelf();
   $tabEle.removeClass( jQueryUiClass.join(" ").replace(/\./g, "") );
});

2017. 10. 22.

Atom(아톰) Tab space(탭 스페이스) 공백 설정 방법

아톰 : file > Settings > Editor > Tab Length

Tab Length 변경!

아래 이미지 파일을 보시면 쉽게 이해하실 수 있습니다.


2017. 9. 25.

Log4j2.xml 기본 설정 (전자정부프레임워크)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <!-- <PatternLayout pattern="%d %5p [%c] %m%n" /> -->
            <PatternLayout pattern="%d %5p (%13F:%L) | %m%n" />
        </Console>
    </Appenders>
    <Loggers>
        <!--특정 로그가 필요한 경우 사용한다.-->
        <!--<Logger name="매퍼네임" level="debug" />-->
 
        <Logger name="egovframework.com.builder" level="debug" additivity="false">
            <AppenderRef ref="console" />
        </Logger>
        <logger name="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" additivity="false">
            <level value="debug" />
            <appender-ref ref="console" />
        </logger>
        <logger name="egovframework.rte.cmmn.ria.support.ExtAnnotationHandlerMapping" additivity="false">
            <level value="debug" />
            <appender-ref ref="console" />
        </logger>
        <logger name="org.springframework.beans.factory.support.DefaultListableBeanFactory" additivity="false">
            <level value="debug" />
            <appender-ref ref="console" />
        </logger>
        
        <Root level="ERROR">
            <AppenderRef ref="console" />
        </Root>
    </Loggers>
 
</Configuration>
 
cs

2017. 1. 4.

Mysql :: 데이터베이스 하위 테이블 모두 삭제


--외래키무시.

SET foreign_key_checks = 0;
SET @tables = NULL;

SELECT GROUP_CONCAT(table_schema, '.', table_name) INTO @tables
FROM information_schema.tables 
WHERE table_schema = '데이터베이스명'; -- specify DB name here.
SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


--외래키 다시 허용.

SET foreign_key_checks = 1;

2015. 8. 20.

Mysql 테이블 명세서 쿼리로 뽑기.

테이블 명세서 쿼리로 뽑아보자!



1. 아래 쿼리를 실행하면 테이블 명세에 필요한 정보가 나온다.


SELECT 
  ORDINAL_POSITION '필드순번',
  COLUMN_NAME '필드명',
  DATA_TYPE '데이터 TYPE',
  COLUMN_TYPE '데이터 LENGTH',
  COLUMN_KEY 'KEY',
  IS_NULLABLE 'NULL값여부',
  EXTRA '자동여부',
  COLUMN_DEFAULT '디폴트값',
  COLUMN_COMMENT '필드설명'

FROM 
  `information_schema`.COLUMNS 

WHERE
  TABLE_SCHEMA = '데이터베이스이름'
  AND TABLE_NAME = '테이블이름'

ORDER BY
  TABLE_NAME, ORDINAL_POSITION 

2015. 8. 17.

PHP Session(세션)

PHP 세션 사용 방법



PHP세션 사용방법에 대해 알아보도록 하자.

1. PHP에서 세션을 사용하기 위해서는 session_start(); 를 선언해주여야한다.


<? 
   session_start(); 
?>


2. 세션을 저장하기 위해 아래와 같이 사용한다.

<? 
   session_start();
   $_SESSION["arg_test"] = "test"; //세션에 값설정
?>


3. 세션 확인.

<? 
   session_start();
   echo $_SESSION["arg_test"]; //"test" 를 출력한다.
?>


4. 세션 초기화.

<? 
   session_start();
   session_destroy();
   echo $_SESSION["arg_test"]; //아무값도 없음.
?>







MysqliDb.php 사용법 및 Github 링크


https://github.com/joshcam/PHP-MySQLi-Database-Class

Initialization

To utilize this class, first import MysqliDb.php into your project, and require it.
require_once ('MysqliDb.php');
After that, create a new instance of the class.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
Its also possible to set a table prefix:
$db->setPrefix ('my_');
Next, prepare your data, and call the necessary methods.

Insert Query

Simple example
$data = Array ("login" => "admin",
               "firstName" => "John",
               "lastName" => 'Doe'
)
$id = $db->insert('users', $data);
if($id)
    echo 'user was created. Id='.$id;
Insert with functions use
$data = Array(
    'login' => 'admin',
    'active' => true,
    'firstName' => 'John',
    'lastName' => 'Doe',
    'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")),
    // password = SHA1('secretpassword+salt')
    'createdAt' => $db->now(),
    // createdAt = NOW()
    'expires' => $db->now('+1Y')
    // expires = NOW() + interval 1 year
    // Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear
);

$id = $db->insert ('users', $data);
if ($id)
    echo 'user was created. Id=' . $id;
else
    echo 'insert failed: ' . $db->getLastError();

Update Query

$data = Array (
    'firstName' => 'Bobby',
    'lastName' => 'Tables',
    'editCount' => $db->inc(2),
    // editCount = editCount + 2;
    'active' => $db->not()
    // active = !active;
);
$db->where ('id', 1);
if ($db->update ('users', $data))
    echo $db->count . ' records were updated';
else
    echo 'update failed: ' . $db->getLastError();

Select Query

After any select/get function calls amount or returned rows is stored in $count variable
$users = $db->get('users'); //contains an Array of all users 
$users = $db->get('users', 10); //contains an Array 10 users
or select with custom columns set. Functions also could be used
$cols = Array ("id", "name", "email");
$users = $db->get ("users", null, $cols);
if ($db->count > 0)
    foreach ($users as $user) { 
        print_r ($user);
    }
or select just one row
$db->where ("id", 1);
$user = $db->getOne ("users");
echo $user['id'];

$stats = $db->getOne ("users", "sum(id), count(*) as cnt");
echo "total ".$stats['cnt']. "users found";
or select one column or function result
$count = getValue ("users", "count(*)");
echo "{$count} users found";

Delete Query

$db->where('id', 1);
if($db->delete('users')) echo 'successfully deleted';

Generic Query Method

By default rawQuery() will filter out special characters so if you getting problems with it you might try to disable filtering function. In this case make sure that all external variables are passed to the query via bind variables
// filtering enabled
$users = $db->rawQuery('SELECT * from users where customerId=?', Array (10));
// filtering disabled
//$users = $db->rawQuery('SELECT * from users where id >= ?', Array (10), false);
foreach ($users as $user) {
    print_r ($user);
}
More advanced examples:
$params = Array(1, 'admin');
$users = $db->rawQuery("SELECT id, firstName, lastName FROM users WHERE id = ? AND login = ?", $params);
print_r($users); // contains Array of returned rows

// will handle any SQL query
$params = Array(10, 1, 10, 11, 2, 10);
$q = "(
    SELECT a FROM t1
        WHERE a = ? AND B = ?
        ORDER BY a LIMIT ?
) UNION (
    SELECT a FROM t2 
        WHERE a = ? AND B = ?
        ORDER BY a LIMIT ?
)";
$resutls = $db->rawQuery ($q, $params);
print_r ($results); // contains Array of returned rows

Where Method

This method allows you to specify where parameters of the query. WARNING: In order to use column to column comparisons only raw where conditions should be used as column name or functions cant be passed as a bind variable.
Regular == operator with variables:
$db->where ('id', 1);
$db->where ('login', 'admin');
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE id=1 AND login='admin';
Regular == operator with column to column comparison:
// WRONG
$db->where ('lastLogin', 'createdAt');
// CORRECT
$db->where ('lastLogin = createdAt');
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE lastLogin = createdAt;
$db->where ('id', 50, ">=");
// or $db->where ('id', Array ('>=' => 50));
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE id >= 50;
BETWEEN / NOT BETWEEN:
$db->where('id', Array (4, 20), 'BETWEEN');
// or $db->where ('id', Array ('BETWEEN' => Array(4, 20)));

$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id BETWEEN 4 AND 20
IN / NOT IN:
$db->where('id', Array(1, 5, 27, -1, 'd'), 'IN');
// or $db->where('id', Array( 'IN' => Array(1, 5, 27, -1, 'd') ) );

$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id IN (1, 5, 27, -1, 'd');
OR CASE
$db->where ('firstName', 'John');
$db->orWhere ('firstName', 'Peter');
$results = $db->get ('users');
// Gives: SELECT * FROM users WHERE firstName='John' OR firstName='peter'
NULL comparison:
$db->where ("lastName", NULL, '<=>');
$results = $db->get("users");
// Gives: SELECT * FROM users where lastName <=> NULL
Also you can use raw where conditions:
$db->where ("id != companyId");
$db->where ("DATE(createdAt) = DATE(lastLogin)");
$results = $db->get("users");
Or raw condition with variables:
$db->where ("(id = ? or id = ?)", Array(6,2));
$db->where ("login","mike")
$res = $db->get ("users");
// Gives: SELECT * FROM users WHERE (id = 2 or id = 2) and login='mike';
Optionally you can use method chaining to call where multiple times without referencing your object over an over:
$results = $db
    ->where('id', 1)
    ->where('login', 'admin')
    ->get('users');

Ordering method

$db->orderBy("id","asc");
$db->orderBy("login","Desc");
$db->orderBy("RAND ()");
$results = $db->get('users');
// Gives: SELECT * FROM users ORDER BY id ASC,login DESC, RAND ();
order by values example:
$db->orderBy('userGroup', 'ASC', array('superuser', 'admin', 'users'));
$db->get('users');
// Gives: SELECT * FROM users ORDER BY FIELD (userGroup, 'superuser', 'admin', 'users') ASC;

Grouping method

$db->groupBy ("name");
$results = $db->get ('users');
// Gives: SELECT * FROM users GROUP BY name;
Join table products with table users with LEFT JOIN by tenantID

JOIN method

$db->join("users u", "p.tenantID=u.tenantID", "LEFT");
$db->where("u.id", 6);
$products = $db->get ("products p", null, "u.name, p.productName");
print_r ($products);

Properties sharing

Its is also possible to copy properties
Simple pagination example:
$db->where ("agentId", 10);
$db->where ("active", true);

$customers = $db->copy ();
$res = $customers->get ("customers", Array (10, 10));
// SELECT * FROM customers where agentId = 10 and active = 1 limit 10, 10

$res = $db->getOne ("customers", "count(id) as cnt");
echo "total records found: " . $res['cnt'];
// SELECT count(id) FROM users where agentId = 10 and active = 1

Subqueries

Subquery in selects:
$ids = $db->subQuery ();
$ids->where ("qty", 2, ">");
$ids->get ("products", null, "userId");

$db->where ("id", $ids, 'in');
$res = $db->get ("users");
// Gives SELECT * FROM users WHERE id IN (SELECT userId FROM products WHERE qty > 2)
Subquery in inserts:
$userIdQ = $db->subQuery ();
$userIdQ->where ("id", 6);
$userIdQ->getOne ("users", "name"),

$data = Array (
    "productName" => "test product",
    "userId" => $userIdQ,
    "lastUpdated" => $db->now()
);
$id = $db->insert ("products", $data);
// Gives INSERT INTO PRODUCTS (productName, userId, lastUpdated) values ("test product", (SELECT name FROM users WHERE id = 6), NOW());

EXISTS / NOT EXISTS condition

$sub = $db->subQuery();
    $sub->where("company", 'testCompany');
    $sub->get ("users", null, 'userId');
$db->where (null, $sub, 'exists');
$products = $db->get ("products");
// Gives SELECT * FROM products WHERE EXISTS (select userId from users where company='testCompany')

Helper commands

Reconnect in case mysql connection died
if (!$db->ping())
    $db->connect()
Obtain an initialized instance of the class from another class
    $db = MysqliDb::getInstance();
Get last executed SQL query. Please note that function returns SQL query only for debugging purposes as its execution most likely will fail due missing quotes around char variables.
    $db->get('users');
    echo "Last executed query was ". $db->getLastQuery();

Transaction helpers

Please keep in mind that transactions are working on innoDB tables. Rollback transaction if insert fails:
$db->startTransaction();
...
if (!$db->insert ('myTable', $insertData)) {
    //Error while saving, cancel new record
    $db->rollback();
} else {
    //OK
    $db->commit();
}