Monthly Archives: 2月 2015

「android開発」android端末の無線LAN WiFIのIPアドレスを取得するサンプルコード

Javaコード:
@SuppressWarnings(“deprecation”)
public static String IPAnalysis(Context context) {
//wifiを取得
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
//wifi無効/有効の判断
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int mAddress = wifiInfo.getIpAddress();
Log.d(“IPAddress—> “, Formatter.formatIpAddress(mAddress));
return Formatter.formatIpAddress(mAddress);
}

「Android開発」アプリのバージョン番号を取得するサンプルコード

Javaコード

public static String getVersionNumber(Context context) {
String version = null;
//PackageManagerのインスタンスを取得
PackageManager packageManager = context.getPackageManager();
// getPackageName()
PackageInfo packageInfo;
try {
packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
version = packageInfo.versionName;
} catch (Exception e) {
return “番号 : “;
}
return “番号: ” + version;
}

「php開発」phpでメッセージキューの使い方

1.サーバー側
$exchannel = \Tang\Amqp\AmqpService::getService()->get()->getExchannel(‘demo_startnews24’);
$exchannel->publish(‘message’);
//messageを発送

2.クライアント側
$exchannel = \Tang\Amqp\AmqpService::getService()->get()->getExchannel(‘demo_startnews24’);
$queue = $exchannel->getQueue(‘node1’);//node1キューを取得
$queue->consume(function(\Tang\Amqp\Message $message)
{
$body = $message->body();
echo $body;//輸出
},true);

「PHP学習」php開発でヘッダ(header)の基礎知識のまとめ

PHPコード:
<?php
header(‘HTTP/1.1 200 OK’);
header(‘HTTP/1.1 404 Not Found’);
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘Location: http://www.arkgame.com/’);
header(‘Refresh: 10; url=http://www.arkgame.com/’);
header(‘X-Powered-By: PHP/6.0.0’);
header(‘Content-language: en’);
header(‘Content-Length: 1234’);
header(‘Last-Modified: ‘.gmdate(‘D, d M Y H:i:s’, $time).’ GMT’);
header(‘HTTP/1.1 304 Not Modified’);

###content type###
header(‘Content-Type: text/html; charset=utf-8’);
header(‘Content-Type: text/plain’);
header(‘Content-Type: image/jpeg’);
header(‘Content-Type: application/zip’); // ZIP
header(‘Content-Type: application/pdf’); // PD
header(‘Content-Type: audio/mpeg’);
header(‘Content-type: text/css’);
header(‘Content-type: text/javascript’);
header(‘Content-type: application/json’); //json
header(‘Content-type: application/pdf’); //pdf
header(‘Content-type: text/xml’); //xml
header(‘Content-Type: application/x-shockw**e-flash’); //Flash

######

###ダウンロードファイル###
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename=”startnews24_dl.zip”‘);
header(‘Content-Transfer-Encoding: binary’);
readfile(‘test.zip’);
######

###ドキュメント禁止###
header(‘Cache-Control: no-cache, no-store, max-age=0, must-revalidate’);
header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’);
######

###ログインダイアログ###
header(‘HTTP/1.1 401 Unauthorized’);
header(‘WWW-Authenticate: Basic realm=”Top Secret”‘);
######

###xlsファイルのダウンロード###
header(‘Content-Disposition: attachment; filename=it_startnews24.xlsx’);
header(‘Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’);
header(‘Content-Length: ‘.filesize(‘./startnews24_tt.xls’));
header(‘Content-Transfer-Encoding: binary’);
header(‘Cache-Control: must-revalidate’);
header(‘Pragma: public’);
readfile(‘./startnews24_tt.xls’);
######

?>

NodeJSにHTTPを利用してDomain Socketをリスナーする

1.参考コード
var http = require(‘http’);
http.createServer(function (req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
res.end(‘welcome to arkgame.com\n’);
}).listen(‘/tmp/node_http.sock’);
console.log(‘Server running at /tmp/node_http.sock’);

2.テスト方法
telnet /tmp/node_http.sock
Trying /tmp/node_http.sock…
Connected to (null).
Escape character is ‘^]’.
GET / HTTP/1.1
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Mon, 26 Jan 2014 04:21:09 GMT
Connection: keep-alive
Transfer-Encoding: chunked
c
welcome to arkgame.com
0

3. NodeJSのHTTP Clientを利用してアクセス
var http = require(‘http’);
var options = {
socketPath: ‘/tmp/node_http.sock’,
method: ‘GET’,
path: ‘/’
};
var req = http.request(options, function(res){
console.log(‘STATUS: ‘ + res.statusCode);
console.log(‘HEADERS: ‘ + JSON.stringify(res.headers));
res.on(‘data’, function (chunk){
console.log(chunk.toString());
});
});
req.end();
4.http_client.jsのソースコードを実行
node http_client.js
STATUS: 200
HEADERS: {“content-type”:”text/plain”,”date”:”Mon, 26 Jan 2014 04:25:49 GMT”,”connection”:”close”,”transfer-encoding”:”chunked”}
welcome to arkgame.com

