Using Google Search API from Java

April 25th, 2008 vira Posted in Computer science 4 Comments »

Recently I’ve discovered ability to search in Google from Java program in a way different from brute “crawling”.

And I’ve found out two options:

Google SOAP API

With this API you can issue search requests to Google’s index of billions of web pages and receive results as structured data, access information in the Google cache, and check the spelling of words. Google SOAP Search API is implemented as a web service and all you need is just get WSDL and call remote methods through SOAP protocol. Usage of this service is limited to 1000 requests per day.

But as you can read on SOAP API site

As of December 5, 2006, we are no longer issuing new API keys for the SOAP Search API. Developers with existing SOAP Search API keys will not be affected.

So you aren’t able to get API key (I found the old one in Internet).
And Google encourages you to use the AJAX Search API, which is described below.

Example of code that perform search request and show obtained results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import com.google.soap.search.*;
import java.io.*;
 
public class SimpleGoogleDemo {
 
  public static void main(String[] args) {
 
    // Create a Google Search object, set our authorization key
    GoogleSearch s = new GoogleSearch();
    String clientKey="xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    s.setKey(clientKey);
    s.setQueryString("vera.org.ua");
    GoogleSearchResult result = null;
    // Depending on user input, do search or cache query, then print out result
    try {
 
      	result = s.doSearch();
 
    }
    catch (GoogleSearchFault f) {
      System.out.println("The call to the Google Web APIs failed:");
      System.out.println(f.toString());
    }
 
    // if we made it here, the search went through
    System.out.println("Google Search Results:");
    System.out.println("======================");
    if (result!= null)
	    System.out.println(result.toString());
  }
 
}

To run this code you need to have googleapi.jar in your classpath. This jar file contains very useful and easy-to-use class com.google.soap.search.GoogleSearch, which does all search work.

Google AJAX API

Usage of this unlimited and you can make as many request as you want.
Despite the fact that Google in this API FAQ say “The Google AJAX Search API is currently available only for websites.” ability to use it exists :-)

Example of code that perform search request and show obtained results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.io.*;
import java.net.*;
 
public class GoogleAJAXSearchAPI {
    private static String endpointURL = "http://www.google.com/uds/GwebSearch?"+
          "callback=GwebSearch.Raw" +
          "Completion&context=0&lstkp=0&rsz=small&hl=en&" +
          "sig=8656f49c146c5220e273d16b4b6978b2&q=vera.org.ua&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxx&v=1.0";
 
    public static void main(String[] args) throws Exception {
        URLConnection uc = new URL(endpointURL).openConnection();
        HttpURLConnection connection = (HttpURLConnection) uc;
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.connect();
 
        String line;
        InputStream inputStream = null;
        try {
            inputStream = connection.getInputStream();
        } catch (IOException e) {
            inputStream = connection.getErrorStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    }
}

To run this code you just need to get API key here.
So, have fun :)

AddThis Social Bookmark Button

Mac Tips: Mac OS X+DosBox+TASM=true dos development in assembler environment

October 24th, 2007 vira Posted in Computer science 2 Comments »

Что-то моя “формула счастья” усложняется :-) - после (Mac+Cord=remote Win)

Возникла задача делать лабы по асму для х86-го на моем Маке. Вначале думала найти родную cреду для МакОС, но так сразу не нашлось :( И потом вспомнила про старый-добрый TASM, который можно было бы запустить под эмулятором DOS-a. И вышло )

В качестве эмулятора выбран DosBox - An open source DOS emulator for BeOS, Linux, Mac OS X, OS/2, and Windows. Ну и TASM ) После стандартной установки DosBox-a и его запуска необходимо примонтировать директорию, в которую заранее необходимо скопировать установщик TASM-a. В моем случае команда имела вид: mount c ~/dos

