Hospedagem Profissional

Hospedagem Profissional
Clique aqui e ganhe US$ 10,00 para testar durante 1 mês a melhor hospedagem: Digital Ocean!

quinta-feira, 26 de março de 2009

O Google Chart traça gráficos para você

chart

A interface de programação do Google Charts permite a criação de gráficos diretamente na URL
Para webmasters e para quem precisa de um gráfico rápido, mas não tem uma planilha ou outro programa apropriado à mão, o Google traz uma solução. A interface de programação do Google Charts permite a criação de gráficos diretamente na URL. Para isso, vamos usar o exemplo a seguir:

http://chart.apis.google.com/chart?cht=p3&chd=s:Uf9a&chs=250x100&chl=January|February|March|April

Em cht=, colocamos o tipo de gráfico, com p3 indicando uma pizza. Os valores depois de chd=t: indicam os dados do gráfico (veja os tipos em http://code.google.com/intl/pt-BR/apis/chart/types.html).

Os números após chs= mostram o tamanho da imagem a ser gerada e, por fim, os textos depois de chl= trazem as legendas de cada dado (em ordem).

Ao abrir essa URL, o Google devolve o gráfico prontinho, em formato PNG.

Por Eric Costa
em http://info.abril.com.br/dicas/sites/webdesign/o-google-chart-traca-graficos-para-voce.shtml

Creating a Graphical Client for Twitter

In this tutorial, you use the NetBeans IDE to create a simple, graphical, REST-based client that displays Twitter public timeline messages and lets you view and update your Twitter status. The application uses Swing and NetBeans IDE's support for Twitter's SaaS operations.

Running client displaying Twitter messages

If you do not have a Twitter account, go to twitter.com and create an account before proceeding with this tutorial.

A complete sample of this application is available for download.

Click here to download the full sample.

Contents

Content on this page applies to NetBeans IDE 6.5

  • Designing the JFrame
  • Showing Your User Status
  • Setting Up Twitter Authentication
  • Adding the updateStatus Operation
  • Displaying Usernames and Statuses in the JFrame
    • Creating a TimerTask
    • Adding a run Method With the getPublicTimeline Operation
    • Creating a List Cell Rendering Component
    • Displaying the Component in TwitterJFrame

To complete this tutorial, you need the following software and resources.

Software or Resource
Version Required

NetBeans IDE
Java download bundle, Version 6.5

Java Development Kit (JDK)
Version 6 or version 5

User name and password for a Twitter account

Designing the JFrame

In this step you create the GUI elements that will display the Twitter public timeline, your user icon, and where you read and update your status. The GUI elements are all wrapped in a JFrame. You do not have to lay out the GUI elements exactly as described in this section. This layout is a suggestion only. For example, you may add more functionality. However you need to create at least all the elements described in this tutorial.

To design the JFrame:

  1. Choose File > New Project. The New Project wizard opens. Select the Java category, then a Java Application project. Click Next.
  2. Name the project TwitterSwingClient. Select a Project Location. Unselect Create Main Class. (The JFrame will be the main class.) Click Finish.
    New Project wizard showing fields for creating the TwitterSwingClient project
  3. The IDE creates the TwitterSwingClient project, which appears in the Projects window. Right-click the TwitterSwingClient project node and choose New > JFrame Form (or New > Other > Swing GUI Forms > JFrame Form). The New JFrame Form wizard opens.
  4. Name the form TwitterJFrame and create a package for it called twitterclient. Click Finish.
    New JFrame Form wizard showing fields for creating TwitterJFrame
  5. The IDE opens TwitterJFrame in the editor, in the Design view. Here you have a palette of all the Swing components you can drag and drop into the JFrame.
    Twitter J Frame in the Design view of the Editor
  6. Click on the Button icon under Swing Controls in the Palette. Drag and drop it into the bottom right corner of the JFrame. Note that the button displays jButton1, which is the name of this JButton object.
    JFrame showing newly added jButton1
  7. Right-click jButton1 and select Edit Text from the context menu. Change the display text to "Update."
  8. Drag and drop a Label (jLabel1) to the bottom left corner of the JFrame. Change its display text to "Icon." Your user icon will be displayed in this label.
  9. Drag and drop a Text Field (jTextField1) between the Label and the Button. Change its display text to "Status." Click on the right border of the text field and stretch it across towards the button. Blue guidelines appear showing you suggested distances from the button.
  10. Right-click on jLabel1 and select Properties from the context menu. The jLabel1 Properties dialog opens. Set the labelFor property to point to jTextField1. (This increases accessibility.)
  11. Find the properties Maximum Size, Minimum Size, and Preferred Size. Set each of these properties to [48,48], to match the 48px X 48px dimensions of Twitter icons.
    Properties of j Label 1 in Twitter J Frame, showing Maximum, Minimum, and Preferred sizes set to 48, 48
  12. Drag and drop a Scroll Pane into the upper part of the JFrame. Drag its borders to expand it to fill most or all of the space above the text field and button. (You may leave a margin if you want to add more functionality later, such as the menu in the sample.)
  13. Drag and drop a List into the Scroll Pane. A sample list of items appears. Save TwitterJFrame. The JFrame should look like the following image:
    Twitter J Frame in the Design view, with all basic GUI elements

You now have all the basic GUI components for the Swing client. It is time to add the first Twitter SaaS (Software as a Service) operation.

Showing Your User Status

In this section you create a new method and add the Twitter getUserTimeline operation to this method. The getUserTimeline operation gets your user icon and your current status. You then add code to the method to display your icon and status in jLabel1 and jTextField, respectively. Finally you add a line to the JFrame's constructor to initialize the method.

To show your user status:

  1. Switch to the Source view of TwitterJFrame.
  2. In the code, add a few empty lines above the main method.
    Code of Twitter J Frame showing empty lines added above main method
  3. In the empty space, type in the following code to create the method initUserInfo.
    private void initUserInfo() {


    }



  4. Open the Services window in the IDE. Under Web Services, navigate to Twitter > What Are You Doing Service > [statuses] > [user_timeline.{format}] > getUserTimeline.

    Services window with Web Services tree showing Twitter getUserTimelineById operation chosen


  5. Drag and drop getUserTimeline into the method body of initUserInfo. The Customize GET SaaS Service dialog opens. Type "1" for the value of count, because you only want to see the last status message. Exit the value cell for count and click OK. (If you do not exit the cell before you click OK, your change will not be saved. Alternatively, you can change the value of count in the code.)


    Properties dialog for get User Timeline operation


  6. The IDE generates code for the getUserStatusById operation. The IDE also creates the org.netbeans.saas package, which contains the RESTful communication code, and the org.netbeans.saas.twitter package, which contains the authenticaton code and the Twitter WhatAreYouDoingService class. The IDE adds an import statement for this class to TwitterJFrame.

    Note: In the Sample, objects and variables in this method such as format and result are numbered format2, result2, etc, because the getUserTimeline code was added after the getPublicTimeline code.



    private void initUserInfo() {

    try {
    String since = null;
    String sinceId = null;
    String page = null;
    String count = "1";
    String format = "xml";

    RestResponse result = TwitterWhatAreYouDoingService.getUserTimeline(since, sinceId, page, count, format);
    if (result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses resultObj = result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    } else if (result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.NilClasses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.NilClasses) {
    twitter.whatareyoudoingservice.twitterresponse.NilClasses resultObj = result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.NilClasses.class);
    }
    //TODO - Uncomment the print Statement below to print result.
    //System.out.println("The SaasService returned: "+result.getDataAsString());
    } catch (Exception ex) {
    ex.printStackTrace();
    }

    }



  7. In the generated code, locate the if block.

    if (result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses resultObj = result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    }



  8. At the end of the if block, insert code that gets your user status text and icon URL and uses this data to display your status in jTextField1 and jLabel1.

    if (result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses){
    twitter.whatareyoudoingservice.twitterresponse.Statuses resultObj = result.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    StatusType st = resultObj.getStatus().get(0);
    jTextField1.setText(st.getText().trim());
    UserType user = st.getUser();
    String iconSrc = user.getProfileImageUrl();
    URL iconUrl = new URL(iconSrc);
    ImageIcon icon = new ImageIcon(iconUrl, user.getScreenName());
    jLabel1.setIcon(icon);

    }



  9. Press Ctrl-Shift-I to add import statements. A dialog opens with a choice of URL classes to import. Select the default, java.net.URL.


  10. At the top of the TwitterJFrame class, locate the constructor. Add the line initUserInfo(); to the constructor's body.

    public class TwitterJFrame extends javax.swing.JFrame {

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    initComponents();
    initUserInfo();
    }




