Статьи

Начало работы с «Программное обеспечение как услуга»

«Программное обеспечение как услуга» (SaaS) — все более популярная модель для обеспечения функциональности программного обеспечения, поскольку она экономична с точки зрения как стоимости, так и клиентских аппаратных ресурсов. Команда NetBeans создала Диспетчер веб-служб в IDE NetBeans 6.1 для поддержки приложений SaaS, упрощая для разработчиков Java доступ ко всем популярным службам SaaS в Интернете.

Примечание автора: эта статья основана на работе, выполненной Питером Лю из Sun Microsystems.

 

Что такое SaaS?

«Программное обеспечение как услуга» относится к модели доставки программного приложения, в которой поставщик программного обеспечения разрабатывает веб-приложение и размещает и использует приложение для использования своими клиентами через Интернет. Клиенты платят не за собственное программное обеспечение, а за его использование. Они используют его через API, доступный через Интернет, обычно через SOAP или веб-сервисы RESTful.

Что такое диспетчер веб-служб NetBeans?

Диспетчер веб-служб NetBeans — это значительно расширенный набор функций, добавленный к знакомому узлу веб-служб на вкладке Сервисы среды IDE. Он заменяет палитру для веб-служб RESTful, но это только часть функциональных возможностей диспетчера веб-служб. Вы можете перетаскивать операции в код, просматривать API и просматривать файлы WADL. Web Services Manager содержит большое количество 3 — й партии SaaS услуг, в том числе Amazon, Delicious, Flickr, Google и Yahoo.

Функциональность менеджера веб-сервисов

Диспетчер веб-служб предоставляет следующие функции:

  • Может отображать как службы на основе WSDL (StrikeIron, GoogleAdSense), так и службы RESTful на основе WADL (Amazon S3, Flickr и т. Д.).

  • Позволяет вам перетаскивать (DnD) операции из сервисов в код. Среда IDE генерирует весь код подключения для доступа к сервису, когда вы выполняете операцию.

  • Предоставляет ссылку на документацию API сервиса. Выберите View API Document в контекстном меню узла службы, и API откроется в окне браузера.

  • Открывает WADL службы, когда она существует. Нажмите View WADL в контекстном меню узла службы, и WADL откроется в редакторе IDE. WADL — это простая альтернатива WSDL для использования с веб-приложениями XML / HTTP. См. Https://wadl.dev.java.net/ для получения дополнительной информации о проекте Java net WADL.

  • Поддерживает генерацию кода ресурсов POJO, сервлетов, JSP и RESTful. PHP, Ruby, JavaScript и другие языки будут поддерживаться в будущем.

  • Автоматически создает URL-адреса для созданных пользователем элементов. В сервисе Amazon S3 Bucket URL для getBucket имеет вид {bucket} .s3.amazonaws.com, где {bucket} — это имя, которое пользователь дает корзине. Например, если пользователь называет корзину myphotobucket, сгенерированный URL-адрес getBucket будет myphotobucket.s3.amazonaws.com. Аналогично, URL-адрес для getObject — {bucket} .s3.amazonaws.com / {object}, где {object} — это имя, которое пользователь указывает в коде для объекта, и объединяется с URL-адресом для getBucket. Продолжить с В предыдущем примере, если этот пользователь называет объект mypicture.jpg, URL для соответствующего getObject — это myphotobucket.s3.amazonaws.com/mypicture.jpg.

  • Поддерживает следующие механизмы безопасности:

    • Ключ API

    • HTTP Basic

    • Подпись заголовка

    • Логин пользователя

Механизмы аутентификации

API Key (Google, Zillow, Yahoo, etc)
The API key is passed as a query parameter on every API call. The purpose of this scheme is to track the usage of the API, and not for securing communication. This is suitable for services whose data is public to everyone.

From the developers perspective, this is the simplest scheme to support since all you need to do is append the key as a query parameter.

HTTP Basic Authentication (Delicious, Twitter)
This scheme allows a web browser or a client program to provide credentials in the form of a user name and password. The advantage of this scheme is that it is support by all browsers. The disadvantage is that the password is transmitted in plain text.

From the developers perspective, this is also a very simple scheme to implement. Your application can either prompt the user for the password or use a default password for application-based security.

Header Signing (Amazon S3)
This scheme requires a public key and a secret key. Here is how it works:

First, create a string in base64 encoding by concatenating the public key with information in the HTTP request header, e.g. request method, request URL, date, etc. You then create a signature of the string using the SHA1-HMAC algorithm and the secret key. The signature is then added to the request header.
This scheme is mainly used for application-based security. The application is still responsible for authenticating the users of the application using other schemes.

From the developer’s perspective, this scheme is very complicated to implement. You need to write specialized code to perform the authentication.

User Login (Facebook, Flickr)
The scheme requires the application to redirect the user to a login page on the Facebook or Flickr website. This is how this scheme works for Facebook:
First, the application developer needs to register the application with Facebook to get an API key and a secret key. Every method call to Facebook needs to be signed using the secret key.

During the login process, the application first calls Facebook to request a token using the API key. Next, the user is redirected to a login URL constructed from the API key and the token. This URL takes the user to a login page on Facebook. After the user logs into Facebook and authorizes the application to call Facebook on his/her behalf, the application sends back a session key and a session secret key. From them on, all API calls must pass the session key and be signed using the session secret key.

The authentication scheme is very secure and allows the user to grant and revoke access to the application. The disadvantage is that it is very complicated and is not suitable for machine-to-machine communication.

 


