如何使用Gretty插件在Jetty中运行WAR?

时间:2019-07-10 20:02:22

标签: gradle gretty

我当前的目标是获取在我的机器上的Jetty实例中运行的Web应用程序的启动权,以便我可以针对它编写Selenium测试。 Gretty插件似乎正在加载,但是我无法找到有关如何创建和配置任务的实际说明。

部分问题是不同版本的Gretty插件存在混淆。首先将其加载是一种反复试验的练习。

我正在尝试使用Gradle 5.4.1和Gretty 2.3.1,我认为它们是当前版本(当前)。

我有三个子项目,“ laoi”依赖于“ aofl”,依赖于“ efl”。老版本生成一个WAR文件。任务appRunWar似乎想创建并运行自己的WAR文件,而不是使用我的文件(至少这似乎正在发生)。

settings.gradle:

rootProject.name = 'aoi'
include 'cm', 'efl', 'aofl', 'laoi', 'uiTest'

build.gradle(laoi):

static def getDate() {
    return new Date().format('yyyyMMdd-HHmmss')
}

final String timepickerAddonVersion = '1.6.3'
final String datatablesVersion = '1.10.19'
final String jqueryUIVersion = '1.12.1'
final String jqueryVersion = '3.2.1'

if (null == System.properties['aoi.release'] || null == System.properties['aoi.iteration']) {
    if (null == System.env['RELEASE'] || null == System.env['ITERATION']) {
        ext.ITERATION = "un"
        ext.RELEASE = "dev"
    } else {
        ext.ITERATION = System.env['ITERATION']
        ext.RELEASE = System.env['RELEASE']
    }
} else {
    ext.ITERATION = System.properties['aoi.iteration']
    ext.RELEASE = System.properties['aoi.release']
}
System.setProperty('aoi.iteration', ext.ITERATION)
System.setProperty('aoi.release', ext.RELEASE)

if (null == System.properties['aoi.manifest']) {
    if (null == System.env['MANIFEST']) {
        System.out.println("Using default manifest name.")
        ext.MANIFEST = "aoiManifest"
        System.out.println("Manifest: ${ext.MANIFEST}")
    } else {
        ext.MANIFEST = System.env['MANIFEST']
    }
} else {
    ext.MANIFEST = System.properties['aoi.manifest']
}
System.setProperty('aoi.manifest', ext.MANIFEST)
System.out.println("Manifest: ${ext.MANIFEST}")

final String warFileName = 'aoi-'+ System.properties['aoi.release'] +'_'+ System.properties['aoi.iteration'] + ".war"
println "War file name: ${warFileName}"

final String sourceManifestName = "${ext.MANIFEST}.xml"
println "Source manifest name: ${sourceManifestName}"

def rootLibs = new File("${rootDir}/libs")

repositories {
    mavenCentral()
    jcenter()
    flatDir {
        dirs "${rootDir}/libs"
    }
}


compileScala {
    dependsOn ":efl:test", ":aofl:test"
}

task copyManifest(type: Copy) {
    from('src/main/resources') {
        include sourceManifestName
        rename sourceManifestName, 'aoiManifest.xml'
    }
    into("${buildDir}/resources/main/bootstrap/liftweb")
}

task createVersionFile {
    dependsOn "processResources"
    doLast {
        new File("${buildDir}/resources/main/aoiVersion.conf").text = "AOI_VERSION=" + System.properties['aoi.release'] +'-'+ System.properties['aoi.iteration'] + " (" + getDate() + ")"
        new File("${buildDir}/resources/main/WebJarVersions.conf").text =
"""jQuery-Timepicker-Addon=$timepickerAddonVersion
datatables=$datatablesVersion
jquery=$jqueryVersion
jquery-ui=$jqueryUIVersion
jquery-ui-themes=$jqueryUIVersion
"""
    }
}

war {
    dependsOn ":aofl:test", "compileScala", "copyManifest", "processResources", "createVersionFile"
    setDestinationDirectory(rootLibs)

    setArchiveFileName(warFileName)

    from('${buildDir}/resources/main') {
        include '**/*.xml'
        into("classes")
    }
}

dependencies {
    implementation project(":efl")
    implementation project(":aofl")
    implementation "org.webjars:jquery:$jqueryVersion"
    implementation "org.webjars:jquery-ui:$jqueryUIVersion"
    implementation "org.webjars:jquery-ui-themes:$jqueryUIVersion"
    implementation "org.webjars:datatables:$datatablesVersion"
    implementation "org.webjars:jQuery-Timepicker-Addon:$timepickerAddonVersion"
    implementation 'org.webjars:webjars-servlet-2.x:1.1'
}

1 个答案:

答案 0 :(得分:0)

