Sunday, March 16, 2008

Backup and Restore SQL Server using Transact SQL

Pada sebuah database umumnya kita membutuhkan back up yang dilakukan secara berkala pada pengaturan sistem produksi yang ada. Back up sangat dibutuhkan untuk melindungi data dari bencana.Microsoft SQL Server 2000 memperkenalkan berbagai cara untuk melakukan back up yang dapat dikombinasikan menjadi sebuah rumus yang diatur sedemikian rupa untuk melindungi dan mengembalikan data sesuai dengan sebelumnya dari kerusakan yang telah terjadi. SQL Server 2000 menambah beberapa aspek untuk fungsi backup dan restore yang telah dimiliki sebelumnya dalam SQL Server 7. Sangat di perlukan untuk melakukan backup database secara berkala. Ini adalah cara terbaik untuk menghasilkan recovery data untuk menjaga data dari berbagai bencana.

Kita akan membahas berbagai macam cara backup yang tersedia pada SQL Server 2000 dan bagaimana rumus-rumusnya dapat digunakan.

Backup Device
Backup device dapat dibuat melalui SQL Enterprise Manager atau menggunakan perintah Transact SQL. Untuk membuat backup device melalui Enterprise Manager.

  1. Buka Enterprise Manager dan pilih SQL Server Group lalu pilih SQL Server Registrationnya yang akan dibackup.
  2. Pilih folder Management dan klik kanan Backup sampai muncul menu pop-up.
  3. Pilih New Backup Device sampai muncul window Backup Device Properties – New Device.
  4. Masukan Nama dan File Name untuk lokasi backup devicenya. Tape Drive Name di disable karena komputer yang digunakan tidak terinstal tape drive. Klik OK jika selesai. Backup device akan terbentuk. Backup device sudah terbentuk, klik kanan di Management -> Backup di Enterprise Manager. Untuk melihat propertiesnya, klik kanan di device dan pilih Properties. Klik View Contents untuk daftar backup yang sudah dilakukan oleh device tersebut.


Backup device juga dapat dibuat dengan menggunakan perintah Transact-SQL melalui SQL Query Analyzer.

  1. Pada SQL Query Analyzer, pada jendela Query, pertama tentukan backup device tersebut untuk database mana? Pilih database dengan memilih database pada menu bar diatas atau menekan tombol Ctrl-U
  2. Lalu ketikan sbb:
    sp_addumpdevice ‘disk’,‘Northwind Complete’,‘d:\backup\Northwind Complete.bak’
  3. Jalankan dengan mengklik tombol Execute Query pada toolbar atau menekan tombol F5 pada keyboard.


Menambahkan Backup History dari Backup Files ke MSDB

Dibawah ini akan dibahas prosedur untuk restore history backup dari file backup.

  1. Buka Enterprise Manager dan pilih SQL Server Group lalu pilih SQL Server Registrationnya yang akan direstore.
  2. Klik kanan di database manapun dan pilih All Task, lalu pilih Restore Database. Window Restore Database akan muncul.
  3. Pilih database yang akan direstore pada Restore as batabase, lalu pilih From Device.
  4. Pilih Read backup set information and add backup history di bagian Parameter.
  5. Klik tombol Select Devices untuk menambah backup file ke listnya. Sampai muncul window Choose Restore Devices.
  6. Klik tombol Add dan pilih backup file yang akan diload.
  7. Lalu klik OK sampai muncul Successfully loaded backup set history. Backup history sukses.
  8. Jika tidak berhasil, pilih tab Options pada window Restore database. Pastikan alamat MDF dan LOGnya sesuai dengan alamat yang ada. Jika masih tidak mau pilih Force restore over existing database pada Options.


Melakukan Backup Complete Database

