Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Литвинов / Лабораторна робота 3.doc
Скачиваний:
30
Добавлен:
23.03.2015
Размер:
2.29 Mб
Скачать

Лабораторна робота 3.

Джерела

  1. Doug Tidwell. Programming Web Services with SOAP.

  2. Ethan Cerami. Web Services Essentials. Distributed Applications with XML-RPC, SOAP, UDDI & WSDL. Publisher: O'Reilly. 2002.

Визначення

Веб-служба (web service) - механізм який забезпечує мережевий доступ до функціональності програмного додатку на базі стандартних Інтернет технологій [1]. Тобто, якщо існує механізм, який дозволяє клієнтському додатку забезпечити зв'язок із серверним додатком на базі одного з протоколів HTTP, SMTP, XML-RPC, SOAP, такий механізм може називатись веб-сервісом.

A web service allows access to application code using standard Internet Technologies.

Web services provide an abstraction layer between the application client and the

application code

За цим визначенням, в якості веб-служб можна розглядати веб-сайти HTML.

Many Web-based systems are still organized as relatively simple client-server

architectures. The core of a Web site is formed by a process that has access to a

local file system storing documents. The simplest way to refer to a document is by

means of a reference called a Uniform Resource Locator (URL). It specifies

where a document is located, often by embedding the DNS name of its associated

server along with a file name by which the server can look up the document in its

local file system.

Наведений приклад є прикладом людино-центрованого додатку: клієнт, використовуючи браузер, задає запит, який обробляється сервісом.

The communication between a browser and Web server is standardized: they both adhere to the HyperText Transfer Protocol (HTTP).

Fundamental to the Web is that virtually all information comes in the form of

a document.

we need only two things: a way of specifying the type of an embedded document, and a way of allowing a browser to handle data of a specific type.

Each (embedded) document has an associated MIME type. MIME stands for

Multipurpose Internet Mail Exchange and, as its name suggests, was originally

developed to provide information on the content of a message body that was sent

as part of electronic mail. MIME distinguishes various types of message contents.

MIME makes a distinction between top-level types and subtypes: text, image, video.

For each top-level type, there may be several subtypes available.

Many subtypes are experimental, meaning that a special format is used requiring its own application at the user' s side. In practice, it is the Web server who will provide this application, either as a separate program that will run aside a browser, or a plugin that can be installed as part of the browser. The variety of document types forces browsers to be extensible.

There is a special application type that indicates that the document

contains data that are related to a specific application.

The multipart type is used for composite documents, that is, documents that

consists of several parts where each part will again have its own associated toplevel

type.

The combination of HTML (or any other markup language such as XML) with scripting provides a powerful means for expressing documents.

One of the first enhancements to the basic architecture was support for simple user interaction by means of the Common Gateway Interface or simply CGI.

CGI defines a standard way by which a Web server can execute a program taking user data as input. Usually, user data come from an HTML form; it specifies the program that is to be executed at the server side, along with parameter values that are filled in by the user. Once the form has been completed, the program's name and collected parameter values are sent to the server

When the server sees the request it starts the program named in the request

and passes it the parameter values. After processing the data, the program generates a document and returns that document to the server. The server will then pass the document to the client.

It appears as if it is asking the CGI program to fetch a document.

