2016년 7월 7일 목요일

[SpRiNg] Spring Security 강제 로그인


Spring Security를 적용한 경우 session 에 값만 만들어 준다고 로그인 처리가 되지 않는다.

아래의 코드는 Spring Security 3.2.7.RELEASE 와 4.1.0.RELEASE 에서 쿠키를 이용하여 로그인을 처리 해야 하는 경우에 사용 하였다.

// 사용자의 아이디, 비밀번호, ROLE_ 로 시작 하는 권한 정보를 가지고 온다.
MySessionDataDto mInfo = commonSvc.getMySessionData(userid); 
Authentication authentication = new UsernamePasswordAuthenticationToken(mInfo.getUserid(), mInfo.getUserpw(), AuthorityUtils.createAuthorityList(mInfo.getUserauth()));
   
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
HttpSession session = request.getSession(true);
 

// 세션에 필요한 정보를 넣어 준다.
session.setAttribute("userid", mInfo.getUserid());
session.setAttribute("usernm", mInfo.getUsernm());


2016년 6월 16일 목요일

[EtC] mysql 한글 깨지는 경우



my.cnf 파일을 수정 하여 아래의 내용을 넣는다.


[client]
default-character-set = utf8


[mysql]
default-character-set = utf8


[mysqld]
init_connect = SET collation_connection = utf8_general_ci
init_connect = SET NAMES utf8
character-set-server = utf8
collation-server = utf8_general_ci


[mysqldump]
default-character-set = utf8

[EtC] tomcat startup 느려진 경우



INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [190,232] milliseconds.


tomcat startup 이 느려진 이유를 찾기 위해 catalina.log 를 보니, 위와 같은 메세지가 보이는 경우 catalina.sh 파일에 아래와 같이 추가 하도록 한다.

#!/bin/sh

JAVA_OPTS="$JAVA_OPTS -Djava.security.egd=file:/dev/./urandom"



참고 : tomcat 메모리 할당

#!/bin/sh

export CATALINA_OPTS="-server -Xms8192m -Xmx8192m -XX:PermSize=256M -XX:MaxPermSize=256M -XX:ParallelGCThreads=4 -XX:+UseConcMarkSweepGC -XX:+AggressiveOpts"


2016년 6월 2일 목요일

[MySqL] mysql backup script

root@api:/usr/local/apache-tomcat-7.0.64# cat ~/mysql-backup.sh


#!/bin/bash

backupdir='/home/freecatz/MYSQL_BACKUP/'`date +%Y%m%d`
olddir='/home/freecatz/MYSQL_BACKUP/'`date -d "7 day ago" +%Y%m%d`

function FN_DB_BACKUP(){
echo $(date +%H:%M) - $1 DATABASE FULL BACKUP START.  >>  $backupdir/$1.log
mysqldump -uroot -p'qwer1234' $1 > $backupdir/$1.sql
echo $(date +%H:%M) - $1 DATABASE FULL BACKUP FINISH.  >>  $backupdir/$1.log
mysql -uroot -p'qwer1234' -e "SELECT TABLE_SCHEMA, CONCAT(FORMAT(SUM(DATA_LENGTH + INDEX_LENGTH) / (1024*1024), 2), 'MB') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$1'" | grep -v TABLE_SCHEMA >> $backupdir/$1.log
}


function FN_MK_DIR(){
mkdir -p $backupdir

if [ -d $olddir ]; then
rm -rf $olddir
fi
}


if [ ! -d $backupdir ]; then
FN_MK_DIR
fi


FN_DB_BACKUP DBTEST1
FN_DB_BACKUP DBTEST2
FN_DB_BACKUP DBTEST3


crontab 에 주기적으로 실행 시켜 두면 된다.

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

00 23   * * *   root    /root/mysql-backup.sh
#

2016년 5월 26일 목요일

[Qt] String to QDate