Untuk Backup complete database dapat dilakukan melalui SQL Server Enterprise Manager atau menggunakan perintah Transact-SQL. Complete backup juga dapat di schedule dengan interval waktu tertentu.
Langkah-langkah untuk melakukan complete backup database melalui SQL Server Enterprise Manager

  1. Buka Enterprise Manager dan pilih SQL Server Groupnya lalu pilih SQL Server Registration.
  2. Buka folder Database, lalu klik kanan pada database yang mau dibackup.
  3. Pilih All Tasks, lalu pilih Backup Database sampai muncul window SQL Server backup.
  4. Masukan nama backup di kolom Nama. Pilih Database – complete untuk complete database backup.
  5. Pilih Overwrite existing media untuk inisialisasi file tujuan atau devicenya atau pilih Append to media untuk menambahkan backup yang sudah terpilih ke file yang sudah ada atau device.

  6. Untuk memilih tujuan backupnya, pilih tombol Add. Akan muncul window Select Backup Destinantion.
  7. Pilih file yang sudah ada atau mesukan nama file yang baru. Klik OK.
  8. Pilih tab Options.
  9. Pilih Verify backup upon completion untuk memberikan peringatan apabila backup selesai.

    Pilih Remove inactive entries from transaction log jika mau menghapus semu log-log backup transaksi yang sudah tidak aktif.

    Pilih Check media set name and backup set expiration untuk memberitahukan media yang terpilih dari media yang tersedia supaya mencegah kesalahan untuk file yang dibackup.

    Pilih Eject tape after backup untuk mengeluarkan kaset secara otomatis dari drivenya pada saat backup selesai.

    Pilih Backup set will expire untuk menentukan tanggal kadaluarsa file backup agar tidak dapat direstore melebihi tanggal yang sudah diset.

  10. Klik OK untuk memulai backup atau pilih Schedule untuk menjadwalkan operasi backup tersebut.
  11. Tunggu sampai muncul The backup operation has been completed successfully.


Untuk backup database menggunakan perintah Transact-SQL

  1. Buka SQL Query Analyzer.
  2. Ketikan perintah:
    BACKUP DATABASE northwind TO DISK = ‘d:\backups\northwind\nwind.bak’
  3. Jalankan dengan mengklik tombol Execute Query pada toolbar atau menekan tombol F5 pada keyboard.

Restore Complete Backup Database
Untuk merestore database complete yang sudah dibackup, dapat direstore ke database yang sama atau ke database yang berbeda tetapi dalam server yang sama. Untuk mengoperasikanyan dapat melaluiSQL Server Enterprise Manager atau mengunakan perintah Transact-SQL.

Untuk melakukan complete restore database ke database yang sama melalui SQL Server Enterprise

  1. Buka Enterprise Manager dan pilih SQL Server Groupnya lalu pilih SQL Server Registration.
  2. Klik kanan pada database manapun dan pilih All Tasks, lalu pilih Restore Database sampai muncul window Restore Database.
  3. Pilih database backup yang mau direstore. Semua yang pernah melakukan backup ada dalam list pada bagian Parameter. Semua informasi dikumpulkan dari tabel daftar history di MSDB database.
  4. Pada daftar backupnya di bagia Parameter, lalu klik tombol Properties untuk melihat detail backupnya.
  5. Lalu pilih tab Options. Pada tab ini memberitahukan nama dan lokasi database yang mau direstore. Pastikan alamat dan namanya sesuai.
  6. Ada beberapa setting pada tab tersebut:
    Eject tapes after restoring each backupagar kaset pada tape backup secara otomatis keluar setelah restore selesai.
    Prompt before restoring each backup untuk menampilkan dialog ox setelah restore selesai. Pilihan ini dapat digunakan jika melakukan restore lebih dari satu file backup.
    Force restore over existing database untuk melakukan restore pada database yang sudah ada dengan cara menghapus database yang lama lalu restore dengan yang baru.
    Restore As menunjukan alamat database yang mau direstorenya.
    Recovery completion state untuk mendeteksi tahap akhir dari restore.
    Undo file menunjuk pada file yang dibutuhkan oleh SQL Server untuk melacak transaksi restore yang tidak selesai jika restore dalam keadaan standby.
  7. Klik OK untuk memulai proses restore. Akan muncul progressnya sampai muncul pesan sukses atau gagal.


Restore complete backup ke Database baru dalam server yang sama

Database baru dapat dibuat secara otomatis ketika restore selesai. Database baru tersebut dibuat dalam server yang sama dengan database asalnya.

Untuk melakukan restore dari backup complete ke database yang baru dalam server yang sama

  1. Buka Enterprise Manager dan pilih SQL Server Groupnya lalu pilih SQL Server Registration.
  2. Klik kanan pada database manapun dan pilih All Tasks, lalu pilih Restore Database sampai muncul window Restore Database.
  3. Masukan nama database yang akan direstore di pilihan Restore as database.
  4. Didalam Parameter, pilih backup file yang mau direstore. Semua daftar backupnya muncul dibawahnya.
  5. Pilih pada daftar tersebut yang mau direstore dan klik Properties untuk melihat detail dari backup tersebut.
  6. Pilih tab Option.
  7. Perlu diperhatikan nama file dan lokasi MDF dan LOG dari database di Restore As.
  8. Untuk memulai restore, klik OK. Akan muncul progress sampai muncul konfirmasi gagal atau suksesnya.


