ラベル [2012]サーバアーキテクチャ の投稿を表示しています。 すべての投稿を表示
ラベル [2012]サーバアーキテクチャ の投稿を表示しています。 すべての投稿を表示

2012年10月25日木曜日

WEBアプリケーションサーバの構築(6) crontab

1.Shell Scriptエラー処理 前回のツールを動作させる前提として「img」ディレクトリが必要だが,もし存在しないとうまく動作しない.
そこで,「img」ディレクトリの存在有無をチェックし,もし存在しない場合は,ディレクトリを作成するようにツールを編集する.
get_image2.sh
#!/bin/bash

for user in `ls /home`
do
    id $user > /dev/null 2>&1
    if [ $? -eq 0 ] && [ ! -d /home/$user/public_html ]; then
        mkdir -p /home/$user/public_html
        chown $user. /home/$user/public_html
        chmod 711 /home/$user
        echo $user
    fi
done


2.crontabの利用 逆方向も試してみよう
WEBから受け取った値...天気予報の予報値や,特定サイトの値...を,
シェルスクリプトでDBサーバに自動登録.
さらにcrontabを使って,定期的に自動実行.
登録された値はHTMLファイルで閲覧可能なものを作成.
#goo天気の場合
#元ファイル取得
# wget http://weather.goo.ne.jp/area/4610.rdf
#時刻
# grep lastBuildDate 4610.rdf | sed -e "s/\(.*\)<\/lastBuildDate>/\1/g"
#天気
# grep description 4610.rdf | sed -e "s/\(.*\)<\/description>/\1/g"

#Yahoo天気の場合
#元ファイル取得
 wget http://rss.weather.yahoo.co.jp/rss/days/4410.xml
#時刻
 grep lastBuildDate 4410.xml | sed -e "s/\(.*\)<\/lastBuildDate>/\1/g"
#現在の天気と気温を抽出
 grep -n description 4410.xml | grep ^13 | sed -e "s/\(.*\)<\/description>/\1/" | sed "s/\s//g" | sed "s/^.*-//g" | sed "s/\/.*$//g"

1.SQL文を用意
vi temp.sql
 insert into temp (temp) values (10);

2.1で作成したファイルを用いてMySQLへ値流し込み
mysql -u root -s test < temp.sql

3.temp.sqlの値を自動的に更新するシェルスクリプトを作成
temp.sql
 #!/bin/sh
 echo "insert into temp (temp) values (10);" > temp.sql
 /usr/bin/mysql -u root -s test < temp.sql
 exit 0

chmod u+x temp.sql
./temp.sql

4.temp.sqlの中身を自動的に変更する.
temp.sql
 !/bin/sh
 wget http://rss.weather.yahoo.co.jp/rss/days/4410.xml
 str_temp=`grep -n description 4410.xml | grep ^13 | sed -e "s/\(.*\)<\/description>/\1/" | sed "s/\s//g" | sed "s/^.*-//g" | sed "s/\/.*$//g"`
 echo 'insert into temp (temp) values ("'$str_temp'");' > temp.sql
 /usr/bin/mysql -u root -s test < temp.sql
 rm 4410.xml
 exit 0

5.対象とする地域を複数とする.
ファイル名の下2桁目が可変 ---> 4410.xml/4420.xml/4430.xml ... ---> 44*0.xmlの*が1~9まで変化

2012年10月18日木曜日

WEBアプリケーションサーバの構築(5) Shell Script

1.Google画像検索APIの利用
http://ajax.googleapis.com/ajax/services/search/images?q=sato&v=1.0&rsz=1


2.Google画像検索API + shellの利用
curl -s 'http://ajax.googleapis.com/ajax/services/search/images?q=sato&v=1.0&rsz=1' | tr , \\n | grep "url" | sed -e 's/"url"://g' -e 's/"//g'
→Google画像検索の1番最初にマッチした画像のURLが表示される.

3.ツールの作成

get_image.sh
#!/bin/sh

target_list=`/usr/bin/mysql -u root -p[password] arts -e "select name from sa2012"`

for name in $target_list
do
        image_url=`curl -s 'http://ajax.googleapis.com/ajax/services/search/images?q='$name'&v=1.0&rsz=1' | tr , '\\n' | grep "url" | sed -e 's/"url"://g' -e 's/"//g'`

        echo $name" --> "$image_url

        curl -s -o img/$name.jpg $image_url
done

exit 0

※{password}は自自身のパスワードに置き換えること.