Прикладом [http://www.cgi101.com/book/ch4/text.html]

<html><head><title>Guestbook Form</title></head>

<body>

<form action="post.cgi" method="POST">

Your Name: <input type="text" name="name"><br>

Email Address: <input type="text" name="email"><br>

Comments:<br>

<textarea name="comments" rows="5"

cols="60"></textarea><br>

<input type="submit" value="Send">

</form>

</body>

</html>

CGI script

#!/usr/bin/perl -wT

use CGI qw(:standard);

use CGI::Carp qw(warningsToBrowser fatalsToBrowser);

use strict;

print header;

print start_html("Thank You");

print h2("Thank You");

my %form;

foreach my $p (param()) {

$form{$p} = param($p);

print "$p = $form{$p}<br>\n";

}

print end_html;

На сервере, где находится ваш сайт, должно быть разрешено выполнение cgi-скриптов. Дело в том, что скрипт, как и любая другая программа, может выполнять системные команды на сервере, что представляет потенциальную угрозу безопасности.[ http://www.cgi101.com/book/] [http://www.west-wind.com/WebLog/posts/1143.aspx]

Next important enhancements is that servers can also process a document

- before passing it to the client.

A document may contain a server-side script, which is executed by the server when the document has been fetched locally.

The result of executing a script is sent along with the rest of the document

to the client. The script itself is not sent. Server-side script changes a document by essentially replacing the script with the results of its execution.

As server-side processing of Web documents increasingly requires more flexibility, it should come as no surprise that many Web sites are now organized as a three-tiered architecture consisting of a Web server, an application server, and a database.

For example, a server may accept a customer's query, search its database of matching products, and then construct a clickable Web page listing the products found. In many cases the server is responsible for running Java programs, called servlets, that maintain things like shopping carts, implement recommendations, keep lists of favorite items, and so on.

Сьогодні, як правило, це поняття пов’язане з виконанням віддалених функцій(методів) з використанням XML повідомлень (XML messaging). Тобто підкреслюється центральна роль додатку на відміну від користувача. Важливим мотивом до створення стало широке розповсюдження веб-орієнтованих систем, які надають загальні сервіси без безпосередньої участі користувачів.

There is a rapidly growing group of Web-based systems that are offering general services to remote applications without immediate interactions from end users. This organization leads to the concept of Web services [Troelson].

Так, сервіси рівню додатка – механізми публікації, управління, пошуку та вибірки контенту, доступ до яких здійснюється на базі протоколів HTTP та HTML, клієнтські додатки – веб-браузери (web browsers), які понімають ці стандарти можуть зв’язуватися з сервісами. При цьому, такий зв'язок не залежить від платформ(cross-platform interoperability), на базі яких функціонують додатки, бо взаємодія здійснується на рівні протоколів.

A web service is any service that is available over the Internet, uses a standardized XML messaging system, and is not tied to any one operating system or programming language[2].

What makes a Web service special is that it adheres to a collection of standards that will allow it to be discovered and accessed over the Internet by client applications that follow those standards as well[Troelson].

The basic idea is that some client application can call upon the services as provided by a server application.

Note that this principle is no different from what is needed to realize a remote procedure call.

An important component in the Web services architecture is formed by a directory service storing service descriptions.

This service adheres to the Universal Description, Discovery and Integration standard (UDDI). As its name suggests, UDOr prescribes the layout of a database containing service descriptions that will allow Web service clients to browse for relevant services.

Services are described by means of the Web Services Definition Language

(WSDL) which is a formal language very much the same as the interface definition languages used to support RPC-based communication. A WSDL description contains the precise definitions of the interfaces provided by a service, that is, procedure specification, data types, the (logical) location of services, etc.

An important issue of a WSDL description is that can be automatically translated to .clientside and server-side stubs, again, analogous to the generation of stubs in ordinary RPC-based systems

[http://www.codeproject.com/KB/IP/rpcintro1.aspx][ http://msdn.microsoft.com/en-us/library/aa379010(VS.85).aspx][ http://msdn.microsoft.com/en-us/library/aa645736(VS.71).aspx].

Идея вызова удаленных процедур (Remote Procedure Call - RPC) состоит в расширении хорошо известного и понятного механизма передачи управления и данных внутри программы, выполняющейся на одной машине, на передачу управления и данных через сеть. Средства удаленного вызова процедур предназначены для облегчения организации распределенных вычислений. Наибольшая эффективность использования RPC достигается в тех приложениях, в которых существует интерактивная связь между удаленными компонентами с небольшим временем ответов и относительно малым количеством передаваемых данных. Такие приложения называются RPC-ориентированными.

Характерными чертами вызова локальных процедур являются:

  • Асимметричность, то есть одна из взаимодействующих сторон является инициатором;

  • Синхронность, то есть выполнение вызывающей процедуры при останавливается с момента выдачи запроса и возобновляется только после возврата из вызываемой процедуры.

Finally, a core element of a Web service is the specification of how communication takes place. To this end, the Simple Object Access Protocol (SOAP) is used, which is essentially a framework in which much of the communication between two processes can be standardized.

  • Used in conjunction with UDDI registry

  • Provides a normalized description of heterogeneous applications.

    Додаткові характеристики веб-сервісу:

    · A web service should be self-describing. Якщо публікується нового веб-сервіса, потрібна публікація також і інтерфейсу до цього сервісу. Наприклад, якщо при створенні сервісу використовується протокол SOAP, то до нього додається інтерфейс також написаний на базі XML, який визначає всі відкриті методи, аргументи, результати.

    · A web service should be discoverable. Тобто у разі створення сервісу має бути простий механізм публікації цього факту що забезпечує знайдення цього сервісу зацікавленими сторонами(сервісами або додатками). Такий механізм може бути створений на базі централізованого або децентралізованого реєстру.

    Сумарне визначення веб-сервіса:

    · Доступний через мережі Internet або intranet

    · Використовує стандартну систему XML повідомлень

    · Не зв’язаний з певною операційною системою або мовою програмування

    · Має надавати описання інтерфейсу на базі XML

    · Має бути знайдений на базі простого механізму публікації та пошуку сервісів.

    Мотивація

    У разі існування сервісів які можуть бути легко знайдені, з описаними інтерфейсами та відповідають стандартам з’являється можливість автоматизації інтеграції додатків ("just-intime" application integration).

    Схема роботи системи при цьому виглядає наступним чином:

    1. Додаток ініціює пошук необхідного сервісу(наприклад, сервісу певної компанії) в централізованій директорії веб-сервісів. Директорія повертає інформацію по сервісу, яка включає вказівник на місце, де розташоване описання сервісу(інтерфейс) .

    2. Додаток зв'язується з сервісом компанії та отримує його описання.

    3. Керуючись описанням додаток створює запит необхідної функції.

    На сучасний момент автоматизованими можуть бути шаги: отримання набору сервісів з централізованого реєстру, робота з сервісом на базі його описання. Але автоматизація вибору сервісу лишається за людиною.

    І якщо навіть всі ці шаги будуть автоматизовані лишається проблема автоматизації бізнес зв’язків (business relationships).

    Наприклад, опис сервісу не гарантує правильність вибору цінової політики, що логіка сервісу не помилкова і що сервіс завжди доступний до використання. Таким чином, повна версія автоматизації інтеграції додатків не може бути здійснена, а сучасна технологія веб-сервісів дозоляє автоматизувати цей процес частково.

    The Industry Landscape

    На ринку систем розробки веб-сервісів існує три основних суперника:

    Microsoft's .NET, IBM Web Services, Sun Open Net Environment (ONE).

    Незважаючи на ряд особливостей ці системи підтримують загальний набір технологій таких як SOAP, WSDL, UDDI.

    Web Service Architecture

    Погляд на архітектуру веб-сервісів може бути здійснений з двух боків: з точки зору ролей та стеку протоколів.

    Web Service Roles

    Три основні ролі в веб-сервісної архітектури:

    Service provider. Провайдер веб-сервіса. Провайдер забезпечує виконання сервісу та забезпечує доступ через Інтернет.

    Service requestor. Споживач сервісу (consumer of the web service). Споживач використовує сервіс шляхом зєднання та передачі XML-запиту.

    Service registry. Централізована дерікторія сервісов(реєстр сервісов). Реєстр дозволяє розробникам публікацію нових та пошук існуючих сервісів.

    Web Service Protocol Stack

    Існуючий стек протоколів містить чотири основних шара: .

    Service transport. Відповідає за передачу повідомлень між додатками. Включає: hypertext transfer protocol (HTTP), Simple Mail Transfer Protocol (SMTP), file transfer protocol (FTP), Blocks Extensible Exchange Protocol (BEEP).