2018년 1월 16일 화요일

[GoLaNg] 특정 디렉토리 목록 출력

import (
"fmt"
"io/ioutil"
"os"
"strconv"
)

/* 특정 디렉토리의 목록을 출력 한다. */
func DirectoryList(dir string) {
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Println(err)
}

for _, f := range files {
if f.IsDir() {
fmt.Println(f.Name() + "\t" + "디렉토리")
} else {
fmt.Println(f.Name() + "\t" + "파일" + "\t" + strconv.FormatInt(f.Size(), 10) + "Byte")
}
}
}

[GoLaNg] xml parse

1. XML File 내용
<?xml version="1.0" encoding="UTF-8" ?>
<properties>
    <propertie key="HelloMsg">
        <value><![CDATA[Hello World!!]]></value>
    </propertie>
    <propertie key="TestMsg">
        <value><![CDATA[Test!!]]></value>
    </propertie>
</properties>


2. 프로그램
import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "os"

)

/* XML 을 파싱 하기 위한 구조체 */
type Properties struct {
Propertie []Propertie `xml:"propertie"`
}

/* XML 을 파싱 하기 위한 구조체 */
type Propertie struct {
Key   string `xml:"key,attr"`
Value string `xml:"value"`
}

/* XML 파일로 부터 프로퍼티를 읽어 반환 */
func GetPropFromXML(key string) string {
    fp, err := os.Open("freecatz.pe.kr/Conf/properties.xml")
    if err != nil {
        panic(err)
    }
    defer fp.Close()

    // xml 파일 읽기
    data, err := ioutil.ReadAll(fp)

    // xml 디코딩
    var properties Properties
    xmlerr := xml.Unmarshal(data, &properties)
    if xmlerr != nil {
        panic(xmlerr)
    }

    var result string
    for i := 0; i < len(properties.Propertie); i++ {
        if properties.Propertie[i].Key == key {
            result = properties.Propertie[i].Value
        }
        //        fmt.Println("key: " + properties.Propertie[i].Key + "\t -> " + properties.Propertie[i].Value)
    }
    return result
}

[GoLaNg] 파일이 있는지 확인

/* 파일이 있는지 확인 한다. */
func FileExist(filePath string) bool {
    var result bool = false
    if _, err := os.Stat(filePath); os.IsNotExist(err) {
        fmt.Println("파일 없음")
        result = false
    } else {
        fmt.Println("파일 있음")
        result = true
    }
    return result

}

2018년 1월 12일 금요일

[EtC] spring-security login - jquery ajax 405 error


1. 기존 Spring Boot 프로젝트에 html5 부터 지원 되는 cache 기능을 적용
<html lang="ko" manifest="/default.manifest" xmlns:th="http://www.thymeleaf.org">

2. jquery 의 ajax 를 이용하여 spring-security 를 통해 로그인 시도

3. 405 Method Not Allowed 발생

4. cache 대상 파일에서 jquery-1.12.4.min.js 를 제외 하거나,
   spring-security 로그인 페이지에서 manifest="/default.manifest" 를 제거
      : jquery-1.12.4.min.js 를 disk cache 에서 읽어 오는 경우 문제가 발생
       크롬의 시크릿 모드에서는 정상적으로 동작

5. 기존과 같이 정상적으로 spring-security 를 통해 로그인

6. CORS Filter 를 적용 하면 된다는 이야기가 있어 기존 CORS Filter 에 추가해 보았으나 안됨

7. 실력이 개차반이라 아직까지 왜 그런지 이유는 모름

8. 어찌 되었던 해결

2017년 11월 21일 화요일

[LiNuX] 시간 동기화


root@freecatz:~# rdate -s time.bora.net && hwclock --systohc

root@freecatz:~# vi /etc/crontab

# m : minute (0 - 59) 
# h : hour (0 - 23)
# dom : day of month (1 -     ) 
# mon : month (1 - 12) OR jan,feb,mar,apr ... 
# dow : day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# m h dom mon dow user  command
59 23   * * *   root    rdate -s time.bora.net && hwclock --systohc



2017년 11월 20일 월요일

[EtC] nodejs 로 Hello World

1. nodejs 다운로드 및 설치

   https://nodejs.org

  설치 과정 생략


2. 프로젝트 디렉토리 생성

   D:\>helloworld 생성

3. nodejs 실행 파일 생성

   D:\>helloworld 에 server.js 파을 생성 후 아래의 코드를 입력 한다.

   var express = require('express');
   var app = express();

   /*
get으로 / 요청시 아래의 내용들이 실행 된다.
   */
   app.get('/', function (req, res) {

      _date = new Date();
      console.log('Date :', _date.getFullYear() + '.' + _date.getMonth() + 1 + '.' + _date.getDate());
      console.log('uptime : ' + process.uptime());
      console.log('Client : ' + req.connection.remoteAddress);
      res.send('Hello World!');
   });

   /*
테스트용 코드로 /exit 주소를 호출 하는 경우 서버 프로그램을 종료 시킨다.
실제 운영시에는 사용하지 않는다.
   */
   /*
   app.get('/exit', function (req, res) {
      console.log('program self kill');
      process.exit();
   });
   */


   /*
9090 포트로 프로그램을 실행 후, 콘솔에 로그를 찍는다.
   */
   app.listen(9090, function () {

       /* public 디렉토리내 static 리소스들을 사용 하기 위한 코드 */
       app.use(express.static('public'));

       /* 서버가 시작 되고 1초 후 아래의 내용들을 찍어 준다. */
       setTimeout(function() {
       console.log('PID : ' + process.pid);
       console.log('node ver : ' + process.version);
       console.log('arch : ' + process.arch);
   console.log('platform : ' + process.platform);
   console.log('-----> nodejs server started');
       }, 1000);
   });