After you set up authentication, you can run the project. Right-click the project node and select Run from the context menu. An application opens showing your user icon and status.



Running application, showing user icon and status



Setting Up Twitter Authentication




There are two ways you can set up your application to log into Twitter:








To set up automatic login, open org.netbeans.saas.twitter.twitterwhatareyoudoingserviceauthenticator.properties. Type in your username and password and save the file.



Setting the authentication credentials in the authenticator properties file



If you do not set up these properties, a preconfigured login screen appears when you run the application.





Warning: On Windows XP and linux, there are problems rendering the preconfigured login screen. To work around this problem, either set up automatic login or use an alternative login screen. An alternative login screen is provided in the sample. To use the alternative login screen:




  1. Copy the sample's twitterclient.AuthDialog.java to your own twitterclient package.


  2. Replace your version of org.netbeans.saas.twitter.TwitterWhatAreYouDoingServiceAuthenticator.java with the version in the sample.



Adding the updateStatus Operation




In this section you add the Twitter updateStatus operation to JButton1 (the "Update" button), which you created when you designed the JFrame. You also add the code so that when the button is clicked, the client gets the text from JTextField1 (the "Status" field) and sends it to Twitter.





To add the updateStatus operation:







  1. Return to the Design view of TwitterJFrame. Double-click the Update button in the JFrame. The editor switches back to the Source view, in the body of the jButton1ActionPerformed method, which the IDE just created for you.


    TwitterJFrame in Source view, with cursor in middle of newly created jButton1ActionPerformed method


  2. Open the Services window. Under Web Services, navigate to Twitter > WhatAreYouDoingService > Statuses > [update.{format}] > updateStatus.

    Services window showing Web Services tree with Twitter update Service operation selected


  3. Drag and drop the updateStatus operation into the method body of jButton1ActionPerformed. The Customization POST SaaS dialog appears. Accept the defaults and click OK. The IDE generates the code for the updateStatus operation into the method body.


  4. In the generated try block, locate the line String status = "";. Change it to String status = jTextField1.getText().trim();. (Try changing it with code completion!) This gets the text typed into the text field and puts it in the status object that is sent by POST to Twitter.




The application can now update your Twitter status, when you are authenticated.





Displaying Usernames and Statuses in the JFrame




Now you set up the application to display the usernames and public statuses of everyone in the Twitter public timeline.







Creating a TimerTask



To update the display of the Twitter public timeline automatically, wrap the execution code in a TimerTask. Write the TimerTask wrapper first and then fill it in with execution code. Otherwise your code will be full of error warnings.





To create the TimerTask:







  1. Open TwitterJFrame in the Sources view of the editor.


  2. Find the class declaration and the constructor.

    public class TwitterJFrame extends javax.swing.JFrame {

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    initComponents();
    initUserInfo();
    }



  3. In the method body of the constructor, above initComponents();, instantiate the java.util.Timer class. The parameters name the Timer thread "Twitter Updater" and specify that it cannot be run as a daemon.

    public class TwitterJFrame extends javax.swing.JFrame {

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    Timer t = new Timer("Twitter Updater`", false);

    initComponents();
    initUserInfo();
    }



  4. Right-click anywhere in the editor and select Fix Imports from the context menu, or press Ctrl-Shift-I. A dialog opens and gives you a choice of classes to import. Add an import statement for java.util.Timer.


  5. Below the instantiation of Timer, create a new Timer.scheduleAtFixedRate method. The method's parameters are a TimerTask object, the delay before it first runs the task, and the frequency with which it runs the task. Set the method to wait 1.5 seconds and run every 75 seconds. The exact code follows, in bold. An empty line is left where you put the execution code. Note that you have to add an import statement for java.util.TimerTask.

    public class TwitterJFrame extends javax.swing.JFrame {

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    Timer t = new Timer("Twitter Updater`", false);
    t.scheduleAtFixedRate(new TimerTask() {


    }, 1500, 75000);

    initComponents();
    initUserInfo();
    }




The TimerTask wrapper code is now complete. Next you add the execution code.



