newtype
::: newtype의 지식창고 :::
newtype
전체 방문자
오늘
어제
  • 분류 전체보기 (392)
    • Dev (214)
      • C, C++ (43)
      • Go (5)
      • Web (49)
      • DBMS (21)
      • DevOps (8)
      • Java (2)
      • Windows, Win32 (4)
      • Visual Basic (5)
      • C# (2)
      • Mobile (25)
      • SQL CE (7)
      • Google Map (6)
      • Python (2)
      • cygwin (2)
      • 기타 (32)
      • Ruby (1)
    • 명언 (10)
    • 모임 (18)
      • 붕주회 (3)
      • 신흥컴정 (14)
      • 웹20기 (1)
    • 사진 (8)
    • 불펌 (29)
    • 막글 (98)
    • 게임 (6)
    • 여행 (8)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

  • whoami
05-24 02:36
hELLO · Designed By 정상우.
newtype
Dev/Web

GoogleGear Sample source

Dev/Web

GoogleGear Sample source

2007. 7. 4. 03:42

얼마전 구글에서 GoogleGear라는 것을 배포 했다.
처음엔 어떤것인지도 몰랐는데..
최근에 알게된 사실로는 오프라인에서도 웹서핑을 도와준다고 한다.

자세히 내용을 살표보니 SQLite를 이용해 웹에 있는 자료들을 미리 읽어들어 저장해 두고,
오프라인 일 때도 써먹는 다는 내용이였다.

사실, IE의 "오프라인으로 작업"등 비슷한 기능은 이미 있었다.
하지만, 역시 구글이다.
개발자들이 편하게 접근할 수 있도록 GoogleGear API를 열어두었다.

그럼, 코드로 만나보자.

1. GoogleGear를 사용하기 위해서는 먼저 설치가 되어있어야 한다.
   처음 발표되었을때, 뭔지도 모르고 미리 설치는 해두었다 ^^;

2. gears_init.js 파일을 html안에 포함 해야한다.
<script src="gears_init.js"></script>
  gears_init.js 파일을 미리 받아 놓고 위 코드를 html에 포함 해도 되고,
  gears_init.js 파일의 내용 전부를 html 파일에 포함 시켜도 된다.

3. 설치 여부 체크
  html 파일이 열리면, GoogleGear가 설치되어 있는지 체크 하는 부분이 있어야 한다.
  if ( !window.google || !google.gears ) 
  {
      alert('GoogleGear를 먼저 설치하세요.');
      return;
  }

4. DB파일을 생성한다.
SQLite는 파일 하나로 Database를 로칼 컴퓨터에 생성 한다.
FireFox에서는 C:\Documents and Settings\<사용자명>\Application Data\Mozilla\Firefox\Profiles\<임시이름>.default\urlclassifier2.sqlite 라는 파일이 생성되었다.
  try {
    db = google.gears.factory.create('beta.database', '1.0');
  } catch (ex) {
    alert('Database를 생성할 수 없습니다: ' + ex.message);
  }

5. 테이블을 만든다.
  if (db) {
    db.open('address');
    db.execute('create table if not exists ntAddress' +
               ' (name varchar(255), phone varchar(255), email varchar(255) , Timestamp int)');

    display();
  }
  소스를 보면 알겠지만, 자바스크립트에서 쿼리를 직접 날린다. @.@

6. 쿼리를 날린다.
   이렇게 쉽게 사용이 가능하다.
   try {
    db.execute('insert into ntAddress values (?, ?, ?, ?)', [oName.value, oPhone.value, oMail.value, currTime]);
  } catch (e) {
    alert(e.message);
    throw new Error(e.message);
alert (e.message);
   }

   이제까지 Google API가 그러했듯이 엄청 간단하다.
   우리가 잘 아는 쿼리를 직접 날리고,
   무거운 작업의 경우 WorkPool을 이용해 백그라운드로 돌릴 수도 있다.
   LocalServer를 이용해 서버 정보를 간단하게 캐쉬로 만들어 저장하는 할 수도 있는 듯하다.
   Google에서 제공하는 샘플 소스 및 툴 을 받아보자

   손가락이 근질근질 하지 않은가. 흐흐흐흐흐...
 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>주소록</title>
</head>

<body>
<h1>Google Gears Database 를 이용한 주소록</h1>
  <table>
    <tr>
      <td valign="middle"><input type="text" id="title_name"  style="width:10em; border:0px;" value="이름"></td>
      <td valign="middle"><input type="text" id="title_name"  style="width:15em; border:0px;" value="전화번호"></td>
      <td valign="middle"><input type="text" id="title_name"  style="width:15em; border:0px;" value="E-Mail"></td>
      <td valign="middle"><input type="text" id="title_name"  style="width:10em; border:0px;" value="명령"></td>
    </tr>
  </table>
  <span id="view-list">
  </span>