Example: Amazon S3 Buckets Service

Amazon S3 is a web-based storage service that can be used to store and retrieve any amount of data. The underlying infrastructure is the same that Amazon uses for its own network of web sites. Developers can access Amazon S3 through a simple RESTful web service interface. They can upload, download and delete objects of up to 5 GB and store an unlimited number of such objects. The default download protocol is HTTP, but BitTorrent is also supported. Authentication is provided by a Header Signing mechanism, which involves a public key and a secret key. The Amazon account owner can make individual objects public or private and grant rights to individual users.

To use Amazon S3 Buckets, go to http://www.amazon.com/gp/browse.html?node=16427261 and sign up for an access key and a secret key. You’ll have to pay for this by credit card but it is not expensive.

In our example, we use the Amazon S3 Buckets Service to store and retrieve the Creek.jpg photo. First, we create a Web Application project. In that project, we create three servlets, CreateBucketServlet, GetPhotoServlet, and PutPhotoServlet. In each servlet, we delete the method body of the processRequest(request, response) method. Then in the Services tab, we go to the Amazon -> Simple Storage Service -> S3 Bucket Service and expand {bucket}.s3.amazonaws.com -> {object}/

Under the {bucket} node, we drag and drop createBucket into the empty processRequest method body of the CreateBucketServlet. A dialog opens in which we set the default name of the bucket. The bucket name must be globally unique and in lower case. You may want to prepend your name or company name, such as org-netbeans-photobucket, to insure uniqueness. If you use a non-unique bucket name, you will receive an «Access Denied» error message in your server log. (The name «myphotobucket» in the example will not work, because we created a bucket with that name in the process of writing this article!)

When we click OK, the following code is generated in the CreateBucketServlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String bucket = "myphotobucket";

RestResponse result = S3BucketsService.createBucket(bucket, contentType, content);
//TODO - Uncomment the print Statement below to print result.
//out.println("The SaasService returned: "+result.getDataAsString());
} catch (Exception ex) {
ex.printStackTrace();
}

}

The IDE generates the following classes in the project:

  • RestConnection – A wrapper around HttpUrlConnection

  • RestResponse – A wrapper for the HTTP response

  • AmazonS3BucketsServiceAuthenticator – A class that signs the Amazon header

  • amazons3bucketsserviceauthenticator.properties – A properties file that stores the access key and secret key

  • AmazonS3BucketsService – A service wrapper containing the wrapper methods that uses RestConnection to make calls to the Amazon S3 service.

Next, under the {object}/ node, we drag and drop the putObject method into the empty processRequest method
body of the PutPhotoServlet. A dialog opens in which we can specify the type of content we’re passing along with the bucket and object names.

When we click OK, the IDE inserts the RestResponse.putObject method into the S3BucketsService, and the
following code into the processRequest method body of PutPhotoServlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String bucket = "myphotobucket";
String object = "Creek.jpg";
String contentType = "image/jpeg";
java.io.InputStream=null;

RestResponse result = AmazonS3BucketsService.putObject(bucket, object, contentType, content);
//TODO - Uncomment the print Statement below to print result.
//out.println("The SaasService returned: "+result.getDataAsString());
} catch (Exception ex) {
ex.printStackTrace();
}
}

In order for the servlet to put our Creek.jpg file in the bucket, we replace java.io.InputStream=null; with the following code:

// Load the Creek.jpg image to be stored on Amazon S3.
java.io.InputStream content = getServletContext().getResourceAsStream(object);

Next we drag and drop the getObject method into the empty processRequest method body of the GetPhotoServlet. The following dialog opens, in which we specify the bucket and object names.

When we click OK, the IDE inserts the RestResponse.getObject method into the S3BucketsService, and the
following code into the processRequest method body of the GetPhotoServlet. We have manually added some additional code, lines 12-15 below, to set the content type for the response and write the return image data into the response’s output stream. We also added an import statement for java.io.OutputStream.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String bucket = "myphotobucket";
String object = "Creek.jpg";

RestResponse result = AmazonS3BucketsService.getObject(bucket, object);
//TODO - Uncomment the print Statement below to print result.
//out.println("The SaasService returned: "+result.getDataAsString());

// Add this to set the content type for the response and
// write the return image data into the response’s output stream.
response.setContentType(result.getContentType());
OutputStream os = response.getOutputStream();
os.write(result.getDataAsByteArray());
os.close();

} catch (Exception ex) {
ex.printStackTrace();
}
}

Now we need to make some changes to the project so that it will run and will put a picture in the Amazon bucket:

  • In each servlet’s processRequest method body, make sure that the bucket and object values correspond
    to our bucket name and photo file and that the content type, if present, is image/jpeg.

Now we can deploy and run the project. Run each servlet by right-clicking on the servlet’s file node and selecting Run File from the context menu. First we run CreateBucketServlet, then PutPhotoServlet, then GetPhotoServlet. At the end, our picture appears in a browser window. Success!

Summary

This article is an introduction to «Software as a Service» and the Web Services Manager, which is a new interface for using SaaS functionality in your NetBeans IDE projects. We explained what Software as a Service is and gave you a brief tour of the Web Service Manager and its functionality. You could also read a description of the authentication mechanisms that the Web Service Manager supports. Lastly, we provided an example of a Web Application project using the Amazon S3 Buckets Service and three servlets to create a bucket for storing photos, save a photo to the bucket, and get a photo back from the bucket.