4.ツールを使用することで,DBに登録されたユーザの画像を,ユーザー名をファイル名として取得することが可能になったので,リストに画像も併せて表示する.
list6.html
<html>
<head>
    <meta http-equiv=content-type content="text/html; charset=UTF-8">
 <title>real-time search sample(AJAX)</title>
 
 <STYLE TYPE="text/css">
 <!--
 .table1 {
  width: 400px;
  border-collapse: collapse;
  border: 1px #708090 solid;
 }
 .table1 TD {
  border: 1px #708090 solid;
 }
 -->
 </STYLE> 
 
    <script type="text/javascript" src="xmlhttp.js"></script>
    <script type="text/javascript">
    <!--
    findText = findTextOld = "";

    function loadXmlFile(fName){
        httpObj = createXMLHttpRequest(displayData);
        if (httpObj){
            httpObj.open("GET",fName,true);
            httpObj.send(null);
        }
    }

    function displayData(){
        if ((httpObj.readyState == 4) && (httpObj.status == 200)){
            xmlData = httpObj.responseXML;
            $("result").innerHTML = parseXmlData(httpObj.responseText);
        }else{
            $("result").innerHTML = "Loading ...";
        }
    }

    function parseXmlData(xmlData){
        $("result").innerHTML = xmlData;
        idListTags = document.getElementsByTagName("id");
        numListTags = document.getElementsByTagName("num");
        nameListTags = document.getElementsByTagName("name");
        idLen = idListTags.length;

        resultText = "<table class='table1'><tr><th colspan=5>list</th></tr><tr><td><b>id</b></td><td><b>num</b></td><td><b>name</b></td><td><b>image</b></td></tr>";
        for(i=0; i<idLen; i++){
            id = idListTags[i].childNodes[0].nodeValue;
            num = numListTags[i].childNodes[0].nodeValue;
            name = nameListTags[i].childNodes[0].nodeValue;
            str = name.match(findText);
            if (str){
                resultText += "<tr><td>" + id + "</td><td><a href='http://10.2.5." + num + "' target='_blank'>" + num + "</a></td><td>" + name + "</td><td><img height=100 width=100 src='img/" + name + ".jpg'></td></tr>";
            }
        }
        resultText += "</table>";
        return resultText;
    }

    function inputCheck(){
        findText = document.ajaxForm.requestText.value;
        if (findText != findTextOld) {
            str_search = "./backend.php?search_key=" + findText
            loadXmlFile(str_search);
            findTextOld = findText;
        }else{
//            $("result").innerHTML = "Loading ...";
        }
        setTimeout(" inputCheck()",500); // 0.5秒毎
    }

    window.onload = inputCheck;
    // -->
    </script>
</head>
<body>
<form name="ajaxForm" onSubmit="return false">
<input type="text" value="a" name="requestText">
</form>
<div id="result"></div>
</body>
</html>

2012年10月11日木曜日

WEBアプリケーションサーバの構築(4) AJAX

フォームにAJAXを使った画面を作成.

xmlhttp.js
// HTTP通信用、共通関数
function createXMLHttpRequest(cbFunc){
 var XMLhttpObject = null;
 try{
  XMLhttpObject = new XMLHttpRequest();
 }catch(e){
  try{
   XMLhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
   try{
    XMLhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
   }catch(e){
    return null;
   }
  }
 }
 if (XMLhttpObject) XMLhttpObject.onreadystatechange = cbFunc;
 return XMLhttpObject;
}
 
// document.getElementById
function $(tagId){
 return document.getElementById(tagId);
}

backend.php
<?php
 $db_user  = "[user name]";
 $db_password = "[password]";
 $db_name = "[database name]";
 $db_host  = "localhost";

//create xml
    header('Content-type: text/xml; charset=utf-8');
    echo '<?xml version="1.0"?><sa>';

 $search_key = null;

 if(isset($_GET['search_key'])) {
  $search_key = $_GET['search_key'];

  $con = mysql_connect($db_host,$db_user,$db_password) or die("error!");
  mysql_select_db($db_name,$con) or die("DB is not exist");
  $strsql = "SET CHARACTER SET UTF8";
  mysql_query($strsql,$con);
  $strsql = "SELECT id, num, name FROM sa2012 WHERE name LIKE '%".$search_key."%';";
  $res = mysql_query($strsql,$con);

  while ($item = mysql_fetch_array($res)) {
   print "<list><id>".$item[0]."</id><num>".$item[1]."</num><name>".$item[2]."</name></list>";
  }
  mysql_close($con);
    }

    echo '</sa>'; 
?>