<form onsubmit="doSave(); return false;">
  <table>
    <tr>
      <td valign="middle"><input type="text" id="iName"  style="width:10em;"></td>
      <td valign="middle"><input type="text" id="iPhone"  style="width:15em;"></td>
      <td valign="middle"><input type="text" id="iMail"  style="width:15em;"></td>
      <td valign="middle"><input type="submit" value="Save"></td>
    </tr>
  </table>
</form>
<div id="state"></div>

<script src="gears_init.js"></script>
<script>
var db;
init();

function init()
{
  if ( !window.google || !google.gears ) 
  {
      location.href = "http://gears.google.com/?action=install&message=GoogleGear를 먼저 설치하세요.&return=" + location.href;
      return;
  }

  try {
    db = google.gears.factory.create('beta.database', '1.0');
  } catch (ex) {
    alert('Database를 생성할 수 없습니다: ' + ex.message);
  }

  if (db) {
    db.open('address');
    db.execute('create table if not exists ntAddress' +
               ' (name varchar(255), phone varchar(255), email varchar(255) , Timestamp int)');

    display();
  }
}

function doDel(saveTime)
{
   if (!google.gears.factory || !db)  return;
  
  
   try {
    db.execute('delete from ntAddress where Timestamp='+ saveTime);
  } catch (e) {
    alert(e.message);
    throw new Error(e.message);
  }   
    display();
}

function doSave()
{
  if (!google.gears.factory || !db)  return;

  var oName = document.getElementById('iName');
  var oPhone = document.getElementById('iPhone');
  var oMail = document.getElementById('iMail');
  var currTime = new Date().getTime();
 
   try {
    db.execute('insert into ntAddress values (?, ?, ?, ?)', [oName.value, oPhone.value, oMail.value, currTime]);
  } catch (e) {
    alert(e.message);
    throw new Error(e.message);
alert (e.message);
   }

  alert( "'" + oName.value + '" 저장에 성공했습니다.');

  oName.value = '';
  oPhone.value = '';
  oMail.value = '';
 
  display();
}

function display()
{
  var txtResult = '';

  try
  {
    var rs = db.execute('select * from ntAddress order by Timestamp desc');
    var index = 0;
   
    if (rs.isValidRow()==true)
    {
      txtResult = '  <table>\n';
      while (rs.isValidRow())
      {
        txtResult += '    <tr>\n';
        txtResult += '      <td valign="middle"><input type="text" style="width:10em; border:0px;" value="' + rs.field(0) + '"></td>\n';
        txtResult += '      <td valign="middle"><input type="text" style="width:15em; border:0px;" value="' + rs.field(1) + '"></td>\n';
        txtResult += '      <td valign="middle"><input type="text" style="width:15em; border:0px;" value="' + rs.field(2) + '"></td>\n';
        txtResult += '      <td valign="middle"><input type="button" value="Del" onclick="doDel(' + rs.field(3) + ')"></td>\n';
        txtResult += '    </tr>\n';

        ++index;
        rs.next();
      }
      txtResult += '  </table>\n';
    }
    rs.close();
  } catch (e) {
    alert (e.message);
    throw new Error(e.message);
   
  }
 
  document.getElementById('view-list').innerHTML = txtResult;
  alert ( index + '개의 주소록 조회를 성공했습니다' );
}
</script>
</body>
</html>



덧글,
샘플 코딩하면서 삽질을 했다.
innerHTML 스크립트가 IE7에서 먹지 않는 것이다.
한참 삽질을 하다가 IE7 관련 자료에서 이런 문구를 발견 했다.
IE does not support when setting a div’s innerHTML property
div 테그를 span으로 바꾸고 간단히 해결했다.
신버전은 구버전과 호환 되게 해달라고!!!  버럭



반응형

'Dev > Web' 카테고리의 다른 글

다음 자동 로그인 주소 변경..  (4) 2007.11.02
한글변환기  (16) 2007.09.12
티스토리 스킨  (0) 2007.02.23
간단한 Ajax Sample 코드  (2) 2007.02.13
JSP 만으로 오라클 접속  (0) 2007.01.09
    'Dev/Web' 카테고리의 다른 글
    • 다음 자동 로그인 주소 변경..
    • 한글변환기
    • 티스토리 스킨
    • 간단한 Ajax Sample 코드
    newtype
    newtype
    지극히 개인적인 지식의 창고

    티스토리툴바

    단축키

    내 블로그

    내 블로그 - 관리자 홈 전환
    Q
    Q
    새 글 쓰기
    W
    W

    블로그 게시글

    글 수정 (권한 있는 경우)
    E
    E
    댓글 영역으로 이동
    C
    C

    모든 영역

    이 페이지의 URL 복사
    S
    S
    맨 위로 이동
    T
    T
    티스토리 홈 이동
    H
    H
    단축키 안내
    Shift + /
    ⇧ + /

    * 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.