プライマリ・コンテンツに移動
Java Platform, Standard Editionデプロイメント・ガイド
リリース10
E94981-01
目次へ移動
目次

前
次

8 JNLP APIの例

JNLP APIは、標準のJava Platform Standard Edition API経由では入手不可能な追加情報を、アプリケーションに対して提供します。信頼できないアプリケーションに対しては、JNLP APIは、通常はセキュリティ・マネージャによって防止されるファイルの読取りと書込み、クリップボードやプリンタへのアクセスなどの操作のメソッドを提供します。

JNLP APIのpublicクラスおよびインタフェースは、libディレクトリのjavaws.jarファイルに含まれています。JNLP APIを使用しているソース・ファイルをコンパイルする際には、このJARファイルをクラス・パスに含める必要があります。たとえば、Windows上では次のようにします。

javac -classpath .;javaws.jar *.java

次のコード例は、JNLPサービスの使用方法を示しています。

BasicServiceサービスの使用

javax.jnlp.BasicServiceサービスは、環境に対する問合せおよび対話のための一連のメソッドを提供します。これらのメソッドは、AppletContextがJavaアプレットに提供するメソッドに似ています。

showURLメソッドはJNLP APIを使って、プラットフォーム上のデフォルト・ブラウザに対し、指定されたURLを表示するよう指示します。このメソッドは、要求が成功した場合にはtrueを返し、そうでない場合にはfalseを返します。

import javax.jnlp.*;
   ...

   // Method to show a URL
   boolean showURL(URL url) {
       try {
           // Lookup the javax.jnlp.BasicService object
           BasicService bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
           // Invoke the showDocument method
           return bs.showDocument(url);
       } catch(UnavailableServiceException ue) {
           // Service is not supported
           return false;
       }
    }

ClipboardServiceサービスの使用

javax.jnlp.ClipboardServiceサービスは、制限された実行環境で実行されているアプリケーションに対しても、システム全体の共有クリップボードにアクセスするためのメソッドを提供します。

Java Web Startは、クリップボードに格納されている内容(機密情報が含まれる可能性もある)へのアクセスや、そうした内容の上書きが信頼できないアプリケーションに許可されると、セキュリティ上の問題が発生する可能性があることをユーザーに警告します。

