2015年3月7日土曜日

Javaの設定を行う

現在インストールされているJDKを確認する(私の環境ではJDK6、7、8がインストール済み)。
$ /usr/libexec/java_home -V

JDK7をJAVA_HOMEとして設定する。
$ vim ~/.bashrc
$ less ~/.bashrc
(関連箇所を抜粋)
export JAVA_HOME=`/usr/libexec/java_home -v 1.7`

必要に応じてJavaVMのオプションを設定する。例えば下記の通り。
$ vim ~/.bashrc
$ less ~/.bashrc
(関連箇所を抜粋)
export JAVA_OPTS="-Dfile.encoding=UTF-8"
# または
#export JAVA_OPTS="$JAVA_OPTS -Dfile.encoding=UTF-8"

最後に~/.bashrcを再読み込み
$ source ~/.bashrc

2014年12月30日火曜日

プロキシ環境下でApache Subversionを使う

設定ファイル


~/.subversion/servers


グループ毎に個別指定する場合


アクセスするリポジトリが固定している場合はgroupsセクションで設定するのが望ましい
$ cat ~/.subversion/servers
(関連箇所のみ抜粋)
[groups]
targetgroup1 = somerepository.example.org

[targetgroup1]
http-proxy-host = proxy.example.com
http-proxy-port = 8080
http-proxy-username = foo.bar@example.com
http-proxy-password = hogepass


まとめて指定する場合


外部リポジトリにしかアクセスしない場合等はglobalセクションで一括設定すると楽
$ cat ~/.subversion/servers
(関連箇所のみ抜粋)
[global]
http-proxy-exceptions = *.internal.example.com, *.internal.example.net
http-proxy-host = proxy.example.com
http-proxy-port = 8080
http-proxy-username = foo.bar@example.com
http-proxy-password = hogepass

2014年11月26日水曜日

NSURLSessionを使ってHTTPリクエストする(Swift)

SwiftでNSURLSessionDataTaskを使って、HTTP-GET、JSONデータをHTTP-POSTする。

環境
  • Xcode 6.1
  • iOS 8.1
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    // HTTP-GET
    @IBAction func getAsync(sender: AnyObject) {
        
        // create the url-request
        let urlString = "http://httpbin.org/get"
        var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
        
        // set the method(HTTP-GET)
        request.HTTPMethod = "GET"
        
        // use NSURLSessionDataTask
        var task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { data, response, error in
            if (error == nil) {
                var result = NSString(data: data, encoding: NSUTF8StringEncoding)!
                println(result)
            } else {
                println(error)
            }
        })
        task.resume()
        
    }


    // HTTP-POST
    @IBAction func postAsync(sender: AnyObject) {
        
        // create the url-request
        let urlString = "http://httpbin.org/post"
        var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
        
        // set the method(HTTP-POST)
        request.HTTPMethod = "POST"
        // set the header(s)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
        // set the request-body(JSON)
        var params: [String: AnyObject] = [
            "foo": "bar",
            "baz": [
                "a": 1,
                "b": 20,
                "c": 300
            ]
        ]
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil)
        
        // use NSURLSessionDataTask
        var task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
            if (error == nil) {
                var result = NSString(data: data, encoding: NSUTF8StringEncoding)!
                println(result)
            } else {
                println(error)
            }
        })
        task.resume()
        
    }
        
}

2014年10月5日日曜日

即時関数を使ってグローバル汚染を最小にする


関数単位でスコープが決まる性質を利用する。

  • 即時関数を使ってローカルスコープ化することにより、グローバル汚染を防ぐ。
  • strictモードでは関数内のthisがundefinedになるため、callメソッドを使用する。
  • 関数前の「;」はファイル連結時に不具合が出ないようにするための予防策。
<!DOCTYPE html>
<html>
<head lang="ja">
  <meta charset="UTF-8">
  <title>即時関数によるスコープ閉じ込め</title>
</head>
<body>
  <ul>
    <li id="first">1行目</li>
    <li id="second">2行目</li>
    <li id="third">3行目</li>
  <ul>
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
  <script src="./js/app.js"></script>
</body>
</html>
;(function ($) {
  'use strict';

  alert('outside ready method: this = ' + this);
  alert('outside ready method: $ = ' + $);
  alert('outside ready method: _.VERSION = ' + _.VERSION);

  $(function () {
    alert('inside ready method: this = ' + this);
    alert('inside ready method: $ = ' + $);
    alert('inside ready method: _.VERSION = ' + _.VERSION);
    $('#third').css('color', 'red');
  });

  alert('this = ' + this);
  alert('$ = ' + $);
  alert(_.VERSION);

}).call(this, jQuery);
//}.bind(this)(jQuery));

