Ripacchettizzazione di un file WAR in un file JAR

Questo documento descrive come eseguire il nuovo pacchettizzazione di un'applicazione Java 8 come file JAR da eseguire sui runtime Java 11/17.

L'applicazione deve avere una classe Main che avvii un server web che risponda alle richieste HTTP sulla porta 8080, che potrebbe essere specificata dalla variabile di ambiente PORT.

Ad esempio:

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();
  }
}

Esempio di migrazione WAR

Le seguenti istruzioni mostrano come eseguire il nuovo pacchettizzazione di un'applicazione App Engine Java 8 hello-world come JAR da eseguire nel runtime Java 11/17.

La migrazione utilizza l'elemento appengine-simple-jetty-main. Fornisce una classe Main con un semplice server web Jetty che carica un file WAR e pacchettizza la tua app in un file JAR eseguibile:

  1. Clona l'elemento Embedded Jetty Server sulla tua macchina locale:

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

    In alternativa, puoi scaricare il sample come file ZIP ed estrarlo.

  2. Passa alla directory che contiene il codice di esempio:

    cd java-docs-samples/appengine-java11/appengine-simple-jetty-main/
    
  3. Installa la dipendenza localmente:

    mvn install
    
  4. Aggiungi il codice seguente al file pom.xml:

    • appengine-simple-jetty-main dipendenza:
      <dependency>
        <groupId>com.example.appengine</groupId>
        <artifactId>simple-jetty-main</artifactId>
        <version>1</version>
        <scope>provided</scope>
      </dependency>
    • maven-dependency plugin:
      <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 esegue il deployment dei file nella directory ${build.directory}/appengine-staging. Aggiungendo il plug-in maven-dependency alla build, App Engine installa le dipendenze specificate nella cartella corretta.
  5. Crea un elemento entrypoint nel file app.yaml per chiamare l'oggetto appengine-simple-jetty-main e passare il file WAR come argomento. La versione di WAR deve essere la stessa indicata nel file 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. Per eseguire l'applicazione in locale:

    1. Crea il pacchetto dell'applicazione:

      mvn clean package
      
    2. Avvia il server con il file WAR come argomento.

      Ad esempio, puoi avviare il server nell'esempio helloworld-war eseguendo il seguente comando dalla directory java-docs-samples/appengine-java11/appengine-simple-jetty-main/:

      mvn exec:java -Dexec.args="../flexible/java-11/helloworld-war/target/helloworld-1.war"
      
    3. Nel browser web, inserisci il seguente indirizzo:

      http://localhost:8080

  7. Per eseguire il deployment dell'applicazione utilizzando il plug-in Maven:

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

    Sostituisci PROJECT_ID con l'ID del tuo progetto Google Cloud. Se il tuo file pom.xml specifica già il tuo ID progetto, non devi includere la proprietà -Dapp.deploy.projectId nel comando eseguito.