Untuk melakukan restore dari backup complete ke database yang baru dalam server yang sama menggunakan perintah Transact-SQL

  1. Buka SQL Query Analyzer.
  2. Ketikan perintah:
    RESTORE DATABASE nwind_new FROM DISK = ‘c:\backups\northwind\nwind.bak’WITH
    MOVE ‘northwind’ TO ‘d:\Program Files\Microsoft SQL Server\Data\nwind_new.mdf’
    MOVE ‘northwind_log’ TO
    ‘d:\Program Files\Microsoft SQL Server\Data\nwind_new_log.ldf’
  3. Jalankan dengan mengklik tombol Execute Query pada toolbar atau menekan tombol F5 pada keyboard.

Melakukan Restore complete backup ke server yang berbeda
Database SQL Server dapat dibackup dari satu server dan direstore ke server yang lain. Jika database tujuan tidak ada, database tersebut harus dibuat dahulu sebelum proses restore dijalankan. Tetapi database yang baru juga dapat dibuat secara otomatis pada saat melakukan restoring.

Untuk restoring database backup ke server yang berbeda ke database yang baru

  1. Copykan file backupnya ke komputer tujuan atau melalui sharing folder.
  2. Gunakan Enterprise Manager GUI. Lakukan koneksi sampai ke SQL Server Registrationnya.
  3. Klik kanan didatabase manapun dan pilih All Tasks, lalu pilih Restore Database sampai muncul window Restore Databasenya.
  4. Masukan nama database barunya pada Restore as database.
  5. Pilih From device.
  6. Klik tombol Select Devices. Sampai muncul window Choose Restore Devices.
  7. Pilih salah satu Disk atau Tape.
  8. Pilih tombol Add sampai muncul window Choose Restore Destination.
  9. Pilih nama file dan lokasinya. Klik OK sampai kembali ke window Restore Database.
  10. Pilih tab Options dan pastikan nama dan lokasinya sesuai.
  11. Klik OK untuk memulai restoring. Sampai muncul konfirmasi sukses.

Untuk melakukan restoring melalui perintah Transact-SQL, sama dengan perintah pada Restoring complete backup ke database yang baru dalam server yang sama.

Tuesday, March 11, 2008

Step by Step to use Oracle through SQLPlus in UMBC

This tutorial will give basic information about how to use Oracle through SQLPlus in UMBC. Absolutely, you need a GL account, in CMSC461 class to get access priority of Oracle. If you are connecting the GL server from your own pc, you also need a ssh client. I assume the readers know how to connect to the GL machine, know basic ideas of Database and SQL statements.

Step 0: Preparation

Now we begin to our tutorial. I will use these naïve tables as my example.

Student (Studentid, Studentname)

Course (Courseid,Coursename Teachername)

Report (Studentid, Courseid,Grade)

The database has three tables. Student table contains the student information. Course table contains the course information. Report table contains what courses the student chooses and their grades. In the following step, I will show you how to build tables, add, delete and update records, execute queries through SQLPlus.

Now try to draw the E-R diagram for this naïve example.

Step 1: Connecting to Oracle and Exit SQLPlus

Use your GL account to connect to the GL server. (An ssh client can be downloaded from myUMBC) I assume you are already connecting to the GL server in the following steps.

At the prompt, type:

source /usr/local/oracle/oracle.cshrc (if you are using tcsh or csh)

source /usr/local/oracle/oracle.profile (if you are using bash)

Then type:

sqlplus $USER

You can use your gl account’s name to replace $USER or just keep it. If you see the symble below:

SQL>

You’ve successfully connect to the Oracle server.

If you want to exit SQLPlus, simply type in

Exit

You can then leave SQLPlus and exit to the shell you login.

Step 2: Getting Help from SQLPlus

SQLPlus is an interactive program, which means if you forget something, you can ask SQLPlus to tell you. The “help” command is very useful.

HELP displays information on the commands and conventions of SQL*Plus, SQL, and PL/SQL. Type "help", a space, all or part of any topic, and then press Enter. Since it is an easy command, here I do not show any display information for it.