[参考URL]
知ってて当然?初級者のためのJavaScriptで使う即時関数(function(){...})()の全て - 三等兵
callで関数を即時実行すると何が嬉しいのか(と、ちょっとおまけ) - ただぱそこんしてるだけ
便利なjavascriptテクニック集 - Thujikun blog
"use strict" - blog.niw.at

2014年8月16日土曜日

NSURLSessionを使ってHTTPリクエストする

NSURLSessionDataTaskを使って、HTTP-GET、JSONデータをHTTP-POSTする。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *requestUrl;
@property (weak, nonatomic) IBOutlet UITextField *requestBody;
@property (weak, nonatomic) IBOutlet UITextView *requestResult;
- (IBAction)getAsync:(id)sender;
- (IBAction)postAsync:(id)sender;

@end
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// HTTP-GET
- (IBAction)getAsync:(id)sender {
    NSLog(@"%s", __func__);
    
    // create the url-request
    NSURL *url = [NSURL URLWithString:self.requestUrl.text];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // set the method(HTTP-GET)
    [request setHTTPMethod:@"GET"];
    
    // use NSURLSessionDataTask
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (!error) {
            NSHTTPURLResponse *httpRes = (NSHTTPURLResponse *)response;
            NSLog(@"statusCode: %ld", (long)httpRes.statusCode);
            NSLog(@"allHeaderFields: %@", httpRes.allHeaderFields);
            
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"result: %@", result);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.requestResult.text = result;
            });
            
        } else {
            NSLog(@"error: %@", [error localizedDescription]);
        }
        
    }];
    
    [task resume];
}

// HTTP-POST
- (IBAction)postAsync:(id)sender {
    NSLog(@"%s", __func__);
    
    // create the url-request
    NSURL *url = [NSURL URLWithString:self.requestUrl.text];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // set the headers(s)
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // set the method(HTTP-POST)
    [request setHTTPMethod:@"POST"];

    // set the request-body
    NSString *reqBody = self.requestBody.text;
    NSLog(@"%@", reqBody);

    [request setHTTPBody:[reqBody dataUsingEncoding:NSUTF8StringEncoding]];
    
    // use NSURLSessionDataTask
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (!error) {
            NSHTTPURLResponse *httpRes = (NSHTTPURLResponse *)response;
            NSLog(@"statusCode: %ld", (long)httpRes.statusCode);
            NSLog(@"allHeaderFields: %@", httpRes.allHeaderFields);
            
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"result: %@", result);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.requestResult.text = result;
            });
            
        } else {
            NSLog(@"error: %@", [error localizedDescription]);
        }
        
    }];
    
    [task resume];
}

@end

2014年7月25日金曜日

WICの機能や無線LANの状態を確認する

Raspberry Piに無線LAN USBアダプタ(WLI-UC-GNM)を接続

$ lsusb
(関連箇所のみ抜粋)
Bus 001 Device 004: ID 0411:01a2 BUFFALO INC. (formerly MelCo., Inc.) WLI-UC-GNM Wireless LAN Adapter [Ralink RT8070]

$ lsmod
Module                  Size  Used by
(関連箇所のみ抜粋)
rt2800usb              17279  0 
rt2800lib              80619  1 rt2800usb
rt2x00usb              11669  1 rt2800usb
rt2x00lib              44799  3 rt2x00usb,rt2800lib,rt2800usb
mac80211              329373  3 rt2x00lib,rt2x00usb,rt2800lib
cfg80211              211002  2 mac80211,rt2x00lib
rfkill                 19567  2 cfg80211
-->
cfg80211、mac80211の記述からnl80211でカバーできそう

iwのインストール
$ sudo apt-get install iw

サポート機能の確認
$ iw list
Wiphy phy0
(関連箇所のみ抜粋)
 Supported Ciphers:
  * WEP40 (00-0f-ac:1)
  * WEP104 (00-0f-ac:5)
  * TKIP (00-0f-ac:2)
  * CCMP (00-0f-ac:4)
 Available Antennas: TX 0 RX 0
 Supported interface modes:
   * IBSS
   * managed
   * AP
   * AP/VLAN
   * WDS
   * monitor
   * mesh point
 software interface modes (can always be added):
   * AP/VLAN
   * monitor
 valid interface combinations:
   * #{ AP, mesh point } <= 8,
     total <= 8, #channels <= 1