由于没有答案,我不得不自己寻找答案。

Jetty具有一项功能,允许您将WAR文件拖放到目录中并将其加载。为了利用它,您必须找出要查找的目录,或者告诉它要查找的目录。我选择了第二个选项。

指定部署目录的最简单方法是将其放在gretty选项中指定的“ serverConfigFile”中。

gretty {
    serverConfigFile = "$contextFile"
    servletContainer = 'jetty9.4'
    jvmArgs <--- a bunch of arguments go here --->
}

Jetty在“ etc”目录中附带了一堆配置文件。我恶意和公然地窃了主要的Jetty配置文件以及Deployment Manager配置文件-但将路径设置为我选择的一个。我创建了一个写入serverConfigFile的任务。

task createJettyContextsFile {
    doLast {
        new File("$contextFile").text =
"""<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">

<!-- =============================================================== -->
<!-- Documentation of this file format can be found at:              -->
<!-- https://www.eclipse.org/jetty/documentation/current/       -->
<!--                                                                 -->
<!-- Additional configuration files are available in JETTY_HOME/etc -->
<!-- and can be mixed in. See start.ini file for the default         -->
<!-- configuration files.                                            -->
<!--                                                                 -->
<!-- For a description of the configuration mechanism, see the       -->
<!-- output of:                                                      -->
<!--   java -jar start.jar -?                                        -->
<!-- =============================================================== -->

<!-- =============================================================== -->
<!-- Configure a Jetty Server instance with an ID "Server"           -->
<!-- Other configuration files may also configure the "Server"       -->
<!-- ID, in which case they are adding configuration to the same     -->
<!-- instance.  If other configuration have a different ID, they     -->
<!-- will create and configure another instance of Jetty.            -->
<!-- Consult the javadoc of o.e.j.server.Server for all              -->
<!-- configuration that may be set here.                             -->
<!-- =============================================================== -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
    <Arg name="threadpool"><Ref refid="threadPool"/></Arg>

    <!-- =========================================================== -->
    <!-- Add shared Scheduler instance                               -->
    <!-- =========================================================== -->
    <Call name="addBean">
      <Arg>
        <New class="org.eclipse.jetty.util.thread.ScheduledExecutorScheduler"/>
      </Arg>
    </Call>

    <!-- =========================================================== -->
    <!-- Http Configuration.                                         -->
    <!-- This is a common configuration instance used by all         -->
    <!-- connectors that can carry HTTP semantics (HTTP, HTTPS, etc.)-->
    <!-- It configures the non wire protocol aspects of the HTTP     -->
    <!-- semantic.                                                   -->
    <!--                                                             -->
    <!-- This configuration is only defined here and is used by      -->
    <!-- reference from other XML files such as jetty-http.xml,      -->
    <!-- jetty-https.xml and other configuration files which         -->
    <!-- instantiate the connectors.                                 -->
    <!--                                                             -->
    <!-- Consult the javadoc of o.e.j.server.HttpConfiguration       -->
    <!-- for all configuration that may be set here.                 -->
    <!-- =========================================================== -->
    <New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
      <Set name="secureScheme"><Property name="jetty.httpConfig.secureScheme" default="https" /></Set>
      <Set name="securePort"><Property name="jetty.httpConfig.securePort" deprecated="jetty.secure.port" default="8443" /></Set>
      <Set name="outputBufferSize"><Property name="jetty.httpConfig.outputBufferSize" deprecated="jetty.output.buffer.size" default="32768" /></Set>
      <Set name="outputAggregationSize"><Property name="jetty.httpConfig.outputAggregationSize" deprecated="jetty.output.aggregation.size" default="8192" /></Set>
      <Set name="requestHeaderSize"><Property name="jetty.httpConfig.requestHeaderSize" deprecated="jetty.request.header.size" default="8192" /></Set>
      <Set name="responseHeaderSize"><Property name="jetty.httpConfig.responseHeaderSize" deprecated="jetty.response.header.size" default="8192" /></Set>
      <Set name="sendServerVersion"><Property name="jetty.httpConfig.sendServerVersion" deprecated="jetty.send.server.version" default="true" /></Set>
      <Set name="sendDateHeader"><Property name="jetty.httpConfig.sendDateHeader" deprecated="jetty.send.date.header" default="false" /></Set>
      <Set name="headerCacheSize"><Property name="jetty.httpConfig.headerCacheSize" default="4096" /></Set>
      <Set name="delayDispatchUntilContent"><Property name="jetty.httpConfig.delayDispatchUntilContent" deprecated="jetty.delayDispatchUntilContent" default="true"/></Set>
      <Set name="maxErrorDispatches"><Property name="jetty.httpConfig.maxErrorDispatches" default="10"/></Set>
      <Set name="blockingTimeout"><Property deprecated="jetty.httpConfig.blockingTimeout" name="jetty.httpConfig.blockingTimeout.DEPRECATED" default="-1"/></Set>
      <Set name="persistentConnectionsEnabled"><Property name="jetty.httpConfig.persistentConnectionsEnabled" default="true"/></Set>
      <Set name="requestCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.requestCookieCompliance" deprecated="jetty.httpConfig.cookieCompliance" default="RFC6265"/></Arg></Call></Set>
      <Set name="responseCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.responseCookieCompliance" default="RFC6265"/></Arg></Call></Set>
      <Set name="multiPartFormDataCompliance"><Call class="org.eclipse.jetty.server.MultiPartFormDataCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.multiPartFormDataCompliance" default="RFC7578"/></Arg></Call></Set>
    </New>

    <!-- =========================================================== -->
    <!-- Set the default handler structure for the Server            -->
    <!-- A handler collection is used to pass received requests to   -->
    <!-- both the ContextHandlerCollection, which selects the next   -->
    <!-- handler by context path and virtual host, and the           -->
    <!-- DefaultHandler, which handles any requests not handled by   -->
    <!-- the context handlers.                                       -->
    <!-- Other handlers may be added to the "Handlers" collection,   -->
    <!-- for example the jetty-requestlog.xml file adds the          -->
    <!-- RequestLogHandler after the default handler                 -->
    <!-- =========================================================== -->
    <Set name="handler">
      <New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
        <Set name="handlers">
         <Array type="org.eclipse.jetty.server.Handler">
           <Item>
             <New id="Contexts" class="org.eclipse.jetty.server.handler.ContextHandlerCollection"/>
           </Item>
           <Item>
             <New id="DefaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler"/>
           </Item>
         </Array>
        </Set>
      </New>
    </Set>

    <!-- =========================================================== -->
    <!-- extra server options                                        -->
    <!-- =========================================================== -->
    <Set name="stopAtShutdown"><Property name="jetty.server.stopAtShutdown" default="true"/></Set>
    <Set name="stopTimeout"><Property name="jetty.server.stopTimeout" default="5000"/></Set>
    <Set name="dumpAfterStart"><Property name="jetty.server.dumpAfterStart" deprecated="jetty.dump.start" default="false"/></Set>
    <Set name="dumpBeforeStop"><Property name="jetty.server.dumpBeforeStop" deprecated="jetty.dump.stop" default="false"/></Set>

  <Call name="addBean">
    <Arg>
      <New id="DeploymentManager" class="org.eclipse.jetty.deploy.DeploymentManager">
        <Set name="contexts">
          <Ref refid="Contexts" />
        </Set>
        <Call name="setContextAttribute">
          <Arg>org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern</Arg>
          <Arg>.*/[^/]*servlet-api-[^/]*\\.jar\$|.*/javax.servlet.jsp.jstl-.*\\.jar\$|.*/org.apache.taglibs.taglibs-standard-impl-.*\\.jar\$</Arg>
        </Call>

        <Call id="webappprovider" name="addAppProvider">
          <Arg>
            <New class="org.eclipse.jetty.deploy.providers.WebAppProvider">
              <Set name="monitoredDirName">
                <Property>
                  <Name>jetty.deploy.monitoredPath</Name>
                  <Default>
                    <Property name="jetty.deploy.monitoredDir" deprecated="jetty.deploy.monitoredDirName" default="$deployDirectory"/>
                  </Default>
                </Property>
              </Set>
              <Set name="defaultsDescriptor">
                <Property>
                  <Name>jetty.deploy.defaultsDescriptorPath</Name>
                  <Default>
                    <Property name="jetty.home" default="." />/etc/webdefault.xml
                  </Default>
                </Property>
              </Set>
              <Set name="scanInterval"><Property name="jetty.deploy.scanInterval" default="1"/></Set>
              <Set name="extractWars"><Property name="jetty.deploy.extractWars" default="true"/></Set>
              <Set name="configurationManager">
                <New class="org.eclipse.jetty.deploy.PropertiesConfigurationManager">
                </New>
              </Set>
            </New>
          </Arg>
        </Call>
      </New>
    </Arg>
  </Call>

</Configure>
"""
    }
}

然后我添加了一个任务,将WAR文件复制到正确的目录中。

task copyWar(type: Copy) {
    dependsOn ":cm:buildPS", ":laoi:war", 'createJettyContextsFile'
    from("$rootLibs") {
        include "*.war"
    }
    into("$deployDirectory")
}

我不得不稍微调整一下任务的依赖关系,但是现在启动Jetty服务器的Gretty任务都将在正确部署我的WAR文件的情况下运行。