import javax.jnlp;
    ...

    private ClipboardService cs;

    try {
        cs = (ClipboardService)ServiceManager.lookup
                 ("javax.jnlp.ClipboardService");
    } catch (UnavailableServiceException e) {
        cs = null;
    }

    if (cs != null) {
        // set the system clipboard contents to a string selection
        StringSelection ss = new StringSelection("Java Web Start!");
        cs.setContents(ss);
        // get the contents of the system clipboard and print them
        Transferable tr = cs.getContents();
        if (tr.isDataFlavorSupported(DataFlavor.stringFlavor)) {
           try {
                String s = (String)tr.getTransferData(DataFlavor.stringFlavor);
                System.out.println("Clipboard contents: " + s);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

DownloadServiceサービスの使用

javax.jnlp.DownloadServiceサービスを使用すると、アプリケーションは自身のリソースをどのようにキャッシュするかを制御できます。

アプリケーションはこのサービスを使うことで、どのリソースがキャッシュされているかの確認、リソースの強制キャッシュ、およびキャッシュからのリソースの削除を行えます。

import javax.jnlp.*; 
    ... 

    DownloadService ds; 

    try { 
        ds = (DownloadService)ServiceManager.lookup("javax.jnlp.DownloadService"); 
    } catch (UnavailableServiceException e) { 
        ds = null; 
    } 

    if (ds != null) { 

        try { 
            // determine if a particular resource is cached
            URL url = 
                    new URL("http://www.example.com/draw.jar"); 
            boolean cached = ds.isResourceCached(url, "1.0"); 
            // remove the resource from the cache 
            if (cached) { 
                ds.removeResource(url, "1.0"); 
            } 
            // reload the resource into the cache 
            DownloadServiceListener dsl = ds.getDefaultProgressWindow(); 
            ds.loadResource(url, "1.0", dsl); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 

DownloadService2サービスの使用

Java SE 6 update 18リリースで導入されたjavax.jnlp.DownloadService2サービスには次のメソッドがあります。

  • getCachedResources – 指定されたバージョン、URL、およびリソース・タイプに一致する、キャッシュされたリソースをリストします。
  • getUpdateAvailableResources–利用可能な更新が存在するリソースを確認し、一覧表示します。アプリケーションがバージョン・ダウンロード・プロトコルを使用している場合は、DownloadService2.ResourceSpecでバージョンを指定してください。それ以外の場合は、バージョンにnull値を指定します。

DownloadService2.ResourceSpecクラスのインスタンスは、確認するリソースの詳細を指定します。

import javax.jnlp.*;
...
DownloadService2 service = (DownloadService2)
                        ServiceManager.lookup("javax.jnlp.DownloadService2");

// create a new instance of ResourceSpec. In this example: 
// - resource is downloaded from a directory on http://foo.bar.com:8080
// - version is 2. [0-9]+
// - resource type is JAR 
ResourceSpec spec = new ResourceSpec("http://foo.bar.com:8080/.*", 2.*, service.JAR)

// returns all cached resources that match the given ResourceSpec  
ResourceSpec results[] = service.getCachedResources(spec);

// returns all resources for which an update is available on the 
// server http://foo.bar.com:8080.
results = service.getUpdateAvailableResources(spec);

DownloadServiceListenerサービスの実装

javax.jnlp.DownloadServiceListenerサービスは、アプリケーションのダウンロードの進捗を示すカスタマイズされたロード進捗インジケータを指定するためのメソッドを提供します。

FileOpenServiceサービスの使用

javax.jnlp.FileOpenServiceサービスが提供するメソッドを使えば、制限された実行環境で実行されているアプリケーションの場合でも、ローカル・ディスクからファイルをインポートできます。

このインタフェースの目的は、HTML使用時にWeb開発者に対して提供されるのと同じタイプのディスク・アクセス機能を、信頼できない可能性のあるWebデプロイ・アプリケーションに対して提供することです。HTMLフォームは、「開く」ダイアログ・ボックスの表示によるファイルの組込みをサポートしています。


import javax.jnlp.*; 
    ... 

    FileOpenService fos; 

    try { 
        fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService"); 
    } catch (UnavailableServiceException e) { 
        fos = null; 
    } 

    if (fos != null) { 
        try { 
            // ask user to select a file through this service 
            FileContents fc = fos.openFileDialog(null, null); 
            // ask user to select multiple files through this service 
            FileContents[] fcs = fos.openMultiFileDialog(null, null); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 

FileSaveServiceサービスの使用

javax.jnlp.FileSaveServiceサービスが提供するメソッドを使えば、制限された実行環境で実行されているアプリケーションの場合でも、ローカル・ディスクにファイルをエクスポートできます。

このインタフェースの目的は、Webブラウザが表示中の内容に関して提供するのと同レベルのディスク・アクセス機能を、信頼できない可能性のあるWebデプロイ・アプリケーションに対して提供することです。  ほとんどのブラウザは、「別名保存」ダイアログ・ボックスをユーザー・インタフェースの一部として提供しています。

import javax.jnlp.*; 
    ... 

    FileSaveService fss; 
    FileOpenService fos; 

    try { 
        fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService"); 
        fss = (FileSaveService)ServiceManager.lookup 
                                   ("javax.jnlp.FileSaveService"); 
    } catch (UnavailableServiceException e) { 
        fss = null; 
        fos = null; 
    } 

    if (fss != null && fos != null) { 
        try { 
            // get a file with FileOpenService 
            FileContents fc = fos.openFileDialog(null, null); 
            // one way to save a file 
            FileContents newfc = fss.saveFileDialog(null, null, 
            fc.getInputStream(), "newFileName.txt"); 
            // another way to save a file 
            FileContents newfc2 = fss.saveAsFileDialog(null, null, fc); 

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

FileContentsの使用」も参照してください。

IntegrationServiceサービスの使用

javax.jnlp.IntegrationServiceサービスは、ショートカットをプログラムで管理するためのメソッドを提供します。アプリケーションではこのサービスを使用して次の操作を実行できます。

  • デスクトップ・ショートカットの作成

  • メニュー・ショートカットの作成

  • ショートカットの問合せおよび削除

  • MIMEタイプまたはファイル拡張子とのアプリケーションの関連付けの作成、問合せおよび削除

import javax.jnlp.*;
...

IntegrationService is = null;
try {
    is = (IntegrationService) ServiceManager.lookup("javax.jnlp.IntegrationService");
} catch(UnavailableServiceException use){
    ...
}

// creates a desktop and system menu shortcut; returns true if the shortcuts 
// were created successfully
boolean result = is.requestShortcut(true, true, null);

//removes all shortcuts for application
result = is.removeShortcuts();

// checks to see if there are shortcuts for the application
result = is.hasMenuShortcut() && is.hasDesktopShortcut());

// associates the application with the specified mime-type and file extensions
String mime = "x-application/aaa";
String [] exts = {"aaa", "abc"};
result = is.requestAssociation(mime, exts);

// checks if the application is associated with the specified mime-type and file extensions
result = is.hasAssociation(mime, exts);

// removes association between the application and the specified mime-type and file extensions
is.removeAssociation(mime, exts);

PrintServiceサービスの使用

javax.jnlp.PrintServiceサービスが提供するメソッドを使えば、制限された実行環境で実行されているアプリケーションの場合でも、印刷機能にアクセスできます。

アプリケーションはこのサービスを使うことで、印刷ジョブを発行できます。Java Web Startは、その要求をユーザーに表示し、ユーザーによって承認されると、その要求をプリンタのキューに追加します。

Java Web Start 5.0から、直接Java Printing APIが使用できるようになりました。サンドボックスでアプリケーションが実行されている場合、PrintPermissionの付与をユーザーに確認するセキュリティ・ダイアログ・ボックスがJava Web Startによって表示されます。JNLP Printing APIを使用する必要はなくなりました。どのJNLPアプリケーションでも、Java Printing APIにフル・アクセスできます。

import javax.jnlp.*; 
    ... 

    PrintService ps; 

    try { 
        ps = (PrintService)ServiceManager.lookup("javax.jnlp.PrintService"); 
    } catch (UnavailableServiceException e) { 
        ps = null; 
    } 

    if (ps != null) { 
        try { 
             
            // get the default PageFormat
            PageFormat pf = ps.getDefaultPage(); 

            // ask the user to customize the PageFormat
            PageFormat newPf = ps.showPageFormatDialog(pf); 

            // print the document with the PageFormat above
            ps.print(new DocToPrint()); 
           
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 

    // Code to construct the Printable Document
    class DocToPrint implements Printable {
        public int print(Graphics g, PageFormat pageformat, int PageIndex){
            // code to generate what you want to print   
        }
    }

PersistenceServiceサービスの使用

javax.jnlp.PersistenceServiceサービスが提供するメソッドを使えば、制限された実行環境で実行されているアプリケーションの場合でも、クライアント・システム上にローカルにデータを格納できます。

このサービスは、cookieメカニズムがHTMLベースのアプリケーションに提供するサービスと類似するように設計されています。cookieを使用すると、少量のデータをローカルのクライアント・システムに保存できます。 そのデータはブラウザによって安全に管理でき、データを保存したページと同じURLのHTMLページによってのみ取得できます。

import javax.jnlp.*; 
    ... 

    PersistenceService ps; 
    BasicService bs; 

    try { 
        ps = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService"); 
        bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService"); 
    } catch (UnavailableServiceException e) { 
        ps = null; 
        bs = null; 
    } 

    if (ps != null && bs != null) { 

        try { 
            // find all the muffins for our URL
            URL codebase = bs.getCodeBase(); 
            String [] muffins = ps.getNames(url); 

            // get the attributes (tags) for each of these muffins. 
            // update the server's copy of the data if any muffins 
            // are dirty 
            int [] tags = new int[muffins.length]; 
            URL [] muffinURLs = new URL[muffins.length]; 
            for (int i = 0; i < muffins.length; i++) { 
                muffinURLs[i] = new URL(codebase.toString() + muffins[i]); 
                tags[i] = ps.getTag(muffinURLs[i]); 
                // update the server if anything is tagged DIRTY 
                if (tags[i] == PersistenceService.DIRTY) { 
                    doUpdateServer(muffinURLs[i]); 
                } 
            } 

            // read in the contents of a muffin and then delete it 
            FileContents fc = ps.get(muffinURLs[0]); 
            long maxsize = fc.getMaxLength(); 
            byte [] buf = new byte[fc.getLength()]; 
            InputStream is = fc.getInputStream(); 
            long pos = 0; 
            while((pos = is.read(buf, pos, buf.length - pos)) > 0) { 
                // just loop 
            } 
            is.close(); 

            ps.delete(muffinURLs[0]); 

            // re-create the muffin and repopulate its data 
            ps.create(muffinURLs[0], maxsize); 
            fc = ps.get(muffinURLs[0]); 
            // don't append 
            OutputStream os = fc.getOutputStream(false); 
            os.write(buf); 
            os.close(); 

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

   void doUpdateServer(URL url) { 
        // update the server's copy of the persistent data 
        // represented by the given URL 
        ... 
        ps.setTag(url, PersistenceService.CACHED); 
   } 

FileContentsの使用

javax.jnlp.FileContentsオブジェクトは、ファイルの名前と内容をカプセル化します。 このクラスのオブジェクトは、FileOpenServiceFileSaveServiceおよびPersistenceServiceによって使用されます。FileContentsのインスタンスを使用してファイルに対する読書きを行う方法の例を次に示します。

import javax.jnlp.*; 
    ... 

    FileOpenService fos; 

    //Initialize fos (see Using the FileOpenService Service example) 
    ... 

    if (fos != null) { 

        try { 

            // get a FileContents object to work with from the 
            // FileOpenService 
            FileContents fc = fos.openFileDialog(null, null); 

            // get the InputStream from the file and read a few bytes 
            byte [] buf = new byte[fc.getLength()]; 
            InputStream is = fc.getInputStream(); 
            int pos = 0; 
            while ((pos = is.read(buf, pos, buf.length - pos)) > 0) { 
                // just loop 
            } 
            is.close(); 

            // get the OutputStream and write the file back out 
            if (fc.canWrite()) { 
               // don't append 
               OutputStream os = fc.getOutputStream(false); 
               os.write(buf); 
            } 

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

JNLPRandomAccessFileの使用

javax.jnlp.JNLPRandomAccessFileのインスタンスは、ランダム・アクセス・ファイルに対する読取りと書込みの両方をサポートします。ランダム・アクセス・ファイルの動作は、ファイル・システムに格納された大規模なバイト配列の動作に似ています。次のサンプル・コードは、JNLPRandomAccessFileのインスタンスを使ってランダム・アクセス・ファイルに対する書込みを行う方法を示したものです。

import javax.jnlp.*; 
    ... 

    FileOpenService fos; 

    //Initialize fos (see Using the FileOpenService Service example) 
    ... 

    if (fos != null) { 
        try { 
           // ask the user to choose a file to open 
           FileContents fc = fos.openFileDialog(null, null); 

           // attempt to increase the maximum file length 
           long grantedLength = fc.getLength(); 
           if (grantedLength + 1024 > fc.getMaxLength()) { 
               // attempt to increase the maximum file size defined by 
               // the client 
               grantedLength = fc.setMaxLength(grantedLength + 1024); 
           } 

           // if we were able to increase the maximum allowable file size, 
           // get a JNLPRandomAccessFile representation of the file, and 
           // write to it 
           if (fc.getMaxSize() > fc.getLength() && fc.canWrite()) { 
               JNLPRandomAccessFile raf = fc.getRandomAccessFile("rw"); 
               raf.seek(raf.length() - 1); 
               raf.writeUTF("Java Web Start!"); 
               raf.close(); 
           } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 

SingleInstanceServiceサービスの使用

javax.jnlp.SingleInstanceServiceは、アプリケーションが自身をシングルトンとして登録し、また、アプリケーションの異なるインスタンスから渡された引数を処理するためのリスナーを登録する一連のメソッドを提供します。

import javax.jnlp.*; 
    ... 

    SingleInstanceService sis; 

    ... 

    try { 
        sis = 
(SingleInstanceService)ServiceManager.lookup("javax.jnlp.SingleInstanceService");
    } catch (UnavailableServiceException e) { sis=null; }

    ...

    
    // Register the single instance listener at the start of your application
    
    SISListener sisL = new SISListener();
    sis.addSingleInstanceListener(sisL);

    ...
    
    
    // Remember to remove the listener before your application exits
    
    sis.removeSingleInstanceListener(sisL);
    System.exit(0);

    
    // Implement the SingleInstanceListener for your application
    
    class SISListener implements SingleInstanceListener {
        public void newActivation(String[] params) {
            
            // your code to handle the new arguments here
            
            ...
        }
    }

ExtendedServiceサービスの使用

javax.jnlp.ExtendedServiceは、現在のJNLP APIに対する追加サポートを提供します。これを使用すると、アプリケーションは、クライアントのファイル・システムの特定のファイルを開くことができます。

import javax.jnlp.*; 
    ... 

    ExtendedService es; 

    ... 

    try { 
        es = 
(ExtendedService)ServiceManager.lookup("javax.jnlp.ExtendedService");
    } catch (UnavailableServiceException e) { es=null; }

    ...

    
    // Open a specific file in the local machine
    
    File a = new File("c:\somefile.txt");

    ...
    
    
    // Java Web Start will pop up a dialog asking the user to grant permission
    // to read/write the file c:\somefile.txt
    
    FileContents fc_a = es.openFile(a);

    
    // You can now use the FileContents object to read/write the file
    
    ...

    
    // Open a specific set of files in the local machine
    
    File[2] fArray = new File[2];
    
    fArray[0] = a;
    fArray[1] = new File("c:\anotherFile.txt");

    
    // Java Web Start will pop up a dialog asking the user to grant permission
    // to read/write files in fArray
    
    FileContents[] fc_Array = es.OpenFiles(fArray);

    
    // You can now read/write the set of files in fc_Array using the
    // FileContents objects
    
    }

javawsコマンドの使用の詳細は、Java Platform, Standard Editionツール・リファレンスjavawsを参照してください。