Assume you forget how to create a table, try “help create table”. See what the SQLPlus displays.

If you even forget the name of command that you want to use, type “help topics”. SQLplus will show you all topics that it can provide help.

Step 3: Check what tables your have built in Oracle

Oracle maintains some system tables, when user creates an object, it automatically update these system tables. For detailed information, please check the Oracle’s manual. These tables give us a way to check what we have built in the system. It is always important to know what exists in the Database before creating new objects.

System.tab is the table that contains all objects’ name under the current user built before. So type in:

Select * from system.tab;

will list all objects (tables, views…) name.

SQL> select * from system.tab;

no rows selected

Remember: The semicolon at the end of the command is required. The difference between a sqlplus command and a sql statement is that a sql statement should finish with a semicolon.

Since I have not created anything, the returns result gives me nothing.

After getting the table’s name, “describe” command can show the definition of the table. The format is “describe objectname”.

Try “describe system.tab

Step 4: Creating tables

There are two ways to input SQL statements in SQLPlus. One is interactively input directly. The other is using a plain text file. Now I introduce the first way. The second way will be discussed later.

In SQLplus, input:

Create table student

(studentid char(4), studentname char(30), primary key (studentid));

The SQLPlus will show like this:

SQL> Create table student

(studentid char(4), studentname char(30), primary key (studentid));

2

Table created.

Now, try to build the course table and the report table. Using the sql statements below:

Create table course

(courseid char(4), coursename char(30), teachername char(30), primary key (courseid));

Create table report

(studentid char(4), courseid char(4), grade char(1), primary key (studentid,courseid) );

It is a good chance to practice Step 3 now.

Check what you have built in Oracle and show the course table’s definition.

To drop a table, simply type “ drop tablename ;”. I do not get examples here. Readers shall try themselves.

Step 5: dealing with data

The big deal is to deal with data. Now we have three tables, we want to add some data into these tables. Remember three statements”insert, delete and update”.In this step, I will show examples for each sql statements. And readers need to finish exercises I provide.

I’d like to add four students and four courses

Student :

0001 Micro

0002 Soft

0003 IMD

0004 Antel

Course

0001 Database Microsoft

0002 OS Redhat

0003 Architecture Sun

0004 AI IBM

grade

0001 0001 A

0001 0002 F

0002 0003 D

0002 0004 B

0003 0002 A

0003 0003 C

0004 0002 A

0004 0003 B

Now, type

Insert into student values ( ‘0001’, ‘Micro’);

SQLPlus will show

SQL> Insert into student values ( '0001', 'Micro');

1 row created.

Add other rows to the tables

Another way to insert records is to insert records with a query sub statement, please see the textbook for more information.

The format of delete is “ delete from tablename (where sub-statement)”. The “where sub-statement” is not necessary but powerful.

To delete all records in the student table, just input “delete from student”. However we seldom use this statement except if users want to alter table and thus delete all records first.

Example: to delete the student with student number 0001

Input:

Delete from student where studentid = ‘0001’;

SQLPlus will show

SQL> Delete from student where studentid = '0001';

1 row deleted.

Now do the following exercise:

1. delete all records in table grade

2. delete all courses that taught by Redhat

3. delete all records which contains course id “0003”

4. Restore the database after doing the exercise.

The format of update is “ update tablename set columnname = expression (where sub-statement)”. The “where sub-statement” is not necessary. If no “where sub-statement” exists, the update command will update all records and set new value to all column. Suppose teacher “Microsoft” want to teach all courses and get rid of all other teachers, type

Update course set teachername = ‘Microsoft’;

SQLPlus will show

SQL> Update course set teachername = 'Microsoft';

4 rows updated.

Try “select * from course;”

SQL> select * from course;

COUR COURSENAME TEACHERNAME

---- ------------------------------ ------------------------------

0001 database Microsoft

0002 OS Microsoft

0003 Architecture Microsoft

0004 AI Microsoft

Microsoft now is so happy that he teaches all courses.

Suppose you are teacher Sun. Now you want to get back what you teach.

Try “update course set teachername=’Sun’ where courseid=’0003’; “

Now, it is your turn to correct other teachers’ courses. Do the exercises to help IBM and Redhat correct their courses.

Step 6: Queries

Queries are done by the “select” statement. This is an important and complicated statement. I cannot totally show the statement here. Please refer to the textbook for more information. The aim of this step is to show how to input queries interactively.

Example1: Get all records from course table