list4.html
<html>
<head>
    <meta http-equiv=content-type content="text/html; charset=UTF-8">
 <title>real-time search sample(AJAX)</title>
 
 <STYLE TYPE="text/css">
 <!--
 .table1 {
  width: 400px;
  border-collapse: collapse;
  border: 1px #708090 solid;
 }
 .table1 TD {
  border: 1px #708090 solid;
 }
 -->
 </STYLE> 
 
    <script type="text/javascript" src="xmlhttp.js"></script>
    <script type="text/javascript">
    <!--
    findText = findTextOld = "";

    function loadXmlFile(fName){
        httpObj = createXMLHttpRequest(displayData);
        if (httpObj){
            httpObj.open("GET",fName,true);
            httpObj.send(null);
        }
    }

    function displayData(){
        if ((httpObj.readyState == 4) && (httpObj.status == 200)){
            xmlData = httpObj.responseXML;
            $("result").innerHTML = parseXmlData(httpObj.responseText);
        }else{
            $("result").innerHTML = "Loading ...";
        }
    }

    function parseXmlData(xmlData){
        $("result").innerHTML = xmlData;
        idListTags = document.getElementsByTagName("id");
        numListTags = document.getElementsByTagName("num");
        nameListTags = document.getElementsByTagName("name");
        idLen = idListTags.length;

        resultText = "<table class='table1'><tr><th colspan=4>list</th></tr><tr><td><b>id</b></td><td><b>num</b></td><td><b>name</b></td></tr>";
        for(i=0; i<idLen; i++){
            id = idListTags[i].childNodes[0].nodeValue;
            num = numListTags[i].childNodes[0].nodeValue;
            name = nameListTags[i].childNodes[0].nodeValue;
            str = name.match(findText);
            if (str){
                resultText += "<tr><td>" + id + "</td><td><a href='http://10.2.5." + num + "' target='_blank'>" + num + "</a></td><td>" + name + "</td></tr>";
            }
        }
        resultText += "</table>";
        return resultText;
    }

    function inputCheck(){
        findText = document.ajaxForm.requestText.value;
        if (findText != findTextOld) {
            str_search = "./backend.php?search_key=" + findText
            loadXmlFile(str_search);
            findTextOld = findText;
        }else{
//            $("result").innerHTML = "Loading ...";
        }
        setTimeout(" inputCheck()",500); // 0.5秒毎
    }

    window.onload = inputCheck;
    // -->
    </script>
</head>
<body>
<form name="ajaxForm" onSubmit="return false">
<input type="text" value="s" name="requestText">
</form>
<div id="result"></div>
</body>
</html>

2012年10月4日木曜日

WEBアプリケーションサーバの構築(3) PHP

HTMLのフォームから値を受け取り,合致したidのみ表示する画面を作成.

list3_form.html
<html>
<head>
 <title>form</title>
</head>
<body>
 <form action="list3.php" method="get">
  id : <input type="text" name="id" />
  <input type="submit" />
 </form>
</body>
</html>

