resolve issues between jetty 8 and jetty 9 maven plugin that jan noticed

This commit is contained in:
Jesse McConnell 2012-11-01 12:08:07 -05:00
parent 3683653052
commit 2ab0ef25bd
13 changed files with 570 additions and 371 deletions

View File

@ -483,7 +483,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo
if (connectors == null || connectors.length == 0)
{
//if a SystemProperty -Djetty.port=<portnum> has been supplied, use that as the default port
this.connectors = new Connector[] { this.server.createDefaultConnector(server, System.getProperty(PORT_SYSPROPERTY, null)) };
this.connectors = new Connector[] { this.server.createDefaultConnector(System.getProperty(PORT_SYSPROPERTY, null)) };
this.server.setConnectors(this.connectors);
}
}

View File

@ -16,58 +16,55 @@
// ========================================================================
//
/**
*
*/
package org.eclipse.jetty.maven.plugin;
import java.io.IOException;
public class ConsoleScanner extends Thread
public class ConsoleScanner extends Thread
{
private final AbstractJettyMojo mojo;
public ConsoleScanner(AbstractJettyMojo mojo)
public ConsoleScanner(AbstractJettyMojo mojo)
{
this.mojo = mojo;
setName("Console scanner");
setDaemon(true);
}
public void run()
{
try
public void run()
{
try
{
while (true)
while (true)
{
checkSystemInput();
getSomeSleep();
}
}
catch (IOException e)
}
catch (IOException e)
{
mojo.getLog().warn(e);
}
}
private void getSomeSleep()
private void getSomeSleep()
{
try
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
}
catch (InterruptedException e)
{
mojo.getLog().debug(e);
}
}
private void checkSystemInput() throws IOException
{
private void checkSystemInput() throws IOException
{
while (System.in.available() > 0) {
int inputByte = System.in.read();
if (inputByte >= 0)
if (inputByte >= 0)
{
char c = (char)inputByte;
if (c == '\n') {
@ -76,12 +73,12 @@ public class ConsoleScanner extends Thread
}
}
}
/**
* Skip buffered bytes of system console.
*/
private void clearInputBuffer()
private void clearInputBuffer()
{
try
{
@ -101,9 +98,9 @@ public class ConsoleScanner extends Thread
catch (IOException e)
{
mojo.getLog().warn("Error discarding console input buffer", e);
}
}
}
private void restartWebApp()
{
try

View File

@ -1,46 +1,45 @@
//
// ========================================================================
// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.maven.plugin;
/**
* <p>
* This goal is used to run Jetty with a pre-assembled war.
* </p>
* <p>
* It accepts exactly the same options as the <a href="run-war-mojo.html">run-war</a> goal.
* However, it doesn't assume that the current artifact is a
* webapp and doesn't try to assemble it into a war before its execution.
* So using it makes sense only when used in conjunction with the
* <a href="run-war-mojo.html#webApp">webApp</a> configuration parameter pointing to a pre-built WAR.
* </p>
* <p>
* This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested
* HTTP client components.
* </p>
*
* @goal deploy-war
* @requiresDependencyResolution runtime
* @execute phase="validate"
* @description Deploy a pre-assembled war
*
*/
public class JettyDeployWar extends JettyRunWarMojo
{
}
//
// ========================================================================
// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.maven.plugin;
/**
* <p>
* This goal is used to run Jetty with a pre-assembled war.
* </p>
* <p>
* It accepts exactly the same options as the <a href="run-war-mojo.html">run-war</a> goal.
* However, it doesn't assume that the current artifact is a
* webapp and doesn't try to assemble it into a war before its execution.
* So using it makes sense only when used in conjunction with the
* <a href="run-war-mojo.html#webApp">webApp</a> configuration parameter pointing to a pre-built WAR.
* </p>
* <p>
* This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested
* HTTP client components.
* </p>
*
* @goal deploy-war
* @requiresDependencyResolution runtime
* @execute phase="validate"
* @description Deploy a pre-assembled war
*
*/
public class JettyDeployWar extends JettyRunWarMojo
{
}

View File

@ -18,23 +18,32 @@
package org.eclipse.jetty.maven.plugin;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
@ -42,7 +51,10 @@ import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.repository.ComponentDependency;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.resource.Resource;
/**
@ -64,7 +76,7 @@ import org.eclipse.jetty.util.IO;
* There is a <a href="run-war-mojo.html">reference guide</a> to the configuration parameters for this plugin, and more detailed information
* with examples in the <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin/">Configuration Guide</a>.
* </p>
*
*
* @goal run-forked
* @requiresDependencyResolution compile+runtime
* @execute phase="test-compile"
@ -72,17 +84,17 @@ import org.eclipse.jetty.util.IO;
*
*/
public class JettyRunForkedMojo extends AbstractMojo
{
{
public String PORT_SYSPROPERTY = "jetty.port";
/**
* Whether or not to include dependencies on the plugin's classpath with &lt;scope&gt;provided&lt;/scope&gt;
* Use WITH CAUTION as you may wind up with duplicate jars/classes.
* @parameter default-value="false"
*/
protected boolean useProvidedScope;
/**
* The maven project.
*
@ -91,9 +103,9 @@ public class JettyRunForkedMojo extends AbstractMojo
* @readonly
*/
private MavenProject project;
/**
* If true, the &lt;testOutputDirectory&gt;
* and the dependencies of &lt;scope&gt;test&lt;scope&gt;
@ -101,27 +113,27 @@ public class JettyRunForkedMojo extends AbstractMojo
* @parameter alias="useTestClasspath" default-value="false"
*/
private boolean useTestScope;
/**
* The default location of the web.xml file. Will be used
* if &lt;webAppConfig&gt;&lt;descriptor&gt; is not set.
*
*
* @parameter expression="${basedir}/src/main/webapp/WEB-INF/web.xml"
* @readonly
*/
private String webXml;
/**
* The target directory
*
*
* @parameter expression="${project.build.directory}"
* @required
* @readonly
*/
protected File target;
/**
* The temporary directory to use for the webapp.
* Defaults to target/tmp
@ -132,26 +144,26 @@ public class JettyRunForkedMojo extends AbstractMojo
*/
protected File tmpDirectory;
/**
* The directory containing generated classes.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*
*
*/
private File classesDirectory;
/**
* The directory containing generated test classes.
*
*
* @parameter expression="${project.build.testOutputDirectory}"
* @required
*/
private File testClassesDirectory;
/**
* Root directory for all html/jsp etc files
*
@ -159,34 +171,34 @@ public class JettyRunForkedMojo extends AbstractMojo
*
*/
private File webAppSourceDirectory;
/**
* Directories that contain static resources
* for the webapp. Optional.
*
*
* @parameter
*/
private File[] resourceBases;
/**
* If true, the webAppSourceDirectory will be first on the list of
* resources that form the resource base for the webapp. If false,
* If true, the webAppSourceDirectory will be first on the list of
* resources that form the resource base for the webapp. If false,
* it will be last.
*
*
* @parameter default-value="true"
*/
private boolean baseAppFirst;
/**
* Location of jetty xml configuration files whose contents
* Location of jetty xml configuration files whose contents
* will be applied before any plugin configuration. Optional.
* @parameter
*/
private String jettyXml;
/**
* The context path for the webapp. Defaults to the
* name of the webapp's artifact.
@ -205,71 +217,71 @@ public class JettyRunForkedMojo extends AbstractMojo
*/
private String contextXml;
/**
/**
* @parameter expression="${jetty.skip}" default-value="false"
*/
private boolean skip;
/**
* Port to listen to stop jetty on executing -DSTOP.PORT=&lt;stopPort&gt;
* Port to listen to stop jetty on executing -DSTOP.PORT=&lt;stopPort&gt;
* -DSTOP.KEY=&lt;stopKey&gt; -jar start.jar --stop
* @parameter
* @required
*/
protected int stopPort;
/**
* Key to provide when stopping jetty on executing java -DSTOP.KEY=&lt;stopKey&gt;
* Key to provide when stopping jetty on executing java -DSTOP.KEY=&lt;stopKey&gt;
* -DSTOP.PORT=&lt;stopPort&gt; -jar start.jar --stop
* @parameter
* @required
*/
protected String stopKey;
/**
* Arbitrary jvm args to pass to the forked process
* @parameter
*/
private String jvmArgs;
/**
* @parameter expression="${plugin.artifacts}"
* @readonly
*/
private List pluginArtifacts;
/**
* @parameter expression="${plugin}"
* @readonly
*/
private PluginDescriptor plugin;
/**
* @parameter expression="true" default-value="true"
*/
private boolean waitForChild;
private Process forkedProcess;
private Random random;
public class ShutdownThread extends Thread
{
public ShutdownThread()
{
super("RunForkedShutdown");
}
public void run ()
{
if (forkedProcess != null && waitForChild)
@ -278,7 +290,7 @@ public class JettyRunForkedMojo extends AbstractMojo
}
}
}
/**
* @see org.apache.maven.plugin.Mojo#execute()
*/
@ -295,20 +307,20 @@ public class JettyRunForkedMojo extends AbstractMojo
random = new Random();
startJettyRunner();
}
public List<String> getProvidedJars() throws MojoExecutionException
{
{
//if we are configured to include the provided dependencies on the plugin's classpath
//(which mimics being on jetty's classpath vs being on the webapp's classpath), we first
//try and filter out ones that will clash with jars that are plugin dependencies, then
//create a new classloader that we setup in the parent chain.
if (useProvidedScope)
{
List<String> provided = new ArrayList<String>();
List<String> provided = new ArrayList<String>();
for ( Iterator<Artifact> iter = project.getArtifacts().iterator(); iter.hasNext(); )
{
{
Artifact artifact = iter.next();
if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !isPluginArtifact(artifact))
{
@ -322,16 +334,16 @@ public class JettyRunForkedMojo extends AbstractMojo
else
return null;
}
/* ------------------------------------------------------------ */
public File prepareConfiguration() throws MojoExecutionException
{
try
{
{
//work out the configuration based on what is configured in the pom
File propsFile = new File (target, "fork.props");
if (propsFile.exists())
propsFile.delete();
propsFile.delete();
propsFile.createNewFile();
//propsFile.deleteOnExit();
@ -358,9 +370,9 @@ public class JettyRunForkedMojo extends AbstractMojo
//sort out base dir of webapp
if (webAppSourceDirectory != null)
props.put("base.dir", webAppSourceDirectory.getAbsolutePath());
//sort out the resource base directories of the webapp
StringBuilder builder = new StringBuilder();
StringBuilder builder = new StringBuilder();
if (baseAppFirst)
{
add((webAppSourceDirectory==null?null:webAppSourceDirectory.getAbsolutePath()), builder);
@ -371,7 +383,7 @@ public class JettyRunForkedMojo extends AbstractMojo
}
}
else
{
{
if (resourceBases != null)
{
for (File resDir:resourceBases)
@ -380,7 +392,7 @@ public class JettyRunForkedMojo extends AbstractMojo
add((webAppSourceDirectory==null?null:webAppSourceDirectory.getAbsolutePath()), builder);
}
props.put("res.dirs", builder.toString());
//web-inf classes
List<File> classDirs = getClassesDirs();
@ -397,7 +409,7 @@ public class JettyRunForkedMojo extends AbstractMojo
{
props.put("classes.dir", classesDirectory.getAbsolutePath());
}
if (useTestScope && testClassesDirectory != null)
{
props.put("testClasses.dir", testClassesDirectory.getAbsolutePath());
@ -435,7 +447,7 @@ public class JettyRunForkedMojo extends AbstractMojo
throw new MojoExecutionException("Prepare webapp configuration", e);
}
}
private void add (String string, StringBuilder builder)
{
if (string == null)
@ -448,62 +460,62 @@ public class JettyRunForkedMojo extends AbstractMojo
private List<File> getClassesDirs ()
{
List<File> classesDirs = new ArrayList<File>();
//if using the test classes, make sure they are first
//on the list
if (useTestScope && (testClassesDirectory != null))
classesDirs.add(testClassesDirectory);
if (classesDirectory != null)
classesDirs.add(classesDirectory);
return classesDirs;
}
private List<File> getOverlays()
throws MalformedURLException, IOException
{
List<File> overlays = new ArrayList<File>();
for ( Iterator<Artifact> iter = project.getArtifacts().iterator(); iter.hasNext(); )
{
Artifact artifact = (Artifact) iter.next();
Artifact artifact = (Artifact) iter.next();
if (artifact.getType().equals("war"))
overlays.add(artifact.getFile());
}
return overlays;
}
private List<File> getDependencyFiles ()
{
List<File> dependencyFiles = new ArrayList<File>();
for ( Iterator<Artifact> iter = project.getArtifacts().iterator(); iter.hasNext(); )
{
Artifact artifact = (Artifact) iter.next();
if (((!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) && (!Artifact.SCOPE_TEST.equals( artifact.getScope())))
if (((!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) && (!Artifact.SCOPE_TEST.equals( artifact.getScope())))
||
(useTestScope && Artifact.SCOPE_TEST.equals( artifact.getScope())))
{
dependencyFiles.add(artifact.getFile());
getLog().debug( "Adding artifact " + artifact.getFile().getName() + " for WEB-INF/lib " );
getLog().debug( "Adding artifact " + artifact.getFile().getName() + " for WEB-INF/lib " );
}
}
return dependencyFiles;
return dependencyFiles;
}
public boolean isPluginArtifact(Artifact artifact)
{
if (pluginArtifacts == null || pluginArtifacts.isEmpty())
return false;
boolean isPluginArtifact = false;
for (Iterator<Artifact> iter = pluginArtifacts.iterator(); iter.hasNext() && !isPluginArtifact; )
{
@ -512,18 +524,18 @@ public class JettyRunForkedMojo extends AbstractMojo
if (pluginArtifact.getGroupId().equals(artifact.getGroupId()) && pluginArtifact.getArtifactId().equals(artifact.getArtifactId()))
isPluginArtifact = true;
}
return isPluginArtifact;
}
private Set<Artifact> getExtraJars()
throws Exception
{
Set<Artifact> extraJars = new HashSet<Artifact>();
List l = pluginArtifacts;
Artifact pluginArtifact = null;
@ -531,7 +543,7 @@ public class JettyRunForkedMojo extends AbstractMojo
{
Iterator itor = l.iterator();
while (itor.hasNext() && pluginArtifact == null)
{
{
Artifact a = (Artifact)itor.next();
if (a.getArtifactId().equals(plugin.getArtifactId())) //get the jetty-maven-plugin jar
{
@ -543,18 +555,18 @@ public class JettyRunForkedMojo extends AbstractMojo
return extraJars;
}
/* ------------------------------------------------------------ */
public void startJettyRunner() throws MojoExecutionException
{
{
try
{
File props = prepareConfiguration();
List<String> cmd = new ArrayList<String>();
cmd.add(getJavaBin());
if (jvmArgs != null)
{
String[] args = jvmArgs.split(" ");
@ -564,7 +576,7 @@ public class JettyRunForkedMojo extends AbstractMojo
cmd.add(args[i].trim());
}
}
String classPath = getClassPath();
if (classPath != null && classPath.length() > 0)
{
@ -572,7 +584,7 @@ public class JettyRunForkedMojo extends AbstractMojo
cmd.add(classPath);
}
cmd.add(Starter.class.getCanonicalName());
if (stopPort > 0 && stopKey != null)
{
cmd.add("--stop-port");
@ -585,26 +597,26 @@ public class JettyRunForkedMojo extends AbstractMojo
cmd.add("--jetty-xml");
cmd.add(jettyXml);
}
if (contextXml != null)
{
cmd.add("--context-xml");
cmd.add(contextXml);
}
cmd.add("--props");
cmd.add(props.getAbsolutePath());
String token = createToken();
cmd.add("--token");
cmd.add(token);
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.directory(project.getBasedir());
if (PluginLog.getLog().isDebugEnabled())
PluginLog.getLog().debug(Arrays.toString(cmd.toArray()));
forkedProcess = builder.start();
PluginLog.getLog().info("Forked process starting");
@ -612,7 +624,7 @@ public class JettyRunForkedMojo extends AbstractMojo
{
startPump("STDOUT",forkedProcess.getInputStream());
startPump("STDERR",forkedProcess.getErrorStream());
int exitcode = forkedProcess.waitFor();
int exitcode = forkedProcess.waitFor();
PluginLog.getLog().info("Forked execution exit: "+exitcode);
}
else
@ -652,20 +664,20 @@ public class JettyRunForkedMojo extends AbstractMojo
{
if (forkedProcess != null && waitForChild)
forkedProcess.destroy();
throw new MojoExecutionException("Failed to start Jetty within time limit");
}
catch (Exception ex)
{
if (forkedProcess != null && waitForChild)
forkedProcess.destroy();
throw new MojoExecutionException("Failed to create Jetty process", ex);
}
}
public String getClassPath() throws Exception
{
StringBuilder classPath = new StringBuilder();
@ -682,16 +694,16 @@ public class JettyRunForkedMojo extends AbstractMojo
}
}
//Any jars that we need from the plugin environment (like the ones containing Starter class)
Set<Artifact> extraJars = getExtraJars();
for (Artifact a:extraJars)
{
{
classPath.append(File.pathSeparator);
classPath.append(a.getFile().getAbsolutePath());
}
//Any jars that we need from the project's dependencies because we're useProvided
List<String> providedJars = getProvidedJars();
if (providedJars != null && !providedJars.isEmpty())
@ -703,7 +715,7 @@ public class JettyRunForkedMojo extends AbstractMojo
if (getLog().isDebugEnabled()) getLog().debug("Adding provided jar: "+jar);
}
}
return classPath.toString();
}
@ -724,7 +736,7 @@ public class JettyRunForkedMojo extends AbstractMojo
return "java";
}
public static String fileSeparators(String path)
{
StringBuilder ret = new StringBuilder();
@ -759,13 +771,13 @@ public class JettyRunForkedMojo extends AbstractMojo
return ret.toString();
}
private String createToken ()
{
return Long.toString(random.nextLong()^System.currentTimeMillis(), 36).toUpperCase();
}
private void startPump(String mode, InputStream inputStream)
{
ConsoleStreamer pump = new ConsoleStreamer(mode,inputStream);
@ -774,7 +786,7 @@ public class JettyRunForkedMojo extends AbstractMojo
thread.start();
}
/**

View File

@ -63,7 +63,8 @@ import org.eclipse.jetty.webapp.WebAppContext;
*/
public class JettyRunMojo extends AbstractJettyMojo
{
public static final String DEFAULT_WEBAPP_SRC = "src"+File.separator+"main"+File.separator+"webapp";
public static final String DEFAULT_WEBAPP_SRC = "src"+File.separator+"main"+File.separator+"webapp";
/**
* If true, the &lt;testOutputDirectory&gt;
@ -136,12 +137,13 @@ public class JettyRunMojo extends AbstractJettyMojo
*/
private List<File> extraScanTargets;
/**
* Verify the configuration given in the pom.
*
* @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#checkPomConfiguration()
* @see org.mortbay.jetty.plugin.AbstractJettyMojo#checkPomConfiguration()
*/
public void checkPomConfiguration () throws MojoExecutionException
{
@ -149,7 +151,7 @@ public class JettyRunMojo extends AbstractJettyMojo
try
{
if ((getWebAppSourceDirectory() == null) || !getWebAppSourceDirectory().exists())
{
{
File defaultWebAppSrcDir = new File (project.getBasedir(), DEFAULT_WEBAPP_SRC);
getLog().info("webAppSourceDirectory"+(getWebAppSourceDirectory()==null?" not set.":" does not exist.")+" Defaulting to "+defaultWebAppSrcDir.getAbsolutePath());
webAppSourceDirectory = defaultWebAppSrcDir;
@ -444,6 +446,7 @@ public class JettyRunMojo extends AbstractJettyMojo
for ( Iterator<Artifact> iter = projectArtifacts.iterator(); iter.hasNext(); )
{
Artifact artifact = (Artifact) iter.next();
// Include runtime and compile time libraries, and possibly test libs too
if(artifact.getType().equals("war"))
{
@ -451,6 +454,7 @@ public class JettyRunMojo extends AbstractJettyMojo
{
Resource r=Resource.newResource("jar:"+Resource.toURL(artifact.getFile()).toString()+"!/");
overlays.add(r);
getLog().info("Adding overlay for war project artifact "+artifact.getId());
getExtraScanTargets().add(artifact.getFile());
}
catch(Exception e)

View File

@ -25,19 +25,21 @@ import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.eclipse.jetty.util.Scanner;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.xml.XmlConfiguration;
/**
*
*
* <p>
* This goal is used to assemble your webapp into an exploded war and automatically deploy it to Jetty.
* </p>
* <p>
* Once invoked, the plugin can be configured to run continuously, scanning for changes in the pom.xml and
* to WEB-INF/web.xml, WEB-INF/classes or WEB-INF/lib and hot redeploy when a change is detected.
* Once invoked, the plugin can be configured to run continuously, scanning for changes in the pom.xml and
* to WEB-INF/web.xml, WEB-INF/classes or WEB-INF/lib and hot redeploy when a change is detected.
* </p>
* <p>
* You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
* This can be used, for example, to deploy a static webapp that is not part of your maven build.
* This can be used, for example, to deploy a static webapp that is not part of your maven build.
* </p>
* <p>
* There is a <a href="run-exploded-mojo.html">reference guide</a> to the configuration parameters for this plugin, and more detailed information
@ -51,24 +53,24 @@ import org.eclipse.jetty.util.Scanner;
public class JettyRunWarExplodedMojo extends AbstractJettyMojo
{
/**
* The location of the war file.
*
*
* @parameter alias="webApp" expression="${project.build.directory}/${project.build.finalName}"
* @required
*/
private File war;
/**
*
* @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#checkPomConfiguration()
*
* @see org.mortbay.jetty.plugin.AbstractJettyMojo#checkPomConfiguration()
*/
public void checkPomConfiguration() throws MojoExecutionException
{
@ -76,7 +78,7 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo
}
/**
* @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#configureScanner()
* @see org.mortbay.jetty.plugin.AbstractJettyMojo#configureScanner()
*/
public void configureScanner() throws MojoExecutionException
{
@ -93,7 +95,7 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo
scanList.add(new File(webInfDir, "classes"));
scanList.add(new File(webInfDir, "lib"));
setScanList(scanList);
ArrayList<Scanner.BulkListener> listeners = new ArrayList<Scanner.BulkListener>();
listeners.add(new Scanner.BulkListener()
{
@ -113,10 +115,10 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo
setScannerListeners(listeners);
}
public void restartWebApp(boolean reconfigureScanner) throws Exception
public void restartWebApp(boolean reconfigureScanner) throws Exception
{
getLog().info("Restarting webapp");
getLog().debug("Stopping webapp ...");
@ -152,20 +154,20 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo
getLog().info("Restart completed.");
}
public void configureWebApplication () throws Exception
{
super.configureWebApplication();
super.configureWebApplication();
webApp.setWar(war.getCanonicalPath());
}
public void execute () throws MojoExecutionException, MojoFailureException
{
super.execute();
}
}

View File

@ -21,10 +21,14 @@ package org.eclipse.jetty.maven.plugin;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.eclipse.jetty.util.Scanner;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.xml.XmlConfiguration;
/**
* <p>
@ -32,18 +36,18 @@ import org.eclipse.jetty.util.Scanner;
* </p>
* <p>
* Once invoked, the plugin can be configured to run continuously, scanning for changes in the project and to the
* war file and automatically performing a
* hot redeploy when necessary.
* war file and automatically performing a
* hot redeploy when necessary.
* </p>
* <p>
* You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
* This can be used, for example, to deploy a static webapp that is not part of your maven build.
* This can be used, for example, to deploy a static webapp that is not part of your maven build.
* </p>
* <p>
* There is a <a href="run-war-mojo.html">reference guide</a> to the configuration parameters for this plugin, and more detailed information
* with examples in the <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin/">Configuration Guide</a>.
* </p>
*
*
* @goal run-war
* @requiresDependencyResolution compile+runtime
* @execute phase="package"
@ -61,13 +65,13 @@ public class JettyRunWarMojo extends AbstractJettyMojo
private File war;
/**
* @see org.apache.maven.plugin.Mojo#execute()
*/
public void execute() throws MojoExecutionException, MojoFailureException
{
super.execute();
super.execute();
}
@ -75,18 +79,18 @@ public class JettyRunWarMojo extends AbstractJettyMojo
public void configureWebApplication () throws Exception
{
super.configureWebApplication();
webApp.setWar(war.getCanonicalPath());
}
/**
* @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#checkPomConfiguration()
* @see org.mortbay.jetty.plugin.AbstractJettyMojo#checkPomConfiguration()
*/
public void checkPomConfiguration() throws MojoExecutionException
{
return;
return;
}
@ -100,7 +104,7 @@ public class JettyRunWarMojo extends AbstractJettyMojo
scanList.add(getProject().getFile());
scanList.add(war);
setScanList(scanList);
ArrayList listeners = new ArrayList();
listeners.add(new Scanner.BulkListener()
{
@ -117,11 +121,11 @@ public class JettyRunWarMojo extends AbstractJettyMojo
}
}
});
setScannerListeners(listeners);
setScannerListeners(listeners);
}
public void restartWebApp(boolean reconfigureScanner) throws Exception
public void restartWebApp(boolean reconfigureScanner) throws Exception
{
getLog().info("Restarting webapp ...");
getLog().debug("Stopping webapp ...");

View File

@ -23,7 +23,6 @@ import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
@ -33,20 +32,20 @@ import org.eclipse.jetty.webapp.WebAppContext;
/**
* JettyServer
*
*
* Maven jetty plugin version of a wrapper for the Server class.
*
*
*/
public class JettyServer extends org.eclipse.jetty.server.Server
{
public static int DEFAULT_PORT = 8080;
public static int DEFAULT_MAX_IDLE_TIME = 30000;
private RequestLog requestLog;
private ContextHandlerCollection contexts;
public JettyServer()
{
super();
@ -55,7 +54,7 @@ public class JettyServer extends org.eclipse.jetty.server.Server
Resource.setDefaultUseCaches(false);
}
public void setRequestLog (RequestLog requestLog)
{
this.requestLog = requestLog;
@ -69,16 +68,16 @@ public class JettyServer extends org.eclipse.jetty.server.Server
super.doStart();
}
/**
* @see org.eclipse.jetty.server.handler.HandlerCollection#addHandler(org.eclipse.jetty.server.Handler)
*/
public void addWebApplication(WebAppContext webapp) throws Exception
{
{
contexts.addHandler (webapp);
}
/**
* Set up the handler structure to receive a webapp.
* Also put in a DefaultHandler so we get a nice page
@ -86,43 +85,43 @@ public class JettyServer extends org.eclipse.jetty.server.Server
* context isn't at root.
* @throws Exception
*/
public void configureHandlers () throws Exception
public void configureHandlers () throws Exception
{
DefaultHandler defaultHandler = new DefaultHandler();
RequestLogHandler requestLogHandler = new RequestLogHandler();
if (this.requestLog != null)
requestLogHandler.setRequestLog(this.requestLog);
contexts = (ContextHandlerCollection)super.getChildHandlerByClass(ContextHandlerCollection.class);
if (contexts==null)
{
{
contexts = new ContextHandlerCollection();
HandlerCollection handlers = (HandlerCollection)super.getChildHandlerByClass(HandlerCollection.class);
if (handlers==null)
{
handlers = new HandlerCollection();
super.setHandler(handlers);
handlers = new HandlerCollection();
super.setHandler(handlers);
handlers.setHandlers(new Handler[]{contexts, defaultHandler, requestLogHandler});
}
else
{
handlers.addHandler(contexts);
}
}
}
}
public Connector createDefaultConnector(Server server, String portnum) throws Exception
public Connector createDefaultConnector(String portnum) throws Exception
{
ServerConnector connector = new ServerConnector(server);
ServerConnector connector = new ServerConnector(this);
int port = ((portnum==null||portnum.equals(""))?DEFAULT_PORT:Integer.parseInt(portnum.trim()));
connector.setPort(port);
connector.setIdleTimeout(DEFAULT_MAX_IDLE_TIME);
// connector.setMaxIdleTime(DEFAULT_MAX_IDLE_TIME);
return connector;
}
}

View File

@ -28,7 +28,6 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.plus.webapp.EnvConfiguration;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
@ -39,8 +38,8 @@ import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.FragmentConfiguration;
import org.eclipse.jetty.webapp.JettyWebXmlConfiguration;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.TagLibConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;
/**
@ -56,6 +55,7 @@ public class JettyWebAppContext extends WebAppContext
{
private static final Logger LOG = Log.getLogger(JettyWebAppContext.class);
private static final String DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN = ".*/javax.servlet-[^/]*\\.jar$|.*/servlet-api-[^/]*\\.jar$";
private static final String WEB_INF_CLASSES_PREFIX = "/WEB-INF/classes";
private static final String WEB_INF_LIB_PREFIX = "/WEB-INF/lib";
@ -73,6 +73,19 @@ public class JettyWebAppContext extends WebAppContext
* @deprecated The value of this parameter will be ignored by the plugin. Overlays will always be unpacked.
*/
private boolean unpackOverlays;
/**
* Set the "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern" with a pattern for matching jars on
* container classpath to scan. This is analogous to the WebAppContext.setAttribute() call.
*/
private String containerIncludeJarPattern = null;
/**
* Set the "org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern" with a pattern for matching jars on
* webapp's classpath to scan. This is analogous to the WebAppContext.setAttribute() call.
*/
private String webInfIncludeJarPattern = null;
/**
* @deprecated The value of this parameter will be ignored by the plugin. This option will be always disabled.
@ -91,14 +104,34 @@ public class JettyWebAppContext extends WebAppContext
new MetaInfConfiguration(),
new FragmentConfiguration(),
envConfig = new EnvConfiguration(),
new AnnotationConfiguration(),
new org.eclipse.jetty.plus.webapp.PlusConfiguration(),
new JettyWebXmlConfiguration(),
new TagLibConfiguration()
new MavenAnnotationConfiguration(),
new JettyWebXmlConfiguration()
});
// Turn off copyWebInf option as it is not applicable for plugin.
super.setCopyWebInf(false);
}
public void setContainerIncludeJarPattern(String pattern)
{
containerIncludeJarPattern = pattern;
}
public String getContainerIncludeJarPattern()
{
return containerIncludeJarPattern;
}
public String getWebInfIncludeJarPattern()
{
return webInfIncludeJarPattern;
}
public void setWebInfIncludeJarPattern(String pattern)
{
webInfIncludeJarPattern = pattern;
}
public boolean getUnpackOverlays()
{
@ -218,17 +251,21 @@ public class JettyWebAppContext extends WebAppContext
{
//Set up the pattern that tells us where the jars are that need scanning for
//stuff like taglibs so we can tell jasper about it (see TagLibConfiguration)
String tmp = (String)getAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern");
tmp = addPattern(tmp, ".*/.*jsp-api-[^/]*\\.jar$");
tmp = addPattern(tmp, ".*/.*jsp-[^/]*\\.jar$");
tmp = addPattern(tmp, ".*/.*taglibs[^/]*\\.jar$");
tmp = addPattern(tmp, ".*/.*jstl[^/]*\\.jar$");
tmp = addPattern(tmp, ".*/.*jsf-impl-[^/]*\\.jar$"); // add in 2 most popular jsf impls
tmp = addPattern(tmp, ".*/.*javax.faces-[^/]*\\.jar$");
tmp = addPattern(tmp, ".*/.*myfaces-impl-[^/]*\\.jar$");
setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", tmp);
//Allow user to set up pattern for names of jars from the container classpath
//that will be scanned - note that by default NO jars are scanned
String tmp = containerIncludeJarPattern;
if (tmp==null || "".equals(tmp))
tmp = (String)getAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN);
tmp = addPattern(tmp, DEFAULT_CONTAINER_INCLUDE_JAR_PATTERN);
setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, tmp);
//Allow user to set up pattern of jar names from WEB-INF that will be scanned.
//Note that by default ALL jars considered to be in WEB-INF will be scanned - setting
//a pattern restricts scanning
if (webInfIncludeJarPattern != null)
setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, webInfIncludeJarPattern);
//Set up the classes dirs that comprises the equivalent of WEB-INF/classes
if (testClasses != null)
@ -241,7 +278,6 @@ public class JettyWebAppContext extends WebAppContext
classpathFiles.addAll(webInfClasses);
classpathFiles.addAll(webInfJars);
// Initialize map containing all jars in /WEB-INF/lib
webInfJarMap.clear();
for (File file : webInfJars)
@ -255,13 +291,28 @@ public class JettyWebAppContext extends WebAppContext
if (this.jettyEnvXml != null)
envConfig.setJettyEnvXml(Resource.toURL(new File(this.jettyEnvXml)));
//setShutdown(false);
// CHECK setShutdown(false);
super.doStart();
}
public void doStop () throws Exception
{
//setShutdown(true);
if (classpathFiles != null)
classpathFiles.clear();
classpathFiles = null;
classes = null;
testClasses = null;
if (webInfJarMap != null)
webInfJarMap.clear();
webInfClasses.clear();
webInfJars.clear();
// CHECK setShutdown(true);
//just wait a little while to ensure no requests are still being processed
Thread.currentThread().sleep(500L);
super.doStop();

View File

@ -0,0 +1,109 @@
//
// ========================================================================
// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.maven.plugin;
import java.io.File;
import org.eclipse.jetty.annotations.AbstractDiscoverableAnnotationHandler;
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.annotations.AnnotationParser;
import org.eclipse.jetty.annotations.AnnotationParser.DiscoverableAnnotationHandler;
import org.eclipse.jetty.annotations.ClassNameResolver;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.MetaData;
import org.eclipse.jetty.webapp.WebAppContext;
public class MavenAnnotationConfiguration extends AnnotationConfiguration
{
private static final Logger LOG = Log.getLogger(MavenAnnotationConfiguration.class);
/* ------------------------------------------------------------ */
@Override
public void parseWebInfClasses(final WebAppContext context, final AnnotationParser parser) throws Exception
{
JettyWebAppContext jwac = (JettyWebAppContext)context;
if (jwac.getClassPathFiles() == null || jwac.getClassPathFiles().size() == 0)
super.parseWebInfClasses (context, parser);
else
{
LOG.debug("Scanning classes ");
//Look for directories on the classpath and process each one of those
MetaData metaData = context.getMetaData();
if (metaData == null)
throw new IllegalStateException ("No metadata");
parser.clearHandlers();
for (DiscoverableAnnotationHandler h:_discoverableAnnotationHandlers)
{
if (h instanceof AbstractDiscoverableAnnotationHandler)
((AbstractDiscoverableAnnotationHandler)h).setResource(null); //
}
parser.registerHandlers(_discoverableAnnotationHandlers);
parser.registerHandler(_classInheritanceHandler);
parser.registerHandlers(_containerInitializerAnnotationHandlers);
for (File f:jwac.getClassPathFiles())
{
//scan the equivalent of the WEB-INF/classes directory that has been synthesised by the plugin
if (f.isDirectory() && f.exists())
{
doParse(context, parser, Resource.newResource(f.toURL()));
}
}
//if an actual WEB-INF/classes directory also exists (eg because of overlayed wars) then scan that
//too
if (context.getWebInf() != null && context.getWebInf().exists())
{
Resource classesDir = context.getWebInf().addPath("classes/");
if (classesDir.exists())
{
doParse(context, parser, classesDir);
}
}
}
}
public void doParse (final WebAppContext context, final AnnotationParser parser, Resource resource)
throws Exception
{
parser.parse(resource, new ClassNameResolver()
{
public boolean isExcluded (String name)
{
if (context.isSystemClass(name)) return true;
if (context.isServerClass(name)) return false;
return false;
}
public boolean shouldOverride (String name)
{
//looking at webapp classpath, found already-parsed class of same name - did it come from system or duplicate in webapp?
if (context.isParentLoaderPriority())
return false;
return true;
}
});
}
}

View File

@ -26,6 +26,7 @@ import java.util.Iterator;
import java.util.List;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.LazyList;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
@ -40,8 +41,8 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
protected Resource _originalResourceBase;
protected Resource[] _unpackedOverlays;
public void configure(WebAppContext context) throws Exception
{
JettyWebAppContext jwac = (JettyWebAppContext)context;
@ -54,11 +55,11 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
while (itor.hasNext())
((WebAppClassLoader)context.getClassLoader()).addClassPath(((File)itor.next()).getCanonicalPath());
if (LOG.isDebugEnabled())
LOG.debug("Classpath = "+((URLClassLoader)context.getClassLoader()).getURLs());
//if (LOG.isDebugEnabled())
//LOG.debug("Classpath = "+LazyList.array2List(((URLClassLoader)context.getClassLoader()).getURLs()));
}
super.configure(context);
// knock out environmental maven and plexus classes from webAppContext
String[] existingServerClasses = context.getServerClasses();
String[] newServerClasses = new String[2+(existingServerClasses==null?0:existingServerClasses.length)];
@ -71,7 +72,7 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
for (int i=0;i<newServerClasses.length;i++)
LOG.debug(newServerClasses[i]);
}
context.setServerClasses( newServerClasses );
context.setServerClasses( newServerClasses );
}
@ -79,6 +80,53 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
{
super.preConfigure(context);
}
public void postConfigure(WebAppContext context) throws Exception
{
super.postConfigure(context);
}
public void deconfigure(WebAppContext context) throws Exception
{
JettyWebAppContext jwac = (JettyWebAppContext)context;
//remove the unpacked wars
if (_unpackedOverlays != null && _unpackedOverlays.length>0)
{
try
{
for (int i=0; i<_unpackedOverlays.length; i++)
{
IO.delete(_unpackedOverlays[i].getFile());
}
}
catch (IOException e)
{
LOG.ignore(e);
}
}
super.deconfigure(context);
//restore whatever the base resource was before we might have included overlaid wars
context.setBaseResource(_originalResourceBase);
}
/**
* @see org.eclipse.jetty.webapp.WebInfConfiguration#unpack(org.eclipse.jetty.webapp.WebAppContext)
*/
@Override
public void unpack(WebAppContext context) throws IOException
{
//Unpack and find base resource as normal
super.unpack(context);
//Add in any overlays as a resource collection for the base
_originalResourceBase = context.getBaseResource();
JettyWebAppContext jwac = (JettyWebAppContext)context;
@ -102,7 +150,7 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
origSize = 1;
}
}
int overlaySize = jwac.getOverlays().size();
Resource[] newResources = new Resource[origSize + overlaySize];
@ -112,7 +160,6 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
if (jwac.getBaseAppFirst())
{
System.arraycopy(origResources,0,newResources,0,origSize);
offset = origSize;
}
else
@ -120,53 +167,23 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
System.arraycopy(origResources,0,newResources,overlaySize,origSize);
}
}
// Overlays are always unpacked
_unpackedOverlays = new Resource[overlaySize];
List<Resource> overlays = jwac.getOverlays();
for (int idx=0; idx<overlaySize; idx++)
{
{
LOG.info("Unpacking overlay: " + overlays.get(idx));
_unpackedOverlays[idx] = unpackOverlay(context, overlays.get(idx));
newResources[idx+offset] = _unpackedOverlays[idx];
LOG.info("Adding overlay: " + _unpackedOverlays[idx]);
}
jwac.setBaseResource(new ResourceCollection(newResources));
}
}
public void postConfigure(WebAppContext context) throws Exception
{
super.postConfigure(context);
}
public void deconfigure(WebAppContext context) throws Exception
{
JettyWebAppContext jwac = (JettyWebAppContext)context;
//remove the unpacked wars
if (_unpackedOverlays != null && _unpackedOverlays.length>0)
{
try
{
for (int i=0; i<_unpackedOverlays.length; i++)
{
IO.delete(_unpackedOverlays[i].getFile());
}
}
catch (IOException e)
{
LOG.ignore(e);
}
}
super.deconfigure(context);
//restore whatever the base resource was before we might have included overlaid wars
context.setBaseResource(_originalResourceBase);
}
/**
* Get the jars to examine from the files from which we have
@ -175,6 +192,7 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
* @param context
* @return the list of jars found
*/
@Override
protected List<Resource> findJars (WebAppContext context)
throws Exception
{
@ -203,14 +221,16 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
list.addAll(superList);
return list;
}
protected Resource unpackOverlay (WebAppContext context, Resource overlay)
throws IOException
{
//resolve if not already resolved
resolveTempDirectory(context);
//Get the name of the overlayed war and unpack it to a dir of the
//same name in the temporary directory
String name = overlay.getName();
@ -225,6 +245,4 @@ public class MavenWebInfConfiguration extends WebInfConfiguration
Resource unpackedOverlay = Resource.newResource(dir.getCanonicalPath());
return unpackedOverlay;
}
}

View File

@ -16,12 +16,12 @@
// ========================================================================
//
package org.eclipse.jetty.maven.plugin;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
@ -41,7 +41,7 @@ import org.eclipse.jetty.server.Server;
* by stopping the Server instances. The choice of
* behaviour is controlled by either passing true
* (exit jvm) or false (stop Servers) in the constructor.
*
*
*/
public class Monitor extends Thread
{
@ -51,7 +51,7 @@ public class Monitor extends Thread
ServerSocket _serverSocket;
boolean _kill;
public Monitor(int port, String key, Server[] servers, boolean kill)
public Monitor(int port, String key, Server[] servers, boolean kill)
throws UnknownHostException, IOException
{
if (port <= 0)
@ -64,7 +64,7 @@ public class Monitor extends Thread
_kill = kill;
setDaemon(true);
setName("StopJettyPluginMonitor");
InetSocketAddress address = new InetSocketAddress("127.0.0.1", port);
InetSocketAddress address = new InetSocketAddress("127.0.0.1", port);
_serverSocket=new ServerSocket();
_serverSocket.setReuseAddress(true);
try
@ -77,7 +77,7 @@ public class Monitor extends Thread
throw x;
}
}
public void run()
{
while (_serverSocket != null)
@ -88,7 +88,7 @@ public class Monitor extends Thread
socket = _serverSocket.accept();
socket.setSoLinger(false, 0);
LineNumberReader lin = new LineNumberReader(new InputStreamReader(socket.getInputStream()));
String key = lin.readLine();
if (!_key.equals(key)) continue;
String cmd = lin.readLine();
@ -97,13 +97,13 @@ public class Monitor extends Thread
try{socket.close();}catch (Exception e){e.printStackTrace();}
try{socket.close();}catch (Exception e){e.printStackTrace();}
try{_serverSocket.close();}catch (Exception e){e.printStackTrace();}
_serverSocket = null;
if (_kill)
{
System.out.println("Killing Jetty");
System.exit(0);
System.exit(0);
}
else
{
@ -111,7 +111,7 @@ public class Monitor extends Thread
{
try
{
System.out.println("Stopping server "+i);
System.out.println("Stopping server "+i);
_servers[i].stop();
}
catch (Exception e)

View File

@ -23,19 +23,23 @@ import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.xml.XmlConfiguration;
public class Starter
{
{
public static final String PORT_SYSPROPERTY = "jetty.port";
private static final Logger LOG = Log.getLogger(Starter.class);
@ -45,21 +49,21 @@ public class Starter
private JettyServer server;
private JettyWebAppContext webApp;
private Monitor monitor;
private int stopPort=0;
private String stopKey=null;
private Properties props;
private String token;
public void configureJetty () throws Exception
{
LOG.debug("Starting Jetty Server ...");
this.server = new JettyServer();
//apply any configs from jetty.xml files first
//apply any configs from jetty.xml files first
applyJettyXml ();
// if the user hasn't configured a connector in the jetty.xml
@ -68,7 +72,7 @@ public class Starter
if (connectors == null|| connectors.length == 0)
{
//if a SystemProperty -Djetty.port=<portnum> has been supplied, use that as the default port
connectors = new Connector[] { this.server.createDefaultConnector(server, System.getProperty(PORT_SYSPROPERTY, null)) };
connectors = new Connector[] { this.server.createDefaultConnector(System.getProperty(PORT_SYSPROPERTY, null)) };
this.server.setConnectors(connectors);
}
@ -84,15 +88,15 @@ public class Starter
this.server.configureHandlers();
webApp = new JettyWebAppContext();
//configure webapp from properties file describing unassembled webapp
configureWebApp();
//set up the webapp from the context xml file provided
//NOTE: just like jetty:run mojo this means that the context file can
//potentially override settings made in the pom. Ideally, we'd like
//the pom to override the context xml file, but as the other mojos all
//configure a WebAppContext in the pom (the <webApp> element), it is
//configure a WebAppContext in the pom (the <webApp> element), it is
//already configured by the time the context xml file is applied.
if (contextXml != null)
{
@ -109,30 +113,30 @@ public class Starter
monitor = new Monitor(stopPort, stopKey, new Server[]{server}, true);
}
}
public void configureWebApp ()
throws Exception
{
if (props == null)
return;
//apply a properties file that defines the things that we configure in the jetty:run plugin:
// - the context path
String str = (String)props.get("context.path");
if (str != null)
webApp.setContextPath(str);
// - web.xml
str = (String)props.get("web.xml");
if (str != null)
webApp.setDescriptor(str);
// - the tmp directory
str = (String)props.getProperty("tmp.dir");
if (str != null)
webApp.setTempDirectory(new File(str.trim()));
// - the base directory
str = (String)props.getProperty("base.dir");
if (str != null && !"".equals(str.trim()))
@ -145,7 +149,7 @@ public class Starter
ResourceCollection resources = new ResourceCollection(str);
webApp.setBaseResource(resources);
}
// - overlays
str = (String)props.getProperty("overlay.files");
if (str != null && !"".equals(str.trim()))
@ -163,8 +167,8 @@ public class Starter
{
webApp.setClasses(new File(str));
}
str = (String)props.getProperty("testClasses.dir");
str = (String)props.getProperty("testClasses.dir");
if (str != null && !"".equals(str.trim()))
{
webApp.setTestClasses(new File(str));
@ -181,7 +185,7 @@ public class Starter
jars.add(new File(names[j].trim()));
webApp.setWebInfLib(jars);
}
}
public void getConfiguration (String[] args)
@ -205,7 +209,7 @@ public class Starter
for (int j=0; names!= null && j < names.length; j++)
{
jettyXmls.add(new File(names[j].trim()));
}
}
}
//--context-xml
@ -221,7 +225,7 @@ public class Starter
props = new Properties();
props.load(new FileInputStream(f));
}
//--token
if ("--token".equals(args[i]))
{
@ -237,16 +241,16 @@ public class Starter
monitor.start();
LOG.info("Started Jetty Server");
server.start();
server.start();
}
public void join () throws Exception
{
server.join();
}
public void communicateStartupResult (Exception e)
{
if (token != null)
@ -257,16 +261,16 @@ public class Starter
System.out.println(token+"\t"+e.getMessage());
}
}
public void applyJettyXml() throws Exception
{
if (jettyXmls == null)
return;
for ( File xmlFile : jettyXmls )
{
LOG.info( "Configuring Jetty from xml configuration file = " + xmlFile.getCanonicalPath() );
LOG.info( "Configuring Jetty from xml configuration file = " + xmlFile.getCanonicalPath() );
XmlConfiguration xmlConfiguration = new XmlConfiguration(Resource.toURL(xmlFile));
xmlConfiguration.configure(this.server);
}
@ -286,8 +290,8 @@ public class Starter
System.arraycopy(existing, 0, children, 1, existing.length);
handlers.setHandlers(children);
}
public static final void main(String[] args)
{
if (args == null)