Type:

select * from course;

SQLPlus will show

SQL> select * from course;

COUR COURSENAME TEACHERNAME

---- ------------------------------ ------------------------------

0001 database Microsoft

0002 OS Redhat

0003 Architecture Sun

0004 AI IBM

Try “select student.studentname, report.grade from student, report where student.studentid=report.studentid;”. Explain what this query searches.

Now finish these queries:

1. find the student’s grade whose name is Micro

2. find the teacher’s name whose course is AI

3. Find the students’ names who choose the course OS.

4. Find the teacher’s name that at least one of the students get an A in his course.

Step 7: Using Text File.

You could prepare all your SQL statements such as creation of relations and queries, into a text file and execute the SQL commands in this file when you are in SQLPLUS. Use your favorite editor to edit sql statements. If you are using a word processor such as Microsoft Word, you need to save the file as plain text. Now transfer the file to your GL home directory. The “start,@ and @@” commands can load a sql file and execute. Generally, we can use command “start” only.

Before starting using the text file ,type in “help start”.

The SQLPlus shows:

SQL> help start

START

-----

START executes the contents of a command file. The @ ("at" sign)

and @@ (double "at" sign) commands work similarly to the START

command, but do not enable the passing of values to parameters.

STA[RT] file_name[.ext] [arg ...]

For detailed information on this command, see the SQL*Plus User's

Guide and Reference.

Edit the following file and save it as “example.sql

Drop table course;

Drop table student;

Drop table report;

Create table student

(studentid char(4), studentname char(30), primary key (studentid));

Create table course

(courseid char(4), coursename char(30), teachername char(30), primary key (courseid));

Create table report

(studentid char(4), courseid char(4), grade char(1), primary key (studentid,courseid) );

Insert into student values ( ‘0001’, ‘Micro’);

Insert into student values ( ‘0002’, ‘Soft’);

Insert into student values ( ‘0003’, ‘IMD’);

Insert into student values ( ‘0004’, ‘ANTEL’);

select * from student;

Suppose now the file is in the user’s directory. In SQLPlus: type in “start example.sql

The SQLPlus will execute each command in that file.

SQL> start example.sql

Table dropped.

Table dropped.

Table dropped.

Table created.

Table created.

Table created.

1 row created.

1 row created.

1 row created.

1 row created.

STUD STUDENTNAME

---- ------------------------------

0001 Micro

0002 Soft

0003 IMD

0004 ANTEL

Now type your own file and try.

Step 8: Save outputs

The command “spool” can save all that displays in the screen, including what you input and the system returns back.

Type “spool filename” to start output

Type “spool off” to stop output.

Now do the exercise to save the output to a file called my.log

However sometimes we only want to save the sql statement we input. We do not want to save the return information.

The command “save filename” will save the last sql statement you input into the new file. If the file already exists, the old one will be deleted.

The command “save filename app” will save the last sql statement to the end of the existing file.

Now redo the exercise of step 6. First try to save four queries into four files. Then try to save four queries into one file

Step 9: Commit and Rollback

You should execute the commit command before you change your database. When you are satisfied with your work, you could save it in the database permanently by executing the commit command, or you could discard all changes you made since the last commit command by typing rollback command.

Save all changes in the database:

SQL>commit

Discard all changes made since the last commit:

SQL>rollback

Appendix A: Connect to Oracle 9 using SQLPlus (From ken clingenpeel’s email, thanks Ken)

Simply copy the oracle.profile from /usr/local/oracle to the home directory and replace 8.1.5 with 9.2.0. Then sourced this edited file, and you can use oracle 9.2.0.1.0 when loggin in remotely.

Appendix B: Code to Connect to UMBC’s Oracle and Execute SQL Statements using JDBC

import java.sql.*;

public class JdbcSample {

public static void main(String[] args) {

String userLogin = null, userPasswd = null;

if (args.length <>

System.err.println("usage :: java Test <passwd>");

System.exit(1);

}

else {

userLogin = args[0];

userPasswd = args[1];

}

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

}

catch(ClassNotFoundException ex) {

ex.printStackTrace(System.err);

System.exit(1);

}

String url = "jdbc:oracle:thin:@oracle.gl.umbc.edu:1521:GL";

Connection con = null;

try {

con = DriverManager.getConnection(url, userLogin, userPasswd);

System.out.println("Connected to Oracle.");

}

catch (SQLException se ){

System.out.println("Unable to connect to Oracle.");

se.printStackTrace();

System.exit(1);

}

System.out.println("Tables for user " + userLogin);

try {

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("select table_name from user_tables");

while ( rs.next() ) {

String name = rs.getString(1);

System.out.println(name);

}

stmt.close();

}

catch (SQLException ex ){

System.out.println("Error while executing query.");

ex.printStackTrace(System.err);

System.exit(1);

}

}

}