Adding a run Method With the getPublicTimeline Operation



To display usernames and statuses, the application first gets this data from Twitter. Twitter SaaS provides the getPublicTimeline operation for getting public usernames and statuses. To execute the getPublicTimeline operation when the application runs, the operation needs to be inside a run method. Finally, because the application displays the usernames and statuses in a JList, the application needs to add the results of getPublicTimeline as elements of a DefaultListModel object.



To add a run method with the getPublicTimeline operation:




  1. Above the TwitterJFrame constructor, create a DefaultListModel object named statuses.

    public class TwitterJFrame extends javax.swing.JFrame {

    private DefaultListModel statuses = new DefaultListModel();



    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {



  2. Right-click anywhere in the editor and select Fix Imports from the context menu, or press Ctrl-Shift-I. This action adds an import statement for DefaultListModel.


  3. In the body of the TimerTask object, create a new run method. Use the @Override annotation to override the run method in main.

    public class TwitterJFrame extends javax.swing.JFrame {

    private DefaultListModel statuses = new DefaultListModel();





    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    Timer t = new Timer("Twitter Updater`", false);
    t.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run(){

    }

    }, 1500, 75000);
    initComponents();
    initUserInfo();
    }



  4. Open the Services window. In the Web Services tree, navigate to Twitter > What Are You Doing Service > [statuses] > [public_timeline.{format}] > getPublicTimeline.

    Services window showing Twitter getPublicTimeline operation


  5. Drag and drop getPublicTimeline into the body of the run method. A dialog box opens where you can customize the parameters of the GET operation. Accept the defaults and click OK. The IDE adds a try block with getPublicTimeline into your code.

    public class TwitterJFrame extends javax.swing.JFrame {

    private DefaultListModel statuses = new DefaultListModel();

    /** Creates new form TwitterJFrame */
    public TwitterJFrame() {
    Timer t = new Timer("Twitter Updater`", false);
    t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {

    try {
    String format2 = "xml";

    RestResponse result2 = TwitterWhatAreYouDoingService.getPublicTimeline(format2);
    if (result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses result2Obj = result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    } else if (result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.NilClasses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.NilClasses) {
    twitter.whatareyoudoingservice.twitterresponse.NilClasses result2Obj = result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.NilClasses.class);
    }
    //TODO - Uncomment the print Statement below to print result.
    //System.out.println("The SaasService returned: "+result2.getDataAsString());
    } catch (Exception ex) {
    ex.printStackTrace();
    }


    }
    }, 1500, 75000);
    initComponents();
    initUserInfo();
    }



  6. In the try block, locate the if block.

    if (result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses result2Obj = result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    }



  7. At the end of the if block, insert code that adds a list element to statuses (your DefaultListModel object created in Step 1) for every Status object that the method gets from Twitter.

    if (result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class) instanceof twitter.whatareyoudoingservice.twitterresponse.Statuses) {
    twitter.whatareyoudoingservice.twitterresponse.Statuses result2Obj = result2.getDataAsObject(twitter.whatareyoudoingservice.twitterresponse.Statuses.class);
    for (final StatusType st : result2Obj.getStatus()) {
    SwingUtilities.invokeLater(new Runnable() {

    public void run() {
    statuses.addElement(st);
    }
    });
    }

    }



  8. Press Ctrl-Shift-I to add an import statement for StatusType.



The code for getting statuses from the Twitter public timeline is now complete. Next you write a new class that returns a Component with list elements rendered in GUI components.



Creating a List Cell Rendering Component



Now you have code that gets Status objects from the Twitter Public Timeline and creates a list element for each status. However, you cannot display these raw list elements in a JList. You need to pass the data into GUI components . To accomplish this, create a new JPanel that implements javax.swing.ListCellRenderer. This JPanel returns a java.awt.Component object with the username and status passed in JLabels. You can customize the appearance of the JLabels in the JPanel.



To add a list cell rendering Component:




  1. Right-click the project's node and choose New > JPanel Form. The New JPanel Form wizard opens.


  2. Name the JPanel Item and place it in the twitterclient package.


    New JPanel Form wizard showing panel named Item and package twitterclient


  3. Click Finish. Item.java opens in the Design view of the editor.


  4. Drag and drop a Label and a Text Pane into the JPanel. The Label will display the username and the Text Pane will display that user's status message.


  5. Position the Label and the Text Pane to match how you want the data to be displayed. In the following image, the username is on the left top while the status text is below and slightly indented. The sample project has the data on the top left and the username on the bottom right. Leave enough empty space in the JPanel below the Text Pane for the Text Pane to expand when it contains longer text.


    Layout of jlabels displaying username and status text


  6. Right-click on the JLabel element and select Properties from the context menu. In the Properties, you can change the font, the color, the alignment and other qualities. Set the labelFor property to point to jTextPane1. This improves accessibility. Experiment with the properties of the label until you like the appearance. In the following image, the font color is set to blue in the Foreground property.


    JLabel properties dialog with Foreground set to blue


  7. Open the Properties dialog of the JTextPane and experiment with its appearance.


  8. Change to the Source view for Item.java. Find the Generated Code block and expand it. This shows you the code generated by the IDE when you set the properties of the JLabel and JTextPane.

    In the following image, note the blue color setting for JLabel1. Can you see what properties are set for the JTextPane?



    Code generated in Item.java by setting JLabel properties in the Design view




  9. Find the class declaration and add the code implements ListCellRenderer.

    public class Item extends javax.swing.JPanel implements ListCellRenderer {



  10. Press Ctrl-Shift-I. This action adds an import statement for javax.swing.ListCellRenderer. A warning appears saying that you need to implement all abstract methods.


  11. Add a few empty lines between the generated code block and the variable declarations. Into that space, add the following code, which implements the abstract method getListCellRendererComponent. (You can copy and paste the code, or you can try to reproduce it with code completion.) This code replaces the default label texts "username" and "text" with the Text, User, and ScreenName objects you get with the Twitter StatusType class. The code then returns an instance of Component with these new JLabel text values.

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean sel, boolean focus) {
    StatusType st = (StatusType) value;
    jTextPane1.setText(st.getText());
    jLabel1.setText("<html>" + st.getUser().getScreenName() + "</html>");
    return this;
    }



  12. Press Ctrl-Shift-I. This adds import statements for the StatusType and Component classes. Save Item.java.