NodeJSのTCP、HTTPでDomain Socketを監視する方法

TCP側参考コード:
var net = require(‘net’);
net.createServer(function (socket) {
socket.on(‘data’, function (data) {
socket.write(‘received: ‘ + data);
});
}).listen(‘/tmp/node_tcp.sock’);

「’/tmp/node_tcp.sock’」に接続
参考コード:
telnet /tmp/node_tcp.sock
Trying /tmp/node_tcp.sock…
Connected to (null).
Escape character is ‘^]’.
welcome to arkgame.com
received: welcome to arkgame.com

Python開発でInotifyを利用してファイルを監視するサンプルコード

Pythonコード:
# -*- coding:utf-8 -*-

import os
import pyinotify
from functions import *

WATCH_PATH = ” #監視ディレクトリ

if not WATCH_PATH:
wlog(‘Error’,”The WATCH_PATH setting MUST be set.”)
sys.exit()
else:
if os.path.exists(WATCH_PATH):
wlog(‘Watch status’,’Found watch path: path=%s.’ % (WATCH_PATH))
else:
wlog(‘Error’,’The watch path NOT exists, watching stop now: path=%s.’ % (WATCH_PATH))
sys.exit()

class OnIOHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
wlog(‘Action’,”create file: %s ” % os.path.join(event.path,event.name))

def process_IN_DELETE(self, event):
wlog(‘Action’,”delete file: %s ” % os.path.join(event.path,event.name))

def process_IN_MODIFY(self, event):
wlog(‘Action’,”modify file: %s ” % os.path.join(event.path,event.name))

def auto_compile(path = ‘.’):
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY
notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler())
notifier.start()
wm.add_watch(path, mask,rec = True,auto_add = True)
wlog(‘Start Watch’,’Start monitoring %s’ % path)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break

if __name__ == “__main__”:
auto_compile(WATCH_PATH)

参考URL
https://github.com/seb-m/pyinotify

「shell学習」qmailの大量キューを削除するサンプルコード