Convert to PDU with Didik's Package

langsung saja pada pokok bahasan qt kali ini yaitu mengkonvert suatu string ke pdu
source code:
filename: Convert2PDU.java

import javax.didik.sms.driver.Text;
import java.io.*;

public class Convert2PDU{
public static void main(String[] args)throws IOException
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Masukan No Tujuan : ");
String strNoTelp=input.readLine();
System.out.print("Masukan Pesan : ");
String strPesan=input.readLine();
String strPDU=Text.Text2PDU(strNoTelp,strPesan);
System.out.println("\nPDU Dari notelp \""+strNoTelp+"\" dan pesan \""
+ strPesan+"\" adalah\n\""+strPDU+"\"");
}
}

note:
PDU merupakan gabungan dari Nomor Telp Tujuan dengan Pesan yang Akan dikirim sehingga dalam mengkonvert string ke pdu digunakan 2 parameter yaitu NoTlp dan String Pesan.

testing Convert2PDU.java:

jalankan dengan cara :
java Convert2PDU

Masukan No Tujuan : 628999851448
Masukan Pesan : hi semuanya!!!

PDU Dari notelp "628999851448" dan pesan "hi semuanya!!!" adalah
"11000C912698995841840000AA0EE834685E6ED7C3EE7C38140A01"


untuk mendapatkan package didik silahkan kirim email ke uchiha_didik@yahoo.com

Tuesday, February 12, 2008

Basic Servlet Structure

Here's the outline of a basic servlet that handles GET requests. GET requests, for those unfamiliar with HTTP, are requests made by browsers when the user types in a URL on the address line, follows a link from a Web page, or makes an HTML form that does not specify a METHOD. Servlets can also very easily handle POST requests, which are generated when someone creates an HTML form that specifies METHOD="POST". We'll discuss that in later sections.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Use "request" to read incoming HTTP headers (e.g. cookies)
// and HTML form data (e.g. data the user entered and submitted)


// Use "response" to specify the HTTP response line and headers
// (e.g. specifying the content type, setting cookies).


PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}
}
(Download template source code -- click with the right mouse on the link or hold down SHIFT while clicking on the link.)

To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods that let you find out about incoming information such as FORM data, HTTP request headers, and the like. The HttpServletResponse has methods that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlets, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exceptions, so you are required to include them in the declaration. Also note that you have to import classes in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse). Finally, note that doGet and doPost are called by the service method, and sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request.

Wednesday, February 6, 2008

Bluecove Example

Remote Device Discovery

The LocalDevice class provides method 'getDiscoveryAgent' that returns an instance of the DiscoveryAgent. This DiscoveryAgent can then be used to discover remote bluetooth devices (start HCI inquiry).
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;

/**
* Minimal Device Discovery example.
*/
public class RemoteDeviceDiscovery {

public static final Vector/**/ devicesDiscovered = new Vector();

public static void main(String[] args) throws IOException, InterruptedException {

final Object inquiryCompletedEvent = new Object();

devicesDiscovered.clear();

DiscoveryListener listener = new DiscoveryListener() {

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
System.out.println("Device " + btDevice.getBluetoothAddress() + " found");
devicesDiscovered.addElement(btDevice);
try {
System.out.println(" name " + btDevice.getFriendlyName(false));
} catch (IOException cantGetDeviceName) {
}
}

public void inquiryCompleted(int discType) {
System.out.println("Device Inquiry completed!");
synchronized(inquiryCompletedEvent){
inquiryCompletedEvent.notifyAll();
}
}

public void serviceSearchCompleted(int transID, int respCode) {
}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
}
};

synchronized(inquiryCompletedEvent) {
boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
if (started) {
System.out.println("wait for device inquiry to complete...");
inquiryCompletedEvent.wait();
System.out.println(devicesDiscovered.size() + " device(s) found");
}
}
}

}

Services Search

The following example shows how to use the DiscoveryAgent to find OBEX Push bluetooth service. Class from DeviceDiscovery example is used to find Bluetooth Devices.
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import javax.bluetooth.*;