Now you have an Item class that returns a Component object with username and status displayed in a JLabel and a JTextPane. Next you modify TwitterJFrame to use this Component.



Displaying the Component in TwitterJFrame



In order to display the Component object created in Item.java, the JList in TwitterJFrame has to use Item.java as its cell renderer.







  1. Return to TwitterJFrame. In the Design view, select the JList. Right-click and open its Properties.

    Properties dialog for the JList element in TwitterJFrame


  2. Select the model property. Press Ctrl-Space. The custom property editor opens, showing the default text displayed in the list.


    J list custom property editor


  3. In the "Set jLlist1's model property using:" drop-down menu, select Custom Code. A text field appears where you type in the properties for jLabel1.setModel. Type statuses in the field and click OK.


    jList custom property editor showing setModel(statuses) chosen in the cusom code editor


  4. In the Properties dialog, select cellRenderer and press Ctrl-Space. The custom property editor opens.


  5. In the "Set jList1's cellRenderer property using:" drop-down menu, select Custom Code. A text field appears where you type in the properties for jList1.cellRenderer. Type new Item() and click OK.


    J List custom cell renderer properties editor showing new Item chosen




Your client application is now complete! Save all files and run the application. (Right-click project node and select Run.) The application opens, showing a list of public timeline messages and a field with your own status.



Running client displaying Twitter messages





More Exercises



Here are a few more ideas for you to explore:




  • Change your Twitter user icon (in a browser) and run the client again. Does the new icon appear?


  • Add a toolbar with some functions to the JFrame.


  • Add a new Scroll Pane with a new List that displays your friends' statuses, using the What Are You Doing Service > [statuses] > [friends_timeline.{format}] > getFriendsTimeline operation. The code is similar to the code for displaying the public timeline.



This article is originaly from http://www.netbeans.org/kb/docs/websvc/twitter-swing.html

segunda-feira, 16 de março de 2009

Developing JAX-WS Web Service Clients

 

Este é um ótimo tutorial sobre como consumir um web service utilizando das ferramentas que o Net Beans 6.5 oferece.

Confira também o post Getting Started with JAX-WS Web Services sobre como desenvolver Web Services com o Net Beans 6.5 de uma forma simples e rápida, com foco no quesito negocial do web service e deixando as configurações e deployments a cargo dos wizards do netbeans.

In this tutorial, you use the web service facilities provided by NetBeans IDE 6.x to analyze a Spell Checker web service, after which you build a web client that interacts with it.

Contents

Content on this page applies to NetBeans IDE 6.0 and 6.1

To follow this tutorial, you need the following software and resources.

Software or Resource
Version Required

NetBeans IDE
Web & Java EE download bundle 6.0 or 6.1
Java download bundle 6.5

Java Development Kit (JDK)
version 6 or
version 5

Java EE-compliant web or application server
Tomcat web server 6.0 and/or
GlassFish application server v2

If you are using JDK 6, you need JDK 6 Update 7 or later.

Both Tomcat and GlassFish can be installed with the Web and Java EE distribution of NetBeans IDE. Alternatively, you can visit theGlassFish downloads page or the Apache Tomcat downloads page.

This is what your client will look like, with all data received from the web service:

Spell Checker report

By the end of this tutorial, you discover that your only contribution to the application consists of providing the text to be checked, invoking an operation on the web service, and rendering the result. The IDE generates all the code needed for contacting the web service and sending the text. The spell checker web service takes care of the rest, it identifies the misspelled words and provides a list of suggested alternatives.

The spell checker web service used in this tutorial is provided by the CDYNE Corporation. CDYNE develops, markets and supports a comprehensive suite of data enhancement, data quality and data analysis web services and business intelligence integration. The spell checker web service is one of the web services provided by CDYNE. Note that the strength of an application based on one or more web services depends on the availability and reliability of the web services. However, CDYNE's FAQ points out that it has a "100% availability objective" and that in the event of "natural disaster, act of terror, or other catastrophe, web service traffic is transferred to our secondary data center". NetBeans thanks CDYNE for enabling this tutorial to be written and for supporting its development.

Consuming the Spell Checker Web Service

To use a web service over a network, which is called "consuming" a web service, you need to create a web service client. For the creation of web service clients, NetBeans IDE 6.1 and 6.0 provide a client creation facility, which is the Web Service Client wizard that generates code for looking up a web service. It also provides facilities for developing the created web service client, a work area consisting of nodes in the Projects window. These facilities are part of the standard NetBeans IDE installation, they're available straight out of the box and no plug-ins are needed.

Creating the Client

In this section, you use a wizard to generate Java objects from the web service's WSDL file.

  1. Choose File > New Project (Ctrl-Shift-N). Under Categories, choose Java Web or Web. Under Projects, choose Web Application. Click Next. Name the project SpellCheckService and make sure that you specify an appropriate server as your target server. (Refer to the "Getting Started" section for details.) Leave all other options at default and click Finish.
  2. In the Projects window, right-click the SpellCheckService project node and choose New > Other. In the New File wizard choose Web Services > Web Service Client. In the Web Service Client wizard, specify the URL to the web service:

    http://ws.cdyne.com/SpellChecker/check.asmx?wsdl

    If you are behind a firewall, you might need to specify a proxy server—otherwise the WSDL file cannot be downloaded. To specify the proxy server, click Proxy Settings in the Web Service Client wizard and set your proxy host and port number.

  3. Leave the package name blank. In NetBeans IDE 6.1 and 6.5 you are not allowed to specify a package name. By default the client class package name is taken from the WSDL. In this case is com.cdyne.ws.
  4. In NetBeans IDE 6.1 or 6.5, select JAX version JAX-WS (Some older services require JAX-RPC clients). Click Finish.
  5. In the Projects window, within the Web Service References node, you see the following:
    Projects window showing web service references

The Projects window shows that a web service called 'check' has made the operation 'CheckTextBody' available to your application. The 'CheckTextBody' operation checks a string for spelling errors and returns data to be processed by the client. You will use this operation throughout this tutorial.

In the Files window, within the build node, you see the following:

Files view showing package structure of Build node

The Files window shows the client stubs that were generated by the JAX-WS Web Service Client wizard.

Developing the Client