-->
IBSS: アドホック
managed: クライアント
AP: アクセスポイント
VLAN: 無線VLAN
monitor: 無線LANネットワーク検出

無線LANのスキャン
$ sudo iw dev wlan0 scan

iwconfigはまだ使えるようだが、これはそのうちdeprecatedされるかもしれない
$ sudo ifdown wlan0
$ iwconfig
(関連箇所のみ抜粋)
wlan0     IEEE 802.11bgn  ESSID:off/any  
          Mode:Managed  Access Point: Not-Associated   Tx-Power=20 dBm   
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Power Management:on

$ sudo ifup wlan0
$ iwconfig
(関連箇所のみ抜粋)
wlan0     IEEE 802.11bgn  ESSID:"RaspiSSID"  
          Mode:Managed  Frequency:2.462 GHz  Access Point: 01:23:45:67:89:AB   
          Bit Rate=6.5 Mb/s   Tx-Power=20 dBm   
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Power Management:on
          Link Quality=70/70  Signal level=-39 dBm  
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:0   Missed beacon:0


[参考URL]
cfg80211 - Linux Wireless
mac80211 - Linux Wireless
nl80211 - Linux Wireless
hostapd を使用した簡単な方法で WiFi に強力な暗号化を実装する

2014年7月21日月曜日

Raspberry Piのネットワークを設定する

有線LAN


有線LAN用固定IPの設定
$ sudo cp /etc/network/interfaces{,.orig}
$ sudo vim /etc/network/interfaces

/etc/network/interfaces
auto lo
iface lo inet loopback

iface eth0 inet static
address 192.168.21.41
netmask 255.255.255.0
gateway 192.168.21.1

該当IFの無効・有効化
$ sudo ifdown eth0 && sudo ifup eth0


無線LAN


無線LANクライアントの設定
$ sudo cp /etc/wpa_supplicant/wpa_supplicant.conf{,.orig}
$ wpa_passphrase "RaspiSSID" "RaspiSSIDPW" | sudo tee -a /etc/wpa_supplicant/wpa_supplicant.conf
network={
        ssid="RaspiSSID"
        #psk="RaspiSSIDPW"
        psk=d721085129ab22a68036c3c5cf7d28dab5f9b3de93a8866fe6626d59e811b7f7
}

$ sudo vim /etc/wpa_supplicant/wpa_supplicant.conf

/etc/wpa_supplicant/wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
        ssid="RaspiSSID"
        scan_ssid=0           # スキャン方法(0:パッシブ、1:アクティブ)
        priority=0            # 値が大きいほど優先度が高い(デフォルトは0)
        proto=RSN             # WPA2はRSNの別名
        key_mgmt=WPA-PSK
        pairwise=TKIP CCMP
        group=CCMP
        psk=d721085129ab22a68036c3c5cf7d28dab5f9b3de93a8866fe6626d59e811b7f7
        id_str="RaspiConf"    # 識別名
}

無線LAN用固定IPの設定
$ sudo cp /etc/network/interfaces{,.orig}
$ sudo vim /etc/network/interfaces

/etc/network/interfaces
auto lo
iface lo inet loopback

iface eth0 inet static
address 192.168.21.41
netmask 255.255.255.0
gateway 192.168.21.1

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

iface RaspiConf inet static
address 192.168.21.42
netmask 255.255.255.0
gateway 192.168.21.1

該当IFの無効・有効化
$ sudo ifdown wlan0 && sudo ifup wlan0


リゾルバの設定


$ sudo vim /etc/resolv.conf
$ cat /etc/resolv.conf
nameserver 192.168.21.1
nameserver 192.168.22.1
search example.com example.jp


ホスト名の設定


$ sudo vim /etc/hostname
$ cat /etc/hostname
raspi

$ sudo vim /etc/hosts
$ cat /etc/hosts
127.0.0.1      localhost.localdomain   localhost
127.0.1.1      raspi.example.com       raspi
192.168.11.41  raspi.example.com       raspi
192.168.11.42  raspi.example.com       raspi


再起動


$ sudo shutdown -r now


[参考URL]
How-To: WiFi roaming with wpa-supplicant | Debuntu
wpa_supplicant.conf(5)
Gentoo Linux ドキュメント -- 無線ネットワーク