QDate dt = QDate::fromString(ui->dateEdit->text(), "yyyy-MM-dd");

    switch(dt.dayOfWeek()){
       case 1:
            qInfo() << ui->dateEdit->text() << " 월요일 입니다.";
            break;
        case 2:
            qInfo() << ui->dateEdit->text() << " 화요일 입니다.";
            break;
        case 3:
            qInfo() << ui->dateEdit->text() << " 수요일 입니다.";
            break;
        case 4:
            qInfo() << ui->dateEdit->text() << " 목요일 입니다.";
            break;
        case 5:
            qInfo() << ui->dateEdit->text() << " 금요일 입니다.";
            break;
        case 6:
            qInfo() << ui->dateEdit->text() << " 토요일 입니다.";
            break;
        case 7:
            qInfo() << ui->dateEdit->text() << " 일요일 입니다.";
            break;
    }

[Qt5] Open Default Web Browser


#include 

    QDesktopServices::openUrl(QUrl("freecatz.blogspot.kr"));

[Qt5] Hardware Infomation

#include 

    qInfo() << QSysInfo::currentCpuArchitecture();
    qInfo() << QSysInfo::kernelType();
    qInfo() << QSysInfo::kernelVersion();
    qInfo() << QSysInfo::machineHostName();
    qInfo() << QSysInfo::prettyProductName();
    qInfo() << QSysInfo::productType();
    qInfo() << QSysInfo::productVersion();
    ....

[Qt5] UUID

#include 

    QUuid uuid = QUuid::createUuid();
    qInfo() << uuid.toString();

[Qt5] IP Address and MAC Address

.pro file

QT       += network



.cpp source file

#include 
#include 

    QString _MAC = "";
    QString _IP = "";
    
    QTcpSocket socket;
    socket.connectToHost("8.8.8.8", 53); // google DNS, or something else reliable
    if (socket.waitForConnected(3000)) {
//        qInfo() << socket.localAddress().toString();
        foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces()){
            foreach (QNetworkAddressEntry entry, interface.addressEntries()){
                if(socket.localAddress().toString() == entry.ip().toString()){
                    qInfo() << socket.localAddress().toString() << " - " << interface.hardwareAddress();
                    _MAC = interface.hardwareAddress();
                    _IP = socket.localAddress().toString();
                }
            }
        }
    } else {
        qInfo() << socket.errorString();
    }

    socket.destroyed();

2016년 5월 20일 금요일

[EtC] tomcat server.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
      disableUploadTimeout="true"
               enableLookups="false"
               URIEncoding="UTF-8" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="freecatz.pe.kr" jvmRoute="tomcat1">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->


        <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                 channelSendOptions="8">

          <Manager className="org.apache.catalina.ha.session.DeltaManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"/>

          <Channel className="org.apache.catalina.tribes.group.GroupChannel">
            <Membership className="org.apache.catalina.tribes.membership.McastService"
                        address="228.0.0.4"
                        port="45564"
                        frequency="500"
                        dropTime="3000"/>
            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                      address="auto"
                      port="4000"
                      autoBind="100"
                      selectorTimeout="5000"
                      maxThreads="6"/>

            <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
            </Sender>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
          </Channel>

          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
                 filter=""/>
          <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

          <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
                    tempDir="/tmp/war-temp/"
                    deployDir="/tmp/war-deploy/"
                    watchDir="/tmp/war-listen/"
                    watchEnabled="false"/>

          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
        </Cluster>


      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="freecatz.pe.kr"
       appBase="webapps"
            unpackWARs="false"
            autoDeploy="false">
   <Alias>freecatz.pe.kr</Alias>
   <Context className="org.apache.catalina.core.StandardContext"
                     reloadable="true"
                     allowLinking="true"
                     cachingAllowed="true"
                     charsetMapperClass="org.apache.catalina.util.CharsetMapper"
                     cookies="true"
                     crossContext="true"
                     displayName="API Service"
                     docBase="/home/tomcat/webapps/freecatz.pe.kr/ROOT"
                     path=""
                     privileged="false"
                     swallowOutput="false"
                     useNaming="true"
                     workDir="/home/tomcat/server/apache-tomcat-8.0.43_1/work/freecatz.pe.kr"
                     wrapperClass="org.apache.catalina.core.StandardWrapper">
            </Context>

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>