There are many ways to implement a web service client. The web service's WSDL file restricts the type of information that you can send to the web service, and it restricts the type of information you receive in return. However, the WSDL file lays no restrictions on how you pass the information it needs, nor on what the user interface consists of. The client implementation you build below consists of a JSP page which allows the user to enter text to be checked and a servlet which passes the text to the web service and then produces a report containing the result.

Coding the JSP Page

Our JSP page will consist of a text area, where the user will enter text, and a button for sending the text to the web service.

  1. In the Projects window, expand the Web Pages node of the SpellCheckService project and double-click index.jsp so that it opens in the Source Editor.
  2. Copy the following code and paste it over the <body> tags in index.jsp:
    <body>
    <form name="Test" method="post" action="SpellCheckServlet">
    <p>Enter the text you want to check:</p>
    <p>
    <p><textarea rows="7" name="TextArea1" cols="40" ID="Textarea1"></textarea></p>
    <p>
    <input type="submit" value="Spell Check" name="spellcheckbutton">
    </form>
    </body>


    The previously listed code specifies that when the submit button is clicked, the content of the textarea is posted to a servlet calledSpellCheckServlet.





Creating and Coding the Servlet


In this section you create a servlet that will interact with the web service. However, the code that performs the interaction will be provided by the IDE. As a result, you only need to deal with the business logic, that is, the preparation of the text to be sent and the processing of the result.




  1. Right-click the SpellCheckService project node in the Projects window, choose New > Other and then choose Web > Servlet. Click Next. Name the servlet SpellCheckServlet and type clientservlet in the Package drop-down. Click Next. Note that the URL mapping for this servlet is /SpellCheckServlet, as shown below:


    Display in browser

    Click Finish. The servlet opens in the Source Editor.




  2. If you are using NetBeans IDE 6.5, right-click the SpellCheckService project node and choose Properties. Open the Run properties and unselect Deploy on Change.


  3. Put your cursor inside the Source Editor, inside the processRequest method, add some new lines right at the top of the method.


  4. Right-click in the space that you created in the previous step, and choose Web Service Client Resources > Call Web Service Operation. Click the CheckTextBody operation in the "Select Operation to Invoke" dialog box,as shown below:


    Select Operation to Invoke dialog box showing CheckTextBody operation

    Click OK.



    Note: You can also drag and drop the operation node directly from the Projects window into the editor, instead of calling up the dialog shown above.



    At the top of the processRequest method you see a snippet of code that invokes the web service, as shown below:



    try { // Call Web Service Operation
    com.cdyne.ws.Check service = new com.cdyne.ws.Check();
    com.cdyne.ws.CheckSoap port = service.getCheckSoap();
    // TODO initialize WS operation arguments here
    java.lang.String bodyText = "";
    java.lang.String licenseKey = "";
    // TODO process result here
    com.cdyne.ws.DocumentSummary result = port.checkTextBody(bodyText, licenseKey);
    System.out.println("Result = " + result);
    } catch (Exception ex) {
    // TODO handle custom exceptions here
    }


    This method is all you need to invoke the operation on the web service. In addition, the following lines of code are declared at the top of the class:



    @WebServiceRef(wsdlLocation = "http://ws.cdyne.com/SpellChecker/check.asmx?WSDL")
    private Check service;



  5. Replace the entire processRequest method with the code that follows. The in-line comments throughout the code below explain the purpose of each line.

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

    // Call Web Service Operation
    String TextArea1 = request.getParameter("TextArea1");

    com.cdyne.ws.Check service = new com.cdyne.ws.Check();
    com.cdyne.ws.CheckSoap port = service.getCheckSoap();

    // TODO initialize WS operation arguments here
    java.lang.String bodyText = TextArea1;
    java.lang.String licenseKey = "0";

    // TODO process result here
    com.cdyne.ws.DocumentSummary doc = port.checkTextBody(bodyText, licenseKey);
    String allcontent = doc.getBody();

    //From the retrieved document summary,
    //identify the number of wrongly spelled words:

    int no_of_mistakes = doc.getMisspelledWordCount();

    //From the retrieved document summary,
    //identify the array of wrongly spelled words:

    List allwrongwords = doc.getMisspelledWord();

    out.println("<html>");
    out.println("<head>");

    //Display the report's name as a title in the browser's titlebar:
    out.println("<title>Spell Checker Report</title>");
    out.println("</head>");
    out.println("<body>");

    //Display the report's name as a header within the body of the report:
    out.println("<h2><font color='red'>Spell Checker Report</font></h2>");

    //Display all the content (correct as well as incorrectly spelled) between quotation marks:
    out.println("<hr><b>Your text:</b> \"" + allcontent + "\"" + "<p>");

    //For every array of wrong words (one array per wrong word),
    //identify the wrong word, the number of suggestions, and
    //the array of suggestions. Then display the wrong word and the number of suggestions and
    //then, for the array of suggestions belonging to the current wrong word, display each
    //suggestion:

    for (int i = 0; i < allwrongwords.size(); i++) {
    String onewrongword = ((Words) allwrongwords.get(i)).getWord();
    int onewordsuggestioncount = ((Words) allwrongwords.get(i)).getSuggestionCount();
    List allsuggestions = ((Words) allwrongwords.get(i)).getSuggestions();
    out.println("<hr><p><b>Wrong word:</b><font color='red'> " + onewrongword + "</font>");
    out.println("<p><b>" + onewordsuggestioncount + " suggestions:</b><br>");
    for (int k = 0; k < allsuggestions.size(); k++) {
    String onesuggestion = (String) allsuggestions.get(k);
    out.println(onesuggestion);
    }
    }

    //Display a line after each array of wrong words:
    out.println("<hr>");

    //Summarize by providing the number of errors and display them:
    out.println("<font color='red'><b>Summary:</b> " + no_of_mistakes + " mistakes (");
    for (int i = 0; i < allwrongwords.size(); i++) {
    String onewrongword = ((Words) allwrongwords.get(i)).getWord();
    out.println(onewrongword);
    }

    out.println(").");
    out.println("</font>");
    out.println("</body>");
    out.println("</html>");
    out.close();

    } catch (Exception ex) {
    System.out.println("exception" + ex);
    out.println("exception" + ex);
    }

    out.println("</body>");
    out.println("</html>");
    out.close();
    }



  6. You see a number of error bars and warning icons, indicating classes that are not found. To fix imports after pasting the code, either press Ctrl-I, or right-click anywhere, which opens a context menu, and select Fix Imports. (You have a choice of List classes to import. Accept the default java.util.List.) The full list of imported classes follows:
    import com.cdyne.ws.Check;
    import com.cdyne.ws.Words;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.xml.ws.WebServiceRef;


    Note that error handling has not been dealt with in the previously listed code. See Applying What You Have Learned for details.