/**
*
* Minimal Services Search example.
*/
public class ServicesSearch {

static final UUID OBEX_FILE_TRANSFER = new UUID(0x1106);

public static final Vector/**/ serviceFound = new Vector();

public static void main(String[] args) throws IOException, InterruptedException {

// First run RemoteDeviceDiscovery and use discoved device
RemoteDeviceDiscovery.main(null);

serviceFound.clear();

UUID serviceUUID = OBEX_OBJECT_PUSH;
if ((args != null) && (args.length > 0)) {
serviceUUID = new UUID(args[0], false);
}

final Object serviceSearchCompletedEvent = new Object();

DiscoveryListener listener = new DiscoveryListener() {

public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
}

public void inquiryCompleted(int discType) {
}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i < servRecord.length; i++) {
String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
if (url == null) {
continue;
}
serviceFound.add(url);
DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
if (serviceName != null) {
System.out.println("service " + serviceName.getValue() + " found " + url);
} else {
System.out.println("service found " + url);
}
}
}

public void serviceSearchCompleted(int transID, int respCode) {
System.out.println("service search completed!");
synchronized(serviceSearchCompletedEvent){
serviceSearchCompletedEvent.notifyAll();
}
}

};

UUID[] searchUuidSet = new UUID[] { serviceUUID };
int[] attrIDs = new int[] {
0x0100 // Service name
};

for(Enumeration en = RemoteDeviceDiscovery.devicesDiscovered.elements(); en.hasMoreElements(); ) {
RemoteDevice btDevice = (RemoteDevice)en.nextElement();

synchronized(serviceSearchCompletedEvent) {
System.out.println("search services on " + btDevice.getBluetoothAddress() + " " + btDevice.getFriendlyName(false));
LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, btDevice, listener);
serviceSearchCompletedEvent.wait();
}
}

}

}

OBEX Put Client

import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.obex.*;

public class ObexPutClient {

public static void main(String[] args) throws IOException, InterruptedException {

String serverURL = null; // = "btgoep://0019639C4007:6";
if ((args != null) && (args.length > 0)) {
serverURL = args[0];
}
if (serverURL == null) {
String[] searchArgs = null;
// Connect to OBEXPutServer from examples
// searchArgs = new String[] { "11111111111111111111111111111123" };
ServicesSearch.main(searchArgs);
if (ServicesSearch.serviceFound.size() == 0) {
System.out.println("OBEX service not found");
return;
}
// Select the first service found
serverURL = (String)ServicesSearch.serviceFound.elementAt(0);
}

System.out.println("Connecting to " + serverURL);

ClientSession clientSession = (ClientSession) Connector.open(serverURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
return;
}

HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
hsOperation.setHeader(HeaderSet.TYPE, "text");

//Create PUT Operation
Operation putOperation = clientSession.put(hsOperation);

// Send some text to server
byte data[] = "Hello world!".getBytes("iso-8859-1");
OutputStream os = putOperation.openOutputStream();
os.write(data);
os.close();

putOperation.close();

clientSession.disconnect(null);

clientSession.close();
}
}

OBEX Put Server

This class will start an OBEX service that will accept Put commands and print it to standard out.
import java.io.IOException;
import java.io.InputStream;

import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.obex.*;

public class OBEXPutServer {

static final String serverUUID = "11111111111111111111111111111123";

public static void main(String[] args) throws IOException {

LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);

SessionNotifier serverConnection = (SessionNotifier) Connector.open("btgoep://localhost:"
+ serverUUID + ";name=ObexExample");

int count = 0;
while(count < 2) {
RequestHandler handler = new RequestHandler();
serverConnection.acceptAndOpen(handler);
System.out.println("Received OBEX connection " + (++count));
}
}

private static class RequestHandler extends ServerRequestHandler {

public int onPut(Operation op) {
try {
HeaderSet hs = op.getReceivedHeaders();
String name = (String) hs.getHeader(HeaderSet.NAME);
if (name != null) {
System.out.println("put name:" + name);
}

InputStream is = op.openInputStream();

StringBuffer buf = new StringBuffer();
int data;
while ((data = is.read()) != -1) {
buf.append((char) data);
}

System.out.println("got:" + buf.toString());

op.close();
return ResponseCodes.OBEX_HTTP_OK;
} catch (IOException e) {
e.printStackTrace();
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
}
}
}
}