参考コード:
#/bin/bash
#ファイルパス
quepath=/var/spool/mqueue
#ファイル数
filenum=ls $quepath|wc -l
#ファイルを削除
if [ $filenum -ge 100 ];then
find $quepath -type f -name ‘*’ -print0 | xargs -0 rm
rm -rf $quepath/*
fi

「PHP学習」json_decodeを利用するサンプルコード

phpコード
<?php
$json = ‘{“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}’;
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
結果:
object(stdClass)#1 (5) {
[“a”] => int(1)
[“b”] => int(2)
[“c”] => int(3)
[“d”] => int(4)
[“e”] => int(5)
}

array(5) {
[“a”] => int(1)
[“b”] => int(2)
[“c”] => int(3)
[“d”] => int(4)
[“e”] => int(5)
}

「php学習」Content-typeのMIMEタイプ判定配列の定義

PHPコード:
<?php
$mimetypes = array(
‘ez’ => ‘application/andrew-inset’,
‘hqx’ => ‘application/mac-binhex40’,
‘cpt’ => ‘application/mac-compactpro’,
‘doc’ => ‘application/msword’,
‘bin’ => ‘application/octet-stream’,
‘dms’ => ‘application/octet-stream’,
‘lha’ => ‘application/octet-stream’,
‘lzh’ => ‘application/octet-stream’,
‘exe’ => ‘application/octet-stream’,
‘class’ => ‘application/octet-stream’,
‘so’ => ‘application/octet-stream’,
‘dll’ => ‘application/octet-stream’,
‘oda’ => ‘application/oda’,
‘pdf’ => ‘application/pdf’,
‘ai’ => ‘application/postscript’,
‘eps’ => ‘application/postscript’,
‘ps’ => ‘application/postscript’,
‘smi’ => ‘application/smil’,
‘smil’ => ‘application/smil’,
‘mif’ => ‘application/vnd.mif’,
‘xls’ => ‘application/vnd.ms-excel’,
‘ppt’ => ‘application/vnd.ms-powerpoint’,
‘wbxml’ => ‘application/vnd.wap.wbxml’,
‘wmlc’ => ‘application/vnd.wap.wmlc’,
‘wmlsc’ => ‘application/vnd.wap.wmlscriptc’,
‘bcpio’ => ‘application/x-bcpio’,
‘vcd’ => ‘application/x-cdlink’,
‘pgn’ => ‘application/x-chess-pgn’,
‘cpio’ => ‘application/x-cpio’,
‘csh’ => ‘application/x-csh’,
‘dcr’ => ‘application/x-director’,
‘dir’ => ‘application/x-director’,
‘dxr’ => ‘application/x-director’,
‘dvi’ => ‘application/x-dvi’,
‘spl’ => ‘application/x-futuresplash’,
‘gtar’ => ‘application/x-gtar’,
‘hdf’ => ‘application/x-hdf’,
‘js’ => ‘application/x-javascript’,
‘skp’ => ‘application/x-koan’,
‘skd’ => ‘application/x-koan’,
‘skt’ => ‘application/x-koan’,
‘skm’ => ‘application/x-koan’,
‘latex’ => ‘application/x-latex’,
‘nc’ => ‘application/x-netcdf’,
‘cdf’ => ‘application/x-netcdf’,
‘sh’ => ‘application/x-sh’,
‘shar’ => ‘application/x-shar’,
‘swf’ => ‘application/x-shockwave-flash’,
‘sit’ => ‘application/x-stuffit’,
‘sv4cpio’ => ‘application/x-sv4cpio’,
‘sv4crc’ => ‘application/x-sv4crc’,
‘tar’ => ‘application/x-tar’,
‘tcl’ => ‘application/x-tcl’,
‘tex’ => ‘application/x-tex’,
‘texinfo’ => ‘application/x-texinfo’,
‘texi’ => ‘application/x-texinfo’,
‘t’ => ‘application/x-troff’,
‘tr’ => ‘application/x-troff’,
‘roff’ => ‘application/x-troff’,
‘man’ => ‘application/x-troff-man’,
‘me’ => ‘application/x-troff-me’,
‘ms’ => ‘application/x-troff-ms’,
‘ustar’ => ‘application/x-ustar’,
‘src’ => ‘application/x-wais-source’,
‘xhtml’ => ‘application/xhtml+xml’,
‘xht’ => ‘application/xhtml+xml’,
‘zip’ => ‘application/zip’,
‘au’ => ‘audio/basic’,
‘snd’ => ‘audio/basic’,
‘mid’ => ‘audio/midi’,
‘midi’ => ‘audio/midi’,
‘kar’ => ‘audio/midi’,
‘mpga’ => ‘audio/mpeg’,
‘mp2′ => ‘audio/mpeg’,
‘mp3′ => ‘audio/mpeg’,
‘aif’ => ‘audio/x-aiff’,
‘aiff’ => ‘audio/x-aiff’,
‘aifc’ => ‘audio/x-aiff’,
‘m3u’ => ‘audio/x-mpegurl’,
‘ram’ => ‘audio/x-pn-realaudio’,
‘rm’ => ‘audio/x-pn-realaudio’,
‘rpm’ => ‘audio/x-pn-realaudio-plugin’,
‘ra’ => ‘audio/x-realaudio’,
‘wav’ => ‘audio/x-wav’,
‘pdb’ => ‘chemical/x-pdb’,
‘xyz’ => ‘chemical/x-xyz’,
‘bmp’ => ‘image/bmp’,
‘gif’ => ‘image/gif’,
‘ief’ => ‘image/ief’,
‘jpeg’ => ‘image/jpeg’,
‘jpg’ => ‘image/jpeg’,
‘jpe’ => ‘image/jpeg’,
‘png’ => ‘image/png’,
‘tiff’ => ‘image/tiff’,
‘tif’ => ‘image/tiff’,
‘djvu’ => ‘image/vnd.djvu’,
‘djv’ => ‘image/vnd.djvu’,
‘wbmp’ => ‘image/vnd.wap.wbmp’,
‘ras’ => ‘image/x-cmu-raster’,
‘pnm’ => ‘image/x-portable-anymap’,
‘pbm’ => ‘image/x-portable-bitmap’,
‘pgm’ => ‘image/x-portable-graymap’,
‘ppm’ => ‘image/x-portable-pixmap’,
‘rgb’ => ‘image/x-rgb’,
‘xbm’ => ‘image/x-xbitmap’,
‘xpm’ => ‘image/x-xpixmap’,
‘xwd’ => ‘image/x-xwindowdump’,
‘igs’ => ‘model/iges’,
‘iges’ => ‘model/iges’,
‘msh’ => ‘model/mesh’,
‘mesh’ => ‘model/mesh’,
‘silo’ => ‘model/mesh’,
‘wrl’ => ‘model/vrml’,
‘vrml’ => ‘model/vrml’,
‘css’ => ‘text/css’,
‘html’ => ‘text/html’,
‘htm’ => ‘text/html’,
‘asc’ => ‘text/plain’,
‘txt’ => ‘text/plain’,
‘rtx’ => ‘text/richtext’,
‘rtf’ => ‘text/rtf’,
‘sgml’ => ‘text/sgml’,
‘sgm’ => ‘text/sgml’,
‘tsv’ => ‘text/tab-separated-values’,
‘wml’ => ‘text/vnd.wap.wml’,
‘wmls’ => ‘text/vnd.wap.wmlscript’,
‘etx’ => ‘text/x-setext’,
‘xsl’ => ‘text/xml’,
‘xml’ => ‘text/xml’,
‘mpeg’ => ‘video/mpeg’,
‘mpg’ => ‘video/mpeg’,
‘mpe’ => ‘video/mpeg’,
‘qt’ => ‘video/quicktime’,
‘mov’ => ‘video/quicktime’,
‘mxu’ => ‘video/vnd.mpegurl’,
‘avi’ => ‘video/x-msvideo’,
‘movie’ => ‘video/x-sgi-movie’,
‘ice’ => ‘x-conference/x-cooltalk’,
);
?>