Deploying the Client


The IDE uses an Ant build script to build and run your application. The IDE generates the build script based on the options you entered when creating the project. You can fine tune these options in the project's Project Properties dialog box (right-click the project node in the Projects window and choose Properties).




  1. Right-click the project node and choose Run. After a while, the application deploys and displays the JSP page that you coded in the previous section.


  2. Enter some text, making sure that some of it is incorrectly spelled:

    JSP page with text to check


  3. Click Spell Check and see the result:

    Spell Checker report showing errors



Applying What You Have Learned



Now that you have completed your first web service client in the IDE, it is time to stretch your skills and extend the application to be all that it was destined to be. Below are two suggested tasks to get you started.




  • Add error handling code to the servlet.


  • Rewrite the client so that the user can interact with the data returned from the web service. For inspiration, see the client implementation on the CDYNE site. It looks like this:


    CDYNE spell checking service



Fonte : http://www.netbeans.org/kb/60/websvc/client.html

Getting Started with JAX-WS Web Services

Navegando na documentação e tutoriais disponibilizados pelo NetBeans, descobri um ótimo tutorial sobre como utilizar o NetBeans 6.5 para a confecção de webservices e três exemplos de como consumir esse web sercive a partir de uma classe java, um servlet e um jsp.

Me impressionou o grau de automatização em que o netbeans trata as duas operações, principalmente no ato de consumir um web service.

Interessante citar também que o objetivo é deixar que o desenvolver mantenha seu foco somente nas regras negociais do web service, deixando todas as “chatices” das configurações e deployments para os wizards do netbeans.

Realmente vale a pena conferir

ACESSE TAMBÉM O POST “Developing JAX-WS Web Service Clients” PARA UM TUTORIAL MAIS DETALHADO SOBRE DESENVOLVIMENTO DE CLIENTES QUE CONSOMEM WEB SERVICES A PARTIR DO NETBEANS.

 

 

Java API for XML Web Services (JAX-WS) 2.0/2.1, JSR 224, is an important part of the Java EE 5 platform. A follow-up to the release of Java API for XML-based RPC 1.1(JAX-RPC), JAX-WS simplifies the task of developing web services using Java technology. It addresses some of the issues in JAX-RPC 1.1 by providing support for multiple protocols such as SOAP 1.1, SOAP 1.2, XML, and by providing a facility for supporting additional protocols along with HTTP. JAX-WS uses JAXB 2.0 for data binding and supports customizations to control generated service endpoint interfaces. With its support for annotations, JAX-WS simplifies web service development and reduces the size of runtime JAR files.

This document demonstrates the basics of using the IDE to develop a JAX-WS web service. After you create the web service, you write three different web service clients that use the web service over a network, which is called "consuming" a web service. The three clients are a Java class in a Java SE application, a servlet, and a JSP page in a web application. A more advanced tutorial focusing on clients is Developing JAX-WS Web Service Clients.

Contents

Content on this page applies to NetBeans IDE 6.0, 6.1 and 6.5

To follow this tutorial, you need the following software and resources.

Software or Resource
Version Required

NetBeans IDE
Java version 6.5

Java Development Kit (JDK)
version 6 or version 5
Note: If you are using JDK 6,
you must have JDK 6 Update 7 or later.

Java EE-compliant web or application server
Tomcat web server 6.0 and/or
GlassFish application server v2

If you are using JDK 6, you must have JDK 6 Update 7 or later.

Both Tomcat and GlassFish can be installed with the Web and Java EE distribution of NetBeans IDE. Alternatively, you can visit the GlassFish downloads page or the Apache Tomcat downloads page.

Creating a Web Service

The goal of this exercise is to create a project appropriate to the deployment container that you decide to use. Once you have a project, you will create a web service in it.

Choosing a Container

You can either deploy your web service in a web container or in an EJB container. This depends on your choice of implementation. For example, if you plan to deploy to the Tomcat Web Server, which only has a web container, create a web application, not an EJB module.

  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Web category or EJB Module from the Enterprise category.
  2. Name the project CalculatorWSApplication.
  3. Depending on the deployment server that you want to use, do the following:
    • For GlassFish, set the Java EE Version to Java EE 5.
    • For the Tomcat Web Server, unselect the Set Source Level to 1.4 checkbox.
  4. Click through the remaining pages and click Finish.

    Creating a project in NetBeans 6.1 includes new options which can be left at the default. For example, the Use Dedicated Folder for Storing Libraries checkbox may be left unselected.

Creating a Web Service from a Java Class
  1. Right-click the CalculatorWSApplication node and choose New > Web Service.
  2. Name the web service CalculatorWS, type org.me.calculator in Package, and click Finish.

    The Projects window displays the structure of the new web service and the visual designer is shown in the editor area. For web applications you now see the following:

    Projects window displaying the web service

Designing the Web Service

The goal of this exercise is to add to the web service an operation that adds two numbers received from a client.

Adding an Operation to the Web Service
  1. Click Add Operation in the visual designer. A dialog box appears where you can define the new operation.
  2. In the upper part of the Add Operation dialog box, type add in Name and type int in the Return Type drop-down list. In the lower part of the Add Operation dialog box, click Add and create a parameter of type int named i. Then click Add again and create a parameter of type int called j.

    You now see the following:

    Add Operation dialog

  3. Click OK at the bottom of the Add Operation dialog box.

    The visual designer now displays the following:

    Web service visual designer showing added operation

  4. Click Source and notice that the source code that has been generated in the previous steps is as follows:
    Result
  5. In the editor, extend the skeleton add operation to the following (changes are in bold):
        @WebMethod
    public int add(@WebParam(name = "i") int i, @WebParam(name = "j") int j) {
    int k = i + j;
    return k;
    }




As you can see from the preceding code, the web service simply receives two numbers and then returns their sum. In the next section, you use the IDE to test the web service.



Deploying and Testing the Web Service