list3.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>list</title>
</head>
<body>
<?php
 $id = htmlspecialchars($_GET['id']);

 $db_user  = "[user name]";
 $db_password = "[password]";
 $db_name = "[database name]";
 $db_host  = "localhost";

 $db = mysql_connect($db_host,$db_user,$db_password);
 mysql_select_db($db_name,$db); 
 $str_sql = "select * from sa2012 where id = ".$id;
 $rs = mysql_query($str_sql,$db);
 $num = mysql_num_fields($rs);

 print("<table><tr><th colspan=3>list</th></tr>");
 echo("
 ");
 print("<tr>");
 for ($i=0;$i<$num;$i++){
  print("<td><b>".mysql_field_name($rs,$i)."</b></td>");
 }
 print("</tr>");
 while($row=mysql_fetch_array($rs)){
  echo("
 ");
  print("<tr>");
  for($j=0;$j<$num;$j++){
   print("<td>".$row[$j]."</td>");
  }
  print("</tr>");
 }

 print("</table>");

 mysql_free_result($rs);
 mysql_close($db);
?>
</body>
</html>

2012年9月27日木曜日

WEBアプリケーションサーバの構築(2) DBサーバ

1.php-mysqlモジュールをインストール
yum install php-mysql
service httpd stop
service httpd start
service mysqld stop
mysql_secure_installation
/etc/my.cnf
 [mysql] 
 default_character_set=utf8 

 [mysqld] 
 character_set-server=utf8 
 innodb_log_file_size=64M 
 innodb_buffer_pool_size=128M
service mysqld start


2.MySQLにデータベース,テーブル作成
DB Name : arts
Table Name : sa2012

$ mysql -u root -p
create database arts;

$ mysql -u root -p sa
create table sa2012 ( id integer NOT NULL AUTO_INCREMENT PRIMARY KEY, num char(4), host_name char(20), ip_address char(15) );

show tables;
select * from sa2012;

※テーブルの各値はMySQL Workbench等から流し込みます.

3.DBに接続し,中身を表示するPHPファイルを作成
list.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>list</title>
</head>
<body>
<?php
 $db_user  = "[user name]";
 $db_password = "[password]";
 $db_name = "[database name]";
 $db_host  = "localhost";

 $db = mysql_connect($db_host,$db_user,$db_password);
 mysql_select_db($db_name,$db); 
 $str_sql = "select * from sa2012";
 $rs = mysql_query($str_sql,$db);
 $num = mysql_num_fields($rs);

 print("<table><tr><th colspan=3>list</th></tr>");
 echo("
 ");
 print("<tr>");
 for ($i=0;$i<$num;$i++){
  print("<td><b>".mysql_field_name($rs,$i)."</b></td>");
 }
 print("</tr>");
 while($row=mysql_fetch_array($rs)){
  echo("
 ");
  print("<tr>");
  for($j=0;$j<$num;$j++){
   print("<td>".$row[$j]."</td>");
  }
  print("</tr>");
 }

 print("</table>");

 mysql_free_result($rs);
 mysql_close($db);
?>
</body>
</html>

4.パーミッションを755に変更
chmod 755 list.php


5.DBに接続し,id=1のものだけを表示するPHPファイルを作成
list2.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>list</title>
</head>
<body>
<?php
 $db_user  = "[user name]";
 $db_password = "[password]";
 $db_name = "[database name]";
 $db_host  = "localhost";

 $db = mysql_connect($db_host,$db_user,$db_password);
 mysql_select_db($db_name,$db); 
 $str_sql = "select * from sa2012 where id = 1";
 $rs = mysql_query($str_sql,$db);
 $num = mysql_num_fields($rs);

 print("<table><tr><th colspan=3>list</th></tr>");
 echo("
 ");
 print("<tr>");
 for ($i=0;$i<$num;$i++){
  print("<td><b>".mysql_field_name($rs,$i)."</b></td>");
 }
 print("</tr>");
 while($row=mysql_fetch_array($rs)){
  echo("
 ");
  print("<tr>");
  for($j=0;$j<$num;$j++){
   print("<td>".$row[$j]."</td>");
  }
  print("</tr>");
 }

 print("</table>");

 mysql_free_result($rs);
 mysql_close($db);
?>
</body>
</html>

2012年9月13日木曜日

WEBアプリケーションサーバの構築(1) WEBサーバ

1.まずはブラウザから自身のサーバにアクセスして状況確認
http://10.2.5.***


2.PHPインストール
yum install php
/etc/php.ini
memory_limit = 16M ; Maximum amount of memory a script may consume
3.Webサーバ(httpd)インストール
yum install httpd
chkconfig httpd on
service httpd start

4.Firewall設定
iptablesのルール初期化
/sbin/iptables -F

現在のルール確認
iptables -L

Firewallにルール追加
/etc/sysconfig/iptables
 # Firewall configuration written by system-config-firewall
 # Manual customization of this file is not recommended.
 *filter
 :INPUT ACCEPT [0:0]
 :FORWARD ACCEPT [0:0]
 :OUTPUT ACCEPT [0:0]
 -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
 -A INPUT -p icmp -j ACCEPT
 -A INPUT -i lo -j ACCEPT
 -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
 -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
 -A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT
 -A INPUT -j REJECT --reject-with icmp-host-prohibited
 -A FORWARD -j REJECT --reject-with icmp-host-prohibited
 COMMIT

service iptables restart

5.動作確認
ブラウザから以下のアドレスにアクセスし,テスト画面が表示されることを確認
http://10.2.5.***

2012年9月6日木曜日

各ユーザーのhome以下にpublic_htmlを作成するツール

userDirMake.sh
#!/bin/bash

for user in `ls /home`
do
    id $user > /dev/null 2>&1
    if [ $? -eq 0 ] && [ ! -d /home/$user/public_html ]; then
        mkdir -p /home/$user/public_html
        chown $user. /home/$user/public_html
        chmod 711 /home/$user
        echo $user
    fi
done

仮想環境(ESXi4)の準備

学生用仮想環境
10.2.5.2共有サーバ(1学期使用)
10.2.5.101折笠orikasa00:50:56:00:01:01
10.2.5.102金本kanemoto00:50:56:00:01:02
10.2.5.103鈴木suzuki00:50:56:00:01:03
10.2.5.104西崎nishizaki00:50:56:00:01:04
10.2.5.105西村nishimura00:50:56:00:01:05
10.2.5.106マナハンmanahan00:50:56:00:01:06
10.2.5.107荒井arai00:50:56:00:01:07
10.2.5.108小沼onuma00:50:56:00:01:08
10.2.5.109小谷田koyata00:50:56:00:01:09
10.2.5.110城田shirota00:50:56:00:01:10
10.2.5.111中山nakayama00:50:56:00:01:11
10.2.5.112萩原hagiwara00:50:56:00:01:12
10.2.5.113花山hanayama00:50:56:00:01:13
10.2.5.114樋口higuchi00:50:56:00:01:14
10.2.5.115船谷funaya00:50:56:00:01:15
10.2.5.116星野hoshino00:50:56:00:01:16
10.2.5.117間宮mamiya00:50:56:00:01:17
10.2.5.118佐藤mgrsato00:50:56:00:01:18


1.仮想イメージコピー後に,IPアドレス修正
(IPアドレスをコピー元の値から、各学生用のIPアドレスに変更する)

/etc/udev/rules.d/70-persistent-net.rules
 (最後尾のPCI deviceのみ残す)


/etc/sysconfig/network-scripts/ifcfg-eth0
 DEVICE=eth0
 BOOTPROTO=none
 ONBOOT=yes
 IPADDR=10.2.5.***
 NETMASK=255.0.0.0
 GATEWAY=10.1.0.1


2.VMware Toolsのインストール
mkdir /mnt/cdrom
mount /dev/cdrom /mnt/cdrom
cd /mnt/cdrom
cp VMwareTools-XXX.tar.gz /tmp
cd /tmp
tar zxvf VMwareTools-XXX.tar.gz
cd vmware-tools-distrib
./vmware-install.pl


3.DNS設定
/etc/resolv.conf
 nameserver 8.8.8.8
service network restart
yum update
yum install perl
yum install yum-fastestmirror
yum install yum-utils

2012年6月21日木曜日

WebAPIの利用(6)

WebAPIの利用(5)に,情報ウインドウ表示機能を追加する.
現状では情報ウインドウに特定の文字列を表示しているのみだが,ユーザーから受け取った場所を示す文字列「$word」を活用して,その場所固有の情報を表示するように各自工夫する事.
例)WebAPIの利用(2)を応用し,その地点の天気,最高/最低気温を表示

map_xmlParse2.php
<?php
$word = htmlspecialchars($_POST['word']);
$sensor = htmlspecialchars($_POST['sensor']);
$url = "http://maps.google.com/maps/api/geocode/xml";
$url .= "?address=".$word."&sensor=".$sensor;
$article = simplexml_load_file($url);

$lat = $article->result->geometry->location->lat;
$lng = $article->result->geometry->location->lng;

print<<<EOF
<html>
 <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <title>Google Geocoding and Maps JavaScript API Example</title>
  <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text
  /css" />
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.3&sensor=true"></script>
  <script type="text/javascript">
  function initialize() {
   var myLatlng = new google.maps.LatLng($lat, $lng);

   var myOptions = {
    zoom: 15,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
   };

   var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

   var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: '$word'
   });

   var contentStr = 'test';

   var infowindow = new google.maps.InfoWindow({
    content: contentStr,
    size: new google.maps.Size(50, 50)
   });

   google.maps.event.addListener(marker, 'click', function() {
   infowindow.open(map,marker)
   });
  }
  </script>
 </head>
 <body onload="initialize()">
  <div id="map_canvas"></div>
 </body>
</html>
EOF;
?>

情報ウインドウに天気を表示する例
<?php
$word = htmlspecialchars($_POST['word']);
$sensor = htmlspecialchars($_POST['sensor']);
$url = "http://maps.google.com/maps/api/geocode/xml";
$url .= "?address=".$word."&sensor=".$sensor;
$article = simplexml_load_file($url);

$lat = $article->result->geometry->location->lat;
$lng = $article->result->geometry->location->lng;

// get weather
$url2 = "http://www.google.com/ig/api?weather=".$word;
$xml = simplexml_load_file($url2);

$city = $xml->weather->forecast_information->city->attributes();
$forecast_date = $xml->weather->forecast_information->forecast_date->attributes();
$unit_system = $xml->weather->forecast_information->unit_system->attributes();

$current_condition = $xml->weather->current_conditions->condition->attributes();
$temp_c = $xml->weather->current_conditions->temp_c->attributes();
$humidity = $xml->weather->current_conditions->humidity->attributes();
$current_icon = $xml->weather->current_conditions->icon->attributes();
$wind_condition = $xml->weather->current_conditions->wind_condition->attributes();

print<<<EOF
<html>
<head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
 <title>Google Geocoding and Maps JavaScript API Example</title>
 <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text
 /css" />
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.3&sensor=true"></script>
 <script type="text/javascript">
 function initialize() {
  var myLatlng = new google.maps.LatLng($lat, $lng);

  var myOptions = {
   zoom: 15,
   center: myLatlng,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  var marker = new google.maps.Marker({
   position: myLatlng,
   map: map,
   title: '$word'
  });

  var contentStr = '$city($forecast_date)[$unit_system]<br />現在の状況:$current_condition<br />気温:$temp_c<br />湿度:$humidity<br /><img src="http://www.google.com$current_icon"><br />風向:$wind_condition';

  var infowindow = new google.maps.InfoWindow({
   content: contentStr,
   size: new google.maps.Size(50, 50)
  });

  google.maps.event.addListener(marker, 'click', function() {
   infowindow.open(map,marker)
  });
 }
 </script>
</head>
<body onload="initialize()">
 <div id="map_canvas"></div>
</body>
</html>
EOF;
?>

WebAPIの利用(5)

WebAPIの利用(4)を更に発展させ,ユーザーが入力した任意の文字列から座標を検索し,地図を表示する.

1.ユーザーが文字列を入力する画面(map_form.html)を用意.
2.画面に配置された送信ボタンを押すことで,postメソッドにより文字列を送信.
3.送信された文字列をphpファイル(map_xmlParse2.php)で受け取り.
4.受け取った文字列を用いて,マッチする座標を検索
5.座標を使って地図を表示.

表示例

LINK

map_form.html
<html>
<head>
 <title>form sample</title>
</head>
<body>
 <form action="map_xmlParse2.php" method="post">
  座標を調べたい文字列 : <input type="text" name="word" />
  <input type="hidden" name="sensor" value="true" />
  <input type="submit" />
 </form>
</body>
</html>

map_xmlParse2.php
<?php
 $word = htmlspecialchars($_POST['word']);
 $sensor = htmlspecialchars($_POST['sensor']);
 $url = "http://maps.google.com/maps/api/geocode/xml";
 $url .= "?address=".$word."&sensor=".$sensor;
 $article = simplexml_load_file($url);

 $lat = $article->result->geometry->location->lat;
 $lng = $article->result->geometry->location->lng;

print<<<EOF
 <html>
 <head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
 <title>Google Geocoding and Maps JavaScript API Example</title>
 <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
 <script type="text/javascript">
   function initialize() {
     var myLatlng = new google.maps.LatLng(
EOF;
 echo $lat;
 echo ", ";
 echo $lng;
print<<<EOF
     );

     var myOptions = {
       zoom: 15,
       center: myLatlng,
       mapTypeId: google.maps.MapTypeId.ROADMAP
     }
     var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

     var marker = new google.maps.Marker({
       position: myLatlng,
       map: map,
       title:"
EOF;
 echo $word;
print<<<EOF
       "
     });
   }
 </script>
 </head>
 <body onload="initialize()">
   <div id="map_canvas"></div>
 </body>
 </html>
EOF;
?>

Javascriptについて

まずはHello, world.

js_1.html
<html>
 <head>
  <title>Javascript</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   document.write("Hello World");
   // -->
  </script>
 </body>
</html>


Javascriptにおける変数の扱いについて.
※Javascriptでは変数を明示的に宣言する場合、var を用います.
※Javascriptでは変数名や関数名などの大文字と小文字は別の文字として扱われます.

js_2.html
<html>
 <head>
  <title>サンプル</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   str = "small letter";
   STR = "CAPITAL LETTER";
   document.write(str + STR);
   // -->
  </script>
 </body>
</html>


PHPとJavascriptを組み合わせて利用.
※PHPはサーバーサイドで実行され,Javascriptはクライアントサイドで実行される事に注意.

js_3.php
<?php
$str = "Hello World";

print<<<EOL
<html>
 <head>
  <title>Javascript</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   document.write($str);
   // -->
  </script>
 </body>
</html>
EOL;

?>

2012年6月14日木曜日

WebAPIの利用(4)

WebAPIの利用(3)を発展させ,入力した文章中のキーフレーズを画像に置き換えて表示する.
(ユーザーによる)文章入力 →キーフレーズ抽出API →キーフレーズによる画像検索 →元となる文章中のキーフレーズ部分を画像に置換

表示例

LINK

text_form2.html
<html>
 <head>
  <title>text form2</title>
 </head>
 <body>
  <form action="text_xmlParse2.php" method="post">
   変換したい文字列 : <input type="text" name="word" />
  <input type="submit" />
 </form>
 </body>
</html>

text_xmlParse2.php
<?php
$word = htmlspecialchars($_POST['word']);
$appid = "(アプリケーションID)";

$url1 = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract";
$url1 .= "?sentence=".$word."&appid=".$appid;
$article1 = simplexml_load_file($url1);
$keyphrase = $article1->Result->Keyphrase;
$score = $article1->Result->Score;

$url2 = "http://search.yahooapis.jp/ImageSearchService/V2/imageSearch";
$url2 .= "?results=1&query=".$keyphrase."&appid=".$appid;
$article2 = simplexml_load_file($url2);
$image_url = $article2->Result->Url;
$image_thumbnail = $article2->Result->Thumbnail->Url;

print<<<EOF
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>keyphrase replace2</title>
</head>
<body>
EOF;
echo "キーフレーズ:";
echo $keyphrase;

echo "<br />";
echo "スコア:";
echo $score;

echo "<br />";
echo "画像URL:";
echo $image_url;

echo "<br />";
echo "サムネイルURL:";
echo $image_thumbnail;


echo "<br />";
echo "<br />";
echo "元の文章:";
echo $word;

echo "<br />";
echo "<br />";
echo "変換後の文章:";
$temp = str_replace($keyphrase, "<a href=".$image_url."><img src=".$image_thumbnail."></a>", $word);
echo $temp;


print<<<EOF
</body>
</html>
EOF;
?>

WebAPIの利用(3)

Yahoo!のテキスト解析Web APIのキーフレーズ抽出を利用して,入力した文章中のキーフレーズを抽出し,そのキーフレーズに対して置換やリンクの付与等を行う.

表示例

LINK

text_form.html
<html>
 <head>
  <title>text form</title>
 </head>
 <body>
  <form action="xmlParse.php" method="post">
   変換したい文字列 : <input type="text" name="word" />
  <input type="submit" />
 </form>
 </body>
</html>

text_xmlParse.php
<?php
$word = htmlspecialchars($_POST['word']);
$appid = "(アプリケーションID)";
$url = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract";
$url .= "?sentence=".$word."&appid=".$appid;
$article = simplexml_load_file($url);

$keyphrase = $article->Result->Keyphrase;
$score = $article->Result->Score;

print<<<EOF
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>keyphrase replace</title>
</head>
<body>
EOF;
echo "キーフレーズ:";
echo $keyphrase;

echo "<br />";
echo "スコア:";
echo $score;

echo "<br />";
echo "元の文章:";
echo $word;

echo "<br />";

echo "<br />";
echo "変換後の文章1:";
$temp1 = str_replace($keyphrase, "<b>禁則事項</b>", $word);
echo $temp1;

echo "<br />";
echo "変換後の文章2:";
$temp2 = str_replace($keyphrase, "<a href=http://www.google.com/search?q=".$keyphrase.">".$keyphrase."</a>", $word);
echo $temp2;

echo "<br />";
echo "変換後の文章3:";
$temp2 = str_replace($keyphrase, "<a href=http://www.google.com/search?tbm=isch&q=".$keyphrase.">".$keyphrase."</a>", $word);
echo $temp2;

print<<<EOF
</body>
</html>
EOF;
?>
※アプリケーションIDの登録はこちら.

2012年6月7日木曜日

WebAPIの利用(2)

気象情報(天気予報)APIの利用

表示例

LINK

API URL
http://www.google.com/ig/api?weather=Yokohama,Kanagawa

取得されるXMLのサンプル
<xml_api_reply version="1">
 <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
  <forecast_information>
   <city data="Yokohama, Kanagawa Prefecture"/>
   <postal_code data="Yokohama,Kanagawa"/>
   <latitude_e6 data=""/>
   <longitude_e6 data=""/>
   <forecast_date data="2011-11-17"/>
   <current_date_time data="1970-01-01 00:00:00 +0000"/>
   <unit_system data="SI"/>
  </forecast_information>
  <current_conditions>
   <condition data="ところにより曇り"/>
   <temp_f data="63"/>
   <temp_c data="17"/>
   <humidity data="湿度 : 39%"/>
   <icon data="/ig/images/weather/jp_cloudy.gif"/>
   <wind_condition data="風: 南東 4 m/s"/>
  </current_conditions>
  <forecast_conditions>
   <day_of_week data="木"/>
   <low data="11"/>
   <high data="18"/>
   <icon data="/ig/images/weather/jp_sunny.gif"/>
   <condition data="ところにより晴れ"/>
  </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="金"/>
   <low data="10"/>
   <high data="18"/>
   <icon data="/ig/images/weather/jp_cloudy.gif"/>
   <condition data="曇り"/>
   </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="土"/>
   <low data="16"/>
   <high data="21"/>
   <icon data="/ig/images/weather/jp_rainysometimescloudy.gif"/>
   <condition data="雨の可能性"/>
  </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="日"/>
   <low data="14"/>
   <high data="22"/>
   <icon data="/ig/images/weather/jp_rainysometimescloudy.gif"/>
   <condition data="雨の可能性"/>
  </forecast_conditions>
 </weather>
</xml_api_reply>

weather.php
<?php
 $area = "Yokohama";
 $url = "http://www.google.com/ig/api?weather=".$area;

 $xml = simplexml_load_file($url);

//forecast_information
 $city = $xml->weather->forecast_information->city->attributes();
 $forecast_date = $xml->weather->forecast_information->forecast_date->attributes();
 $unit_system = $xml->weather->forecast_information->unit_system->attributes();

//current_conditions
 $current_condition = $xml->weather->current_conditions->condition->attributes();
 $temp_c = $xml->weather->current_conditions->temp_c->attributes();
 $humidity = $xml->weather->current_conditions->humidity->attributes();
 $current_icon = $xml->weather->current_conditions->icon->attributes();
 $wind_condition = $xml->weather->current_conditions->wind_condition->attributes();

//forecast_conditions
 $day_of_week = $xml->weather->forecast_conditions->day_of_week->attributes();
 $low = $xml->weather->forecast_conditions->low->attributes();
 $high = $xml->weather->forecast_conditions->high->attributes();
 $forecast_icon = $xml->weather->forecast_conditions->icon->attributes();
 $forecast_condition = $xml->weather->forecast_conditions->conditionh->attributes();

print<<<EOF
 <html>
 <head>
 <title>google weather sample</title>
 </head>
 <body>
EOF;

 print "場所:".$city."<br />";
 print "予報日:".$forecast_date."<br />";
 print "単位:".$unit_system."<br />";
 print "<br />";
 print "現在の状況<br />";
 print "状況:".$current_condition."<br />";
 print "気温:".$temp_c."<br />";
 print "湿度:".$humidity."<br />";
 print "<img src='http://www.google.com".$current_icon."'><br />";
 print "風向:".$wind_condition."<br />";
 print "<br />";
 print "明日の天気<br />";
 print "曜日:".$day_of_week."<br />";
 print "最低気温:".$low."<br />";
 print "最高気温:".$high."<br />";
 print "<img src='http://www.google.com".$forecast_icon."'><br />";
 print "状況:".$forecast_condition."<br />";

print<<<EOF
 </body>
 </html>
EOF;
?>

WebAPIの利用(1)

twitter public timeline検索APIの利用
表示例

LINK

取得されるXMLのサンプル(一部抜粋)
<?xml version="1.0" encoding="utf-8"?>
<rss>
 <channel>
   <item>
    <title>@Copa3 ありがとうございます。横浜ですかそりゃ、とおくていけませんわ。</title>
    <link>http://twitter.com/sendaimo/statuses/137026307379822592</link>
    <description>@&lt;a class=" " href="http://twitter.com/Copa3"&gt;Copa3&lt;/a&gt; ありがとうございます。&lt;em&gt;横浜&lt;/em&gt;ですかそりゃ、とおくていけませんわ。</description>
    <pubDate>Thu, 17 Nov 2011 04:36:32 +0000</pubDate>
    <guid>http://twitter.com/sendaimo/statuses/137026307379822592</guid>
    <author>sendaimo@twitter.com (Kimiaki Nagase)</author>
    <media:content type="image/jpg" height="48" width="48" url="http://a0.twimg.com/profile_images/825361762/saxbobo02_normal.gif" xmlns:media="http://search.yahoo.com/mrss/" />
    <google:image_link xmlns:google="http://base.google.com/ns/1.0">http://a0.twimg.com/profile_images/825361762/saxbobo02_normal.gif</google:image_link>
    <twitter:metadata xmlns:twitter="http://api.twitter.com/">
     <twitter:result_type>recent</twitter:result_type>
    </twitter:metadata>
   </item>
 </channel>
</rss>

twitter_timeline.php
<?php
 $word = "横浜";
 $url = "http://search.twitter.com/search.rss?q=".$word;

 $rss = simplexml_load_file($url);

 $title = $rss->channel->item->title;
 $link = $rss->channel->item->link;
 $description = $rss->channel->item->description;
 $pubDate = $rss->channel->item->pubDate;
 $author = $rss->channel->item->author;

print<<<EOF
 <html>
 <head>
 <title>twitter sample</title>
 </head>
 <body>
EOF;

 print "title : ".$title."<br />";
 print "link : ".$link."<br />";
 print "description : ".$description."<br />";
 print "pubDate : ".$pubDate."<br />";
 print "author : ".$author."<br />";
 print "image_link : ".$iage_link."<br />";

print<<<EOF
 </body>
 </html>
EOF;
?>

2012年5月31日木曜日

WEBサーバの利用

1.public_htmlへ移動
# cd public_html
2.index.htmlを作成
# vi index.html

<html>
<head>
<link rel="stylesheet" href="base.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>テスト</title>
<body>
テスト
</body>
</html>
3.base.cssを作成
body {
 font: normal normal 14px Arial, Tahoma, Helvetica, FreeSans, sans-serif;
 color: #000000;
 background: #aabbaa none no-repeat scroll center center;
 font-family:'ヒラギノ角ゴ Pro W3','Hiragino Kaku Gothic Pro','メイリオ',Meiryo,'MS Pゴシック',sans-serif;
}

html body .region-inner {
 min-width: 0;
 max-width: 100%;
 width: auto;
}

.content-outer {
 font-size: 90%;
}

a:link {
 text-decoration:none;
 color: #445566;
}
a:visited {
 text-decoration:none;
 color: #000000;
}
a:hover {
 text-decoration:underline;
 color: #1455ff;
}
4.phpinfo.phpを作成
# vi phpinfo.php

<?php
  phpinfo();
?>

#chmod 755 phpinfo.php
4.Hello, World!
# vi hello.php

<?php
echo "Hello World!";
?>

# chmod 755 hello.php
5.文字列表示・結合
# vi test.php

<?php
$str1 = "Hello";
$str2 = "World";

print<<<EOF
<html>
<head>
<link rel="stylesheet" href="base.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>テスト2</title>
<body>
テスト2
<br>
EOF;

echo $str1.",".$str2;

print<<<EOF
</body>
</html>
EOF;
?>

# chmod 755 test.php
6.外部APIの利用(twitter)
# vi twitter.php

<?php
 $word = "横浜";
 $url = "http://search.twitter.com/search.rss?q=".$word;

 $rss = simplexml_load_file($url);

 $title = $rss->channel->item->title;
 $link = $rss->channel->item->link;
 $description = $rss->channel->item->description;
 $pubDate = $rss->channel->item->pubDate;
 $author = $rss->channel->item->author;

print<<<EOF
 <html>
 <head>
 <link rel="stylesheet" href="base.css" />
 <title>twitter sample</title>
 </head>
 <body>
EOF;

 print "title : ".$title."<br />";
 print "link : ".$link."<br />";
 print "description : ".$description."<br />";
 print "pubDate : ".$pubDate."<br />";
 print "author : ".$author."<br />";
 print "image_link : ".$iage_link."<br />";

print<<<EOF
 </body>
 </html>
EOF;
?>

#chmod 755 twitter.php

2012年5月10日木曜日

授業用仮想環境の構築

以下の記事を参考に,授業用の仮想環境を構築

仮想環境構築手順(サーバ編)
http://mgrsato.blogspot.jp/2011/11/blog-post_8056.html

仮想環境構築手順(クライアント編)
http://mgrsato.blogspot.jp/2011/11/blog-post_2844.html

[SA-3-2] サーバーへのユーザー追加
http://mgrsato.blogspot.jp/2010/09/sa-23.html

初期設定~WEBサーバ構築
http://mgrsato.blogspot.jp/2011/12/web.html

[SA-3-10] httpd設定
http://mgrsato.blogspot.jp/2010/10/sa-3-httpd.html

2012年4月26日木曜日

サーバを構成する要素 -CPU-

1.自分たちが使用しているPCのCPUが持つ機能を確認する.

2.近年のサーバ用のCPUについても,機能等確認する.

3.サーバの用途毎に必要とされる機能,留意すべき項目等について議論する.