このセクションでは、次のトピックについて説明します。
BasicServiceサービスの使用ClipboardServiceサービスの使用DownloadServiceサービスの使用DownloadService2サービスの使用DownloadServiceListenerサービスの実装FileOpenServiceサービスの使用FileSaveServiceサービスの使用IntegrationServiceサービスの使用PrintServiceサービスの使用PersistenceServiceサービスの使用FileContentsの使用JNLPRandomAccessFileの使用SingleInstanceServiceサービスの使用ExtendedServiceサービスの使用JNLP APIは、標準Java Platform Standard Edition APIを使用して利用できない追加情報をアプリケーションに提供します。 信頼できないアプリケーションに対しては、JNLP APIは、通常はセキュリティ・マネージャによって防止されるファイルの読取りと書込み、クリップボードやプリンタへのアクセスなどの操作のメソッドを提供します。
JNLP APIのパブリック・クラスおよびインタフェースは、JREのlibディレクトリにあるjavaws.jarファイルに含まれています。 このJARファイルは、JNLP APIを使用するソース・ファイルをコンパイルするときにクラスパスに含める必要があります。 たとえば、Windows上では次のようにします。
javac -classpath .;javaws.jar *.java
BasicServiceサービスの使用javax.jnlp.BasicServiceサービスが提供する一連のメソッドを使えば、環境に対する問い合わせや対話を行えます。これらのメソッドは、AppletContextがJavaアプレットに対して提供するメソッドに似ています。
showURLメソッドはJNLP APIを使って、プラットフォーム上のデフォルト・ブラウザに対し、指定されたURLを表示するよう指示します。 このメソッドは、要求が成功した場合にはtrueを返し、そうでない場合にはfalseを返します。
import javax.jnlp.*;
...
//URLを表示するメソッド
boolean showURL(URL url) {
try {
//Javax.jnlp.BasicServiceオブジェクトを検索する
BasicService bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
//showDocumentメソッドを呼び出す
return bs.showDocument(url);
} catch(UnavailableServiceException ue) {
//サービスがサポートされていない
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) {
//システム・クリップボードの内容を文字列の選択範囲に設定する
StringSelection ss = new StringSelection("Java Web Start!");
cs.setContents(ss);
//システム・クリップボードの内容を取得し、出力する
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サービスの使用Java SE 6 update 18リリースで導入されたjavax.jnlp.IntegrationServiceサービスには、ショートカットをプログラムで管理するためのメソッドがあります。 アプリケーションではこのサービスを使用して次の操作を実行できます。
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が使用できるようになりました。サンドボックスでアプリケーションが実行されている場合、このAPIを起動すると、PrintPermissionの付与をユーザーに確認するセキュリティ・ダイアログが表示されます。 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オブジェクトは、ファイルの名前と内容をカプセル化します。 このクラスのオブジェクトは、FileOpenService、FileSaveService、および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の使用方法の詳細は、javawsのドキュメント(「Solaris、LinuxおよびmacOS」またはWindows)を参照してください。