When you deploy a web service to a web container, the IDE lets you test the web service to see if it functions as you expect. The Tester application, provided by GlassFish, is integrated into the IDE for this purpose. For the Tomcat Web Server, there is a similar tool. However, while GlassFish's Tester page lets you enter values and test them, the Tomcat Web Server does not. In the latter case, you can only see that the web service is deployed, you cannot test the values. No facility for testing whether an EJB module is deployed successfully is currently available.



To test successful deployment to a web container:




  1. Right-click the project and choose Undeploy and Deploy. The IDE starts the application server, builds the application, and deploys the application to the server. You can follow the progress of these operations in the CalculatorWSApplication (run-deploy) and GlassFish V2 or Tomcat tabs in the Output view.


  2. In the IDE's Projects tab, expand the Web Services node of the CalculatorWSApplication project. Right-click the CalculatorWS node, and choose Test Web Service.

    Projects tab showing Test Web Service context menu option

    The IDE opens the tester page in your browser, if you deployed a web application to GlassFish. For the Tomcat Web Server and deployment of EJB modules, the situation is different:




    • If you deployed to GlassFish, type two numbers in the tester page, as shown below:

      Web service tester page when service successfully deployed to GlassFish

      The sum of the two numbers is displayed:



      Web page showing result of web service test




    • If you deployed to the Tomcat Web Server, you will see the following instead, which indicates that you have successfully deployed your web service:

      Web page displayed when web service was successfully deployed to Tomcat server


    • Right-click the project node, choose Properties, and click Run. Depending on the deployment server that you want to use, do the following:

      • For GlassFish, type /CalculatorWSService?Tester in the Relative URL field.


      • For the Tomcat Web Server, type /CalculatorWS?Tester in the Relative URL field.



      Note: Since the result of a deployed EJB module is not displayed in a browser, you cannot take the step above if you are working with an EJB module.







Consuming the Web Service



Now that you have deployed the web service, you need to create a client to make use of the web service's add method. Here, you create three clients— a Java class in a Java SE application, a servlet, and a JSP page in a web application.



Note: A more advanced tutorial focusing on clients is Developing JAX-WS Web Service Clients.



Client 1: Java Class in Java SE Application


In this section, you create a standard Java application. The wizard that you use to create the application also creates a Java class. You then use the IDE's tools to create a client and consume the web service that you created at the start of this tutorial.



If you are using JDK 6 with NetBeans IDE 6.5, you must have JDK 6 Update 7 or later.




  1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the Java category. Name the project CalculatorWS_Client_Application. Leave Create Main Class selected and accept all other default settings. Click Finish.


  2. Right-click the CalculatorWS_Client_Application node and choose New > Web Service Client.


  3. In Project, click Browse. Browse to the web service that you want to consume. When you have selected the web service, click OK.


  4. Leave the other settings at default and click Finish.

    The Projects window displays the new web service client, with a node for the add method that you created:



    New web service client in Java SE application displayed in the Projects window




  5. Double-click Main.java so that it opens in the Source Editor. Delete the TODO comment and then drag the add node above into the empty line. You now see the following:

    public static void main(String[] args) {

    try { // Call Web Service Operation
    org.me.calculator.CalculatorWSService service = new org.me.calculator.CalculatorWSService();
    org.me.calculator.CalculatorWS port = service.getCalculatorWSPort();
    // TODO initialize WS operation arguments here
    int i = 0;
    int j = 0;
    // TODO process result here
    int result = port.add(i, j);
    System.out.println("Result = "+result);
    } catch (Exception ex) {
    // TODO handle custom exceptions here
    }

    }


    Note: Alternatively, instead of dragging the add node, you can right-click in the editor and then choose Web Service Client Resources > Call Web Service Operation.




  6. Initialize the two ints. Just change the values of the two ints above from 0 to other integers, such as 3 and 4.


  7. Right-click the project node and choose Run.

    The Output window now shows the sum:



        compile:
    run:
    Result = 7
    BUILD SUCCESSFUL (total time: 1 second)




Client 2: Servlet in Web Application


In this section, you create a new web application, after which you create a servlet. You then use the servlet to consume the web service that you created at the start of this tutorial.



If you are using JDK 6, you must have JDK 6 Update 7 or later.




  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category. Name the project CalculatorWSServletClient. Click Finish.


  2. Right-click the CalculatorWSServletClient node and choose New > Web Service Client.

    The New Web Service Client wizard appears.




  3. In Project, click Browse. Browse to the web service that you want to consume. When you have selected the web service, click OK.


  4. Leave the other settings at default and click Finish.

    The Web Service References node in the Projects window displays the structure of your newly created client, including the add operation that you created earlier in this tutorial:



    New web service client in servlet displayed in the Projects window




  5. Right-click the CalculatorWSServletClient project node and choose New > Servlet. Name the servlet ClientServlet and place it in a package called org.me.calculator.client. Click Finish.


  6. Right-click the CalculatorWSServletClient project node and choose Properties. Open the Run properties and unselect Deploy on Save.


  7. To make the servlet the entry point to your application, right-click the project node, choose Properties, click Run, and type /ClientServlet in Relative URL. Click OK.


  8. If there are error icons for ClientServlet.java, right-click the project node and select Clean and Build.


  9. In the Source Editor, remove the line that comments out the body of the processRequest method. This is the line:

        /* TODO output your page here


    Next, delete the line that ends the section of commented out code:



        */


    Add some empty lines after this line:



        out.println("<h1>Servlet ClientServlet at " + request.getContextPath () + "</h1>");


    Now, drag the node that represents the add operation into the space that you created.



    The processRequest method now looks as follows (the added code is in bold below):



        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet ClientServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet ClientServlet at " + request.getContextPath () + "</h1>");

    try { // Call Web Service Operation
    org.me.calculator.CalculatorWS port = service.getCalculatorWSPort();
    // TODO initialize WS operation arguments here
    int i = 0;
    int j = 0;
    // TODO process result here
    int result = port.add(i, j);
    out.println("Result = "+result);
    } catch (Exception ex) {
    // TODO handle custom exceptions here
    }


    out.println("</body>");
    out.println("</html>");
    out.close();
    }


    Change the values for i and j to positive integers, such as 3 and 4.




  10. Right-click the project node and choose Run.

    The server starts, if it wasn't running already; the application is built and deployed, and the browser opens, displaying the calculation result, as shown below:

    New web service client in servlet displayed in the Projects window





