WAR ファイルを JAR ファイルに再パッケージ化する

このドキュメントでは、Java 8 アプリケーションを Java 11/17 ランタイムで実行する JAR ファイルとして再パッケージ化する方法を説明します。

アプリケーションには、ポート 8080 で HTTP リクエストに応答するウェブサーバーを起動する Main クラスが必要です。このポートは PORT 環境変数で指定できます。

次に例を示します。

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration.ClassList;
import org.eclipse.jetty.webapp.WebAppContext;

/** Simple Jetty Main that can execute a WAR file when passed as an argument. */
public class Main {

  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage: need a relative path to the war file to execute");
      System.exit(1);
    }
    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StrErrLog");
    System.setProperty("org.eclipse.jetty.LEVEL", "INFO");

    // Create a basic Jetty server object that will listen on port defined by
    // the PORT environment variable when present, otherwise on 8080.
    int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
    Server server = new Server(port);

    // The WebAppContext is the interface to provide configuration for a web
    // application. In this example, the context path is being set to "/" so
    // it is suitable for serving root context requests.
    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setWar(args[0]);
    ClassList classlist = ClassList.setServerDefault(server);

    // Enable Annotation Scanning.
    classlist.addBefore(
        "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
        "org.eclipse.jetty.annotations.AnnotationConfiguration");

    // Set the the WebAppContext as the ContextHandler for the server.
    server.setHandler(webapp);

    // Start the server! By using the server.join() the server thread will
    // join with the current thread. See
    // "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()"
    // for more details.
    server.start();
    server.join();
  }
}

WAR 移行の例

次の手順では、App Engine Java 8 hello-world アプリケーションを Java 11/17 ランタイムで実行する JAR として再パッケージ化する方法を説明します。

この移行では appengine-simple-jetty-main アーティファクトを使用します。これにより、Main クラスにシンプルな Jetty ウェブサーバーが与えられます。Jetty ウェブサーバーは WAR ファイルを読み込み、実行可能な JAR ファイルにパッケージ化します。

  1. ローカルマシンに埋め込み型 Jetty サーバー アーティファクトのクローンを作成します。

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples
    

    zip 形式のサンプルをダウンロードし、ファイルを抽出してもかまいません。

  2. サンプルコードが入っているディレクトリに移動します。

    cd java-docs-samples/appengine-java11/appengine-simple-jetty-main/
    
  3. 依存関係をローカルにインストールします。

    mvn install
    
  4. pom.xml ファイルに次のコードを追加します。

    • appengine-simple-jetty-main 依存関係:
      <dependency>
        <groupId>com.example.appengine</groupId>
        <artifactId>simple-jetty-main</artifactId>
        <version>1</version>
        <scope>provided</scope>
      </dependency>
    • maven-dependency プラグイン:
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.6.1</version>
        <executions>
          <execution>
            <id>copy</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>
                ${project.build.directory}/appengine-staging
              </outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
      App Engine は ${build.directory}/appengine-staging ディレクトリに配置されたファイルをデプロイします。maven-dependency プラグインをビルドに追加すると、指定した依存関係が正しいフォルダにインストールされます。
  5. entrypoint 要素を app.yaml ファイルに作成して appengine-simple-jetty-main オブジェクトを呼び出し、WAR ファイルを引数として渡します。WAR バージョンは、pom.xml ファイルに記載されているバージョンと同じである必要があります。

    runtime: java
    env: flex
    runtime_config:
      operating_system: ubuntu18
      runtime_version: 11
    entrypoint: 'java -cp "*" com.example.appengine.jetty.Main helloworld-1.war'
    handlers:
    - url: /.*
      script: this field is required, but ignored
    
    manual_scaling:
      instances: 1
  6. アプリケーションをローカルで実行するには:

    1. アプリケーションをパッケージ化します。

      mvn clean package
      
    2. WAR ファイルを引数にしてサーバーを起動します。

      たとえば、java-docs-samples/appengine-java11/appengine-simple-jetty-main/ フォルダから次のコマンドを実行すると、helloworld-war サンプルの中のサーバーを起動できます。

      mvn exec:java -Dexec.args="../flexible/java-11/helloworld-war/target/helloworld-1.war"
      
    3. ウェブブラウザに次のアドレスを入力します。

      http://localhost:8080

  7. Maven プラグインを使用してアプリケーションをデプロイするには:

    mvn package appengine:deploy -Dapp.deploy.projectId=PROJECT_ID

    PROJECT_ID は、Google Cloud プロジェクトの ID に置き換えます。pom.xml ファイルですでにプロジェクト ID を指定している場合は、実行するコマンドに -Dapp.deploy.projectId プロパティを含める必要はありません。