4. npm init


  D:\helloworld 에서 npm init 명령을 실행 한다.

  D:\helloworld> npm init
  This utility will walk you through creating a package.json file.
  It only covers the most common items, and tries to guess sensible defaults.

  See `npm help json` for definitive documentation on these fields
  and exactly what they do.

  Use `npm install <pkg>` afterwards to install a package and
  save it as a dependency in the package.json file.

  Press ^C at any time to quit.
  package name: (helloworld)          # 프로젝트 명칭. Mandatory.
  version: (1.0.0)                      # 프로젝트 버전. Optional.
  description: hello world              # 프로젝트 설명. Optional.
  entry point: (index.js)                # 프로젝트 진입점 파일명. Mandatory.
  test command:                      # 모름. Optional.
  git repository:                       # git repository 가 있는 경우. Optional.
  keywords:                          # 키워드. Optional.
  author:                             # 작성자. Optional.
  license: (ISC)                        # 라이센스. Optional.
  About to write to D:\helloworld\package.json:

  {
    "name": "helloworld",
    "version": "1.0.0",
    "description": "hello world",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC"
  }


  Is this ok? (yes)                # 최종 위의 내용으로 package.json 파일이 생성.

  D:\helloworld>


  npm init 명령 실행 후, D:\helloworld\package.json 파일이 생성 된다.


5. express 패키지 설치


    D:\>helloworld> npm install express --save

    위의 명령 실행 후 D:\helloworld 디렉토리 아래 node_module 디렉토리가 생성 되고
    그 아래 express 패키지와 의존성 패키지들이 설치 된다.

6. 실행

   D:\>npm server.js


7. 브라우저와 콘솔을 통한 확인


   http://localhost:9090

2017년 10월 30일 월요일

[EtC] Mac OS X 업데이트 후, svn 명령어에 문제 발생시.


Mac OS 는 업데이트 후 안드로이드 스튜디오에서 svn 명령어를 제대로 사용 하지 못하는 상황이 발생 하였다.

freecatz-MacBook-Pro:~ freecatz$ svn --version
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

freecatz-MacBook-Pro:~ freecatz$ xcode-select --install
xcode-select: note: install requested for command line developer tools


freecatz-MacBook-Pro:~ freecatz$ svn --version
svn, version 1.9.4 (r1740329)
   compiled Aug 13 2017, 18:20:28 on x86_64-apple-darwin16.1.0

Copyright (C) 2016 The Apache Software Foundation.
This software consists of contributions made by many people;
see the NOTICE file for more information.
Subversion is open source software, see http://subversion.apache.org/

The following repository access (RA) modules are available:

* ra_svn : Module for accessing a repository using the svn network protocol.
  - handles 'svn' scheme
* ra_local : Module for accessing a repository on local disk.
  - handles 'file' scheme
* ra_serf : Module for accessing a repository via WebDAV protocol using serf.
  - using serf 1.3.8 (compiled with 1.3.8)
  - handles 'http' scheme
  - handles 'https' scheme

The following authentication credential caches are available:

* Plaintext cache in /Users/freecatz/.subversion
* GPG-Agent
* Mac OS X Keychain

freecatz-MacBook-Pro:~ freecatz$






2017년 10월 26일 목요일

[AnDrOiD] MacOS 10.13 에서 HAXM 설치가 안되는 경우




Mac OS, IOS 는 업데이트 할 때 마다 뭐 하나씩 안되는게 있어서 찾아 봐야 한다.

이럴땐 윈도우와 리눅스가 참 편하다 싶다.

여튼, Mac OS X 10.13 에서 HAXM 가 설치 되지 않았다.

[여기] 를 보니 advancedFeatures.ini 를 찾아 수정 해주라고 한다.

freecatz-MacBook-Pro:~ freecatz$ find ./ -name advancedFeatures.ini
.//Library/Android/sdk/system-images/android-26/google_apis_playstore/x86/advancedFeatures.ini
.//Library/Android/sdk/system-images/android-19/default/x86/advancedFeatures.ini
.//Library/Android/sdk/emulator/lib/advancedFeatures.ini
freecatz-MacBook-Pro:~ freecatz$

찾은 advancedFeatures.ini 파일들을 열어 "HVF = on" 를 추가해 준다.

예)
GrallocSync = on
GLDMA = on
LogcatPipe = on
GLAsyncSwap = on
GLESDynamicVersion = on
PlayStoreImage = on
EncryptUserData = on
IntelPerformanceMonitoringUnit = on
HVF = on

2017년 10월 11일 수요일

[AnDrOiD] apk file name config


build.gradle 파일을 열어 archivesBaseName 를 추가 한다.


... 중략 ...

android {
     compileSdkVersion 26
     buildToolsVersion "26.0.2"
     defaultConfig {
          applicationId "freecatz.pe.kr.mytestapplication"
          minSdkVersion 19
          targetSdkVersion 26
          versionCode 1
          versionName "1.0"
          testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
          archivesBaseName = "freecatz.pe.kr_v" + versionName
     }
     buildTypes {
          release {
               minifyEnabled true
               proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
          }

          debug {
               minifyEnabled false
          }
     }
}

... 중략 ...

[AnDrOiD] gradle.properties

org.gradle.jvmargs=-Xms512m -Xmx1536m
org.gradle.parallel=true
org.gradle.daemon=true