Client 3: JSP Page in Web Application


In this section, you create a new web application and then consume the web service in the default JSP page that the Web Application wizard creates.



If you are using JDK 6, you must have JDK 6 Update 7 or later.




  1. Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Web category. Name the project CalculatorWSJSPClient. Click Finish.


  2. Right-click the CalculatorWSJSPClient node and choose New > Web Service Client.


  3. In Project, click Browse. Browse to the web service that you want to consume. When you have selected the web service, click OK.


  4. Leave the other settings at default and click Finish.

    The Projects window displays the new web service client, as shown below:



    New web service client in servlet displayed in the Projects window




  5. In the Web Service References node, expand the node that represents the web service. The add operation, which you will invoke from the client, is now exposed.


  6. Drag the add operation to the client's index.jsp page, and drop it below the H1 tags. The code for invoking the service's operation is now generated in the index.jsp page, as you can see here:

    <%
    try {
    org.me.calculator.CalculatorWSService service =
    new org.me.calculator.CalculatorWSService();
    org.me.calculator.CalculatorWS port =
    service.getCalculatorWSPort();
    // TODO initialize WS operation arguments here
    int i = 0;
    int j = 0;
    // TODO process result here
    int result = port.add(i, j);
    out.println("Result = "+result);
    } catch (Exception ex) {
    // TODO handle custom exceptions here
    }
    %>


    Change the value for i and j from 0 to other integers, such as 3 and 4.




  7. Right-click the project node and choose Run.

    The server starts, if it wasn't running already. The application is built and deployed, and the browser opens, displaying the calculation result:



    JSP page showing result







Fonte : http://www.netbeans.org/kb/docs/websvc/jax-ws.html

sábado, 14 de março de 2009

Ativação de MIDlets através de Bluetooth

A partir da versão 2.0 da MIDP, os programadores Java podem permitir que aplicativos Java ME (MIDlets) possam ser iniciados de forma automática, sem intervenção do usuário. Este mecanismo é chamado de Push Registry. O objetivo desse post não é explicar de forma detalhada o Push Registry, porém, de forma sucinta, basta saber que é possível programar sua MIDlet pra iniciar automaticamente após um intervalo de tempo ou, com eventos externos, como chegada de mensagem SMS, MMS, Bluetoooth, conexão por socket etc.

A Figura anterior mostra as formas de ativação de uma MIDlet. A “Manual Activation by user” é a forma normal, onde o usuário vai até o menu de aplicativos do dispositivo e inicia a aplicação. Os dois modos de ativação ao lado foram adicionados com o advento do Push Registry.
Bem, dito isso, uma das formas de ativação de MIDlet é com conexão Bluetooth. Para fazer isso, podemos usar a JSR-82, um pacote ocional do Java ME para troca de dados entre dispositivos através de uma conexão Bluetooth ou, utilizar a API Marge. Esta API criada por brasileiros, facilita a criação de aplicativos que utilizem Bluetooth, escondendo um pouco a complexidade da JSR-82.
Para adicionar o mecanismo de Push Registry a um aplicativo tem duas formas: estática ou dinâmica. A forma estática é a mais simples, basta adicionar uma nova linha ao descritor da aplicação, o famoso .JAD. Além disso, é preciso dar permissão de uso para algumas classes. Veja as duas linhas que precisei colocar no arquivo JAD do meu projeto:

MIDlet-Permissions: javax.microedition.io.PushRegistry, javax.microedition.io.Connector.bluetooth.server, javax.microedition.io.Connector.bluetooth.client
MIDlet-Push-1: btspp://localhost:D0FFBEE2D0FFBEE2D0FFBEE2D0FFBEE2,hello.HelloMIDlet,*

A linha de permissões é auto explicativa, a linha MIDlet-Push-1 define um push registre estático. O btspp define o protocolo, a seguir definimos o dispositivo (localhost) e seu UUID como D0FFBEE2D0FFBEE2D0FFBEE2D0FFBEE2. Este UUID é um número de 32 bits que define um identificador único universal. Porque coloquei este número hexadecimal? Porque criei um servidor Bluetooth anteriormente no celular e mandei mostrar no display qual era o UUID que o servidor criado recebia, com isso, fiquei sabendo qual o código universal do aparelho. Depois da vírgula defini qual a classe que será iniciada com esse evento de push resgistry. Finalmente, no último parâmetro é possível criar filtros, no meu caso não coloquei nenhum, passando apenas *.
Bem, o leitor deve ter percebido que para fazer isso precisa conhecer o UUID do aparelho, oque não é muito usual, levando em conta que seu aplicativo será distribuído para N plataformas. Então, a solução é o push registry dinâmico, construído via código fonte. A listagem de código abaixo demonstra como criar um push registry dinâmico:

1: public void registra()
2: {
3:    ServerConfiguration config = new ServerConfiguration(this);//communicationListener
4:    config.setMaxNumberOfConnections(10);
5:    getFrmMain().append(”UUID: “+config.getUuid().toString());
6:    communicationFactory.waitClients(config, this);
7: 
8:    String midletClassName = this.getClass().getName();
9:    String url = “btspp://localhost:”+config.getUuid().toString();
10:    String filter = “*”;
11: 
12:    try
13:    {
14:       PushRegistry.registerConnection(url, midletClassName, filter);
15:    }
16:    catch (ClassNotFoundException ce)
17:    {}
18:    catch (IOException io)
19:    {}
20: }

Na linha 3 crei uma instância de ServerConfiguration, passando como parâmetro a própria classe que implementa a interface CommunicationListener. A linha 6 poderia ser removida, porque apenas inicia o servidor bluetooth e espera por conexão de clientes, porém, o objetivo aqui é só saber o UUID, mas, deixei a linha de código no lugar até para uma questão de aprendizado. As linhas 8, 9, e 10 definem os parâmetros que serão usados para a criação do push registry. Destaque para a linha 9, que utiliza o código config.getUuid().toString() para recuperar a UUID que é usada pela instância de ServerConfiguration que criei. Finalmente, na linha 14 é onde cria-se de fato o push registry.
Bem, acho que é possível notar que não é dificil fazer um Push Registry através de Bluetooth e, fica bem bacana.
Att.
Ping

Por Por Ricardo Ogliari
em http://www.mobilidadetudo.com/2008/10/ativacao-de-midlets-atraves-de-bluetooth.html