Установка TASM-a правда успешно до конца не дошла ( и пришлось доустановить нужные его части, что сделать довольно таки просто. Например, для установки отладчика просто нужно распаковать tddos.pak командой unpak.exe xl tddos.pak c:\tasm\bin. Правда вполне возможно, что такая проблема возникла только у меня.

Итак, мы сделали все, чтобы работать в полноценной среде, для разработки программ на ассемблере под дос. Править исходные файлы можно в любимом текстовом редакторе под MacOS, а дальше tasm.exe prog.asm, tlink.exe /v prog.obj и наконец td.exe prog.exe

Так выглядит запущенный отладчик:

td_dosbox

Только ресурсов этот эмулятор ест - уджас просто

AddThis Social Bookmark Button

Семинар от IBM на тему безопасности J2EE приложений

October 22nd, 2007 vira Posted in Computer science No Comments »

Очередной семинар в Киеве - на этот раз от IBM (на их семинарах я еще не была :)

“Решения IBM для построение защищенной ИТ-инфраструктуры”

Когда? 6 ноября 2007, с 10 до 15

Где? Украина, Киев, ул. Богдана Хмельницкого, д. 53, отель “Опера”, зал “Симфония”

Registration and details

AddThis Social Bookmark Button

Internet works - help to find Steve Fossett

September 10th, 2007 vira Posted in Computer science, internet No Comments »

3-го вересня зник на своєму літаку Стів Фоссет - людина, що встановила багато світових рекордів, при чому у різних видах змагань. Це сумна подія і сподіваюсь, що його знайдуть. Але питання не в цьому. Подібний пост йому не допоможе.Цікавим є метод пошуку. Кожен користувач Інтернету може допомогти знайти Стіва Фоссета аналізуючи супутникові знімки на предмет об’єктів, що схожі на його літак. Цю акцію підтримує Гугл та Амазон. При чому кількість розглянутих знімків стрімко зменшується - швидкість по моїм оцінкам складає приблизно 5 зображень за 1 сек.Якщо це спрацює, то людство матиме цікравий приклад застосування Інтернету для такого важливого завдання як пошук людей. Звичайно ж і раніш таке робилося, але до цього не заохочувались звичайні користувачі Інтернету, які представлють собою величезні за розміром людські ресурси.

AddThis Social Bookmark Button

Java tips: get last inserted autoincrement fields

September 6th, 2007 vira Posted in Computer science No Comments »

To get last inserted autoincrement fields using JDBC you should write something like this:

ResultSet resultSet = statement.getGeneratedKeys();
int newId=0;
if ( resultSet != null && resultSet.next() )
{
newId = resultSet.getInt(1);
}

And don’t forget to add Statement.RETURN_GENERATED_KEYS parameter when create statement.

AddThis Social Bookmark Button

Another one )

July 3rd, 2007 vira Posted in Computer science No Comments »

Today I’ve got another one certificate )))

AddThis Social Bookmark Button

Yellow Belt - one small step in obtaining the BlackBelt

June 16th, 2007 vira Posted in Computer science 1 Comment »

Отримано жовтий пояс з Java-технологій ) Після початкового білого це вже щось.
Можливість відчути себе якимось каратистами програмістам дає спільнота http://www.javablackbelt.com/. Самий топовий пояс - чорний, і на 17.06.07 його ще ніхто не отримав. Може то й не реально ;)

Але враховуючи те, що мені жовтий колір більше до вподоби, то мені чорного пояса не треба )

P.S. І ще я можу протягом 24-х годин хизуватися тим, що є на першій сторінці їх сайту, про що вони сповістили мене при отриманні пояса.

Жовтий по�?�?

AddThis Social Bookmark Button

Always open. Now free

November 13th, 2006 vira Posted in Computer science 1 Comment »

“Sun started a revolution with Java technology 10 years ago. With a free runtime, an open specification, and a platform-independent promise of compatibility, Java technology became a gold standard in embedded devices, mobile phones, on the desktop and within the enterprise. Now, in 2006, Sun is open sourcing its implementations of Java technology as Free/Libre software.”

Official information

AddThis Social Bookmark Button

Google Personalized Home

November 13th, 2006 vira Posted in Computer science No Comments »

Today I’ve been surprised (once more) at Google personalized home page. It’s a great thing. You can open only one page and see a lot of information you are interested in. I didn’t know about this possibility earlier because there isn’t a link to it on Google.com.ua :-(

I saw this link on Google in english

AddThis Social Bookmark Button