flume jetty 跨域问题
13481 httpSource的端口进程号 = flume 启动后的进程号
[root@c log]# netstat -atp Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 localhost:32000 0.0.0.0:* LISTEN 10343/java tcp 0 0 localhost:cslistener 0.0.0.0:* LISTEN 23781/php-fpm: mast tcp 0 0 0.0.0.0:50000 0.0.0.0:* LISTEN 13481/java tcp 0 0 0.0.0.0:webcache 0.0.0.0:* LISTEN 12249/nginx: master tcp 0 0 0.0.0.0:http 0.0.0.0:* LISTEN 12249/nginx: master [root@c log]# ^C [root@c log]# ps -aux | grep java root 10340 0.0 0.0 122088 1284 ? Sl Sep18 39:07 /usr/local/cloudmonitor/wrapper/bin/./wrapper /usr/local/cloudmonitor/wrapper/bin/../conf/wrapper.conf wrapper.syslog.ident=cloudmonitor wrapper.pidfile=/usr/local/cloudmonitor/wrapper/bin/./cloudmonitor.pid wrapper.daemonize=TRUE wrapper.name=cloudmonitor wrapper.displayname=cloudmonitor wrapper.statusfile=/usr/local/cloudmonitor/wrapper/bin/./cloudmonitor.status wrapper java.statusfile=/usr/local/cloudmonitor/wrapper/bin/./cloudmonitor.java.status wrapper.lockfile=/var/lock/subsys/cloudmonitor wrapper.script.version=3.5.27 root 10343 0.8 0.2 2517220 72168 ? Sl Sep18 509:29 /usr/local/cloudmonitor/jre/bin/java -Djava.compiler=none -XX:-UseGCOverheadLimit -XX:NewRatio=1 -XX:SurvivorRatio=8 -XX:+UseSerialGC -Djava.io.tmpdir=../../tmp -Xms16m -Xmx32m -Djava.library.path=../lib:../../lib -classpath ../lib/wrappertest.jar:../lib/wrapper.jar:../../config:../../lib/agent-commons-1.3.4.jar:../../lib/agent-core-1.3.4.jar:../../lib/agent-model-1.3.4.jar:../../lib/aopalliance-1.0.jar:../../lib/commons-logging-1.2.jar:../../lib/commons-net-3.5.jar:../../lib/gson-2.4.jar:../../lib/jvm-plugin-1.3.4.jar:../../lib/log4j-1.2.16.jar:../../lib/metrics-core-3.0.2.jar:../../lib/sigar-1.6.5.132.jar:../../lib/slf4j-api-1.7.5.jar:../../lib/spring-aop-4.2.4.RELEASE.jar:../../lib/spring-beans-4.2.4.RELEASE.jar:../../lib/spring-context-4.2.4.RELEASE.jar:../../lib/spring-core-4.2.4.RELEASE.jar:../../lib/spring-expression-4.2.4.RELEASE.jar:../../lib/system-plugin-1.3.4.jar:../../lib/updater-1.3.4-jar-with-dependencies.jar -Dwrapper.key=JGXBiQ7jznMcXp-o -Dwrapper.port=32000 -Dwrapper.jvm.port.min=31000 -Dwrapper.jvm.port.max=31999 -Dwrapper.disable_console_input=TRUE -Dwrapper.pid=10340 -Dwrapper.version=3.5.27 -Dwrapper.native_library=wrapper -Dwrapper.arch=x86 -Dwrapper.service=TRUE -Dwrapper.cpu.timeout=10 -Dwrapper.jvmid=1 com.aliyun.tianji.cloudmonitor.Application root 13481 0.7 0.3 14763592 126528 pts/0 Sl+ 19:28 0:02 /usr/java/jdk1.8.0_101/bin/java -Xmx20m -Dflume.root.logger=INFO,console -Xms10240m -Xmx10240m -cp /data/UnifiedLog/flume/conf:/data/UnifiedLog/flume/lib/*:/lib/* -Djava.library.path= org.apache.flume.node.Application -f /data/UnifiedLog/flume/conf/httpSourceApp.conf -n a1 root 13851 0.0 0.0 112704 964 pts/3 S+ 19:33 0:00 grep --color=auto java elsearch 26364 66.2 58.9 178108240 19329536 ? Sl Sep18 42347:19 /usr/java/jdk1.8.0_101/bin/java -Xms10g -Xmx10g -Djava.awt.headless=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -XX:+DisableExplicitGC -Dfile.encoding=UTF-8 -Djna.nosys=true -Xms20g -Xmx20g -Des.path.home=/usr/local/elasticsearch-2.4.1 -cp /usr/local/elasticsearch-2.4.1/lib/elasticsearch-2.4.1.jar:/usr/local/elasticsearch-2.4.1/lib/* org.elasticsearch.bootstrap.Elasticsearch start [root@c log]#
追溯源码,找jetty配置
$FlumeHome/bin/flume-ng agent -c $FlumeHome/conf/ -f $FlumeHome/conf/httpSourceApp.conf -n a1 -Dflume.root.logger=INFO,console -Xms2048m -Xmx2048m ;
查启动脚本
apache-flume-1.8.0-bininflume-ng
#!/bin/bash # # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ################################ # constants ################################ FLUME_AGENT_CLASS="org.apache.flume.node.Application" FLUME_AVRO_CLIENT_CLASS="org.apache.flume.client.avro.AvroCLIClient" FLUME_VERSION_CLASS="org.apache.flume.tools.VersionInfo" FLUME_TOOLS_CLASS="org.apache.flume.tools.FlumeToolsMain" CLEAN_FLAG=1 ################################ # functions ################################ info() { if [ ${CLEAN_FLAG} -ne 0 ]; then local msg=$1 echo "Info: $msg" >&2 fi } warn() { if [ ${CLEAN_FLAG} -ne 0 ]; then local msg=$1 echo "Warning: $msg" >&2 fi } error() { local msg=$1 local exit_code=$2 echo "Error: $msg" >&2 if [ -n "$exit_code" ] ; then exit $exit_code fi } # If avail, add Hadoop paths to the FLUME_CLASSPATH and to the # FLUME_JAVA_LIBRARY_PATH env vars. # Requires Flume jars to already be on FLUME_CLASSPATH. add_hadoop_paths() { local HADOOP_IN_PATH=$(PATH="${HADOOP_HOME:-${HADOOP_PREFIX}}/bin:$PATH" which hadoop 2>/dev/null) if [ -f "${HADOOP_IN_PATH}" ]; then info "Including Hadoop libraries found via ($HADOOP_IN_PATH) for HDFS access" # determine hadoop java.library.path and use that for flume local HADOOP_CLASSPATH="" local HADOOP_JAVA_LIBRARY_PATH=$(HADOOP_CLASSPATH="$FLUME_CLASSPATH" ${HADOOP_IN_PATH} org.apache.flume.tools.GetJavaProperty java.library.path) # look for the line that has the desired property value # (considering extraneous output from some GC options that write to stdout) # IFS = InternalFieldSeparator (set to recognize only newline char as delimiter) IFS=$' ' for line in $HADOOP_JAVA_LIBRARY_PATH; do if [[ $line =~ ^java.library.path=(.*)$ ]]; then HADOOP_JAVA_LIBRARY_PATH=${BASH_REMATCH[1]} break fi done unset IFS if [ -n "${HADOOP_JAVA_LIBRARY_PATH}" ]; then FLUME_JAVA_LIBRARY_PATH="$FLUME_JAVA_LIBRARY_PATH:$HADOOP_JAVA_LIBRARY_PATH" fi # determine hadoop classpath HADOOP_CLASSPATH=$($HADOOP_IN_PATH classpath) FLUME_CLASSPATH="$FLUME_CLASSPATH:$HADOOP_CLASSPATH" fi } add_HBASE_paths() { local HBASE_IN_PATH=$(PATH="${HBASE_HOME}/bin:$PATH" which hbase 2>/dev/null) if [ -f "${HBASE_IN_PATH}" ]; then info "Including HBASE libraries found via ($HBASE_IN_PATH) for HBASE access" # determine HBASE java.library.path and use that for flume local HBASE_CLASSPATH="" local HBASE_JAVA_LIBRARY_PATH=$(HBASE_CLASSPATH="$FLUME_CLASSPATH" ${HBASE_IN_PATH} org.apache.flume.tools.GetJavaProperty java.library.path) # look for the line that has the desired property value # (considering extraneous output from some GC options that write to stdout) # IFS = InternalFieldSeparator (set to recognize only newline char as delimiter) IFS=$' ' for line in $HBASE_JAVA_LIBRARY_PATH; do if [[ $line =~ ^java.library.path=(.*)$ ]]; then HBASE_JAVA_LIBRARY_PATH=${BASH_REMATCH[1]} break fi done unset IFS if [ -n "${HBASE_JAVA_LIBRARY_PATH}" ]; then FLUME_JAVA_LIBRARY_PATH="$FLUME_JAVA_LIBRARY_PATH:$HBASE_JAVA_LIBRARY_PATH" fi # determine HBASE classpath HBASE_CLASSPATH=$($HBASE_IN_PATH classpath) FLUME_CLASSPATH="$FLUME_CLASSPATH:$HBASE_CLASSPATH" FLUME_CLASSPATH="$FLUME_CLASSPATH:$HBASE_HOME/conf" fi } add_hive_paths(){ if [ -d "${HIVE_HOME}/lib" ]; then info "Including Hive libraries found via ($HIVE_HOME) for Hive access" FLUME_CLASSPATH="$FLUME_CLASSPATH:$HIVE_HOME/lib/*" fi if [ -d "${HCAT_HOME}/share/hcatalog" ]; then info "Including HCatalog libraries found via ($HCAT_HOME) for Hive access" FLUME_CLASSPATH="$FLUME_CLASSPATH:${HCAT_HOME}/share/hcatalog/*" fi } set_LD_LIBRARY_PATH(){ #Append the FLUME_JAVA_LIBRARY_PATH to whatever the user may have specified in #flume-env.sh if [ -n "${FLUME_JAVA_LIBRARY_PATH}" ]; then export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${FLUME_JAVA_LIBRARY_PATH}" fi } display_help() { cat <<EOF Usage: $0 <command> [options]... commands: help display this help text agent run a Flume agent avro-client run an avro Flume client version show Flume version info global options: --conf,-c <conf> use configs in <conf> directory --classpath,-C <cp> append to the classpath --dryrun,-d do not actually start Flume, just print the command --plugins-path <dirs> colon-separated list of plugins.d directories. See the plugins.d section in the user guide for more details. Default: $FLUME_HOME/plugins.d -Dproperty=value sets a Java system property value -Xproperty=value sets a Java -X option agent options: --name,-n <name> the name of this agent (required) --conf-file,-f <file> specify a config file (required if -z missing) --zkConnString,-z <str> specify the ZooKeeper connection to use (required if -f missing) --zkBasePath,-p <path> specify the base path in ZooKeeper for agent configs --no-reload-conf do not reload config file if changed --help,-h display help text avro-client options: --rpcProps,-P <file> RPC client properties file with server connection params --host,-H <host> hostname to which events will be sent --port,-p <port> port of the avro source --dirname <dir> directory to stream to avro source --filename,-F <file> text file to stream to avro source (default: std input) --headerFile,-R <file> File containing event headers as key/value pairs on each new line --help,-h display help text Either --rpcProps or both --host and --port must be specified. Note that if <conf> directory is specified, then it is always included first in the classpath. EOF } run_flume() { local FLUME_APPLICATION_CLASS if [ "$#" -gt 0 ]; then FLUME_APPLICATION_CLASS=$1 shift else error "Must specify flume application class" 1 fi if [ ${CLEAN_FLAG} -ne 0 ]; then set -x fi $EXEC $JAVA_HOME/bin/java $JAVA_OPTS $FLUME_JAVA_OPTS "${arr_java_props[@]}" -cp "$FLUME_CLASSPATH" -Djava.library.path=$FLUME_JAVA_LIBRARY_PATH "$FLUME_APPLICATION_CLASS" $* } ################################ # main ################################ # set default params FLUME_CLASSPATH="" FLUME_JAVA_LIBRARY_PATH="" JAVA_OPTS="-Xmx20m" LD_LIBRARY_PATH="" opt_conf="" opt_classpath="" opt_plugins_dirs="" arr_java_props=() arr_java_props_ct=0 opt_dryrun="" mode=$1 shift case "$mode" in help) display_help exit 0 ;; agent) opt_agent=1 ;; node) opt_agent=1 warn "The "node" command is deprecated. Please use "agent" instead." ;; avro-client) opt_avro_client=1 ;; tool) opt_tool=1 ;; version) opt_version=1 CLEAN_FLAG=0 ;; *) error "Unknown or unspecified command '$mode'" echo display_help exit 1 ;; esac args="" while [ -n "$*" ] ; do arg=$1 shift case "$arg" in --conf|-c) [ -n "$1" ] || error "Option --conf requires an argument" 1 opt_conf=$1 shift ;; --classpath|-C) [ -n "$1" ] || error "Option --classpath requires an argument" 1 opt_classpath=$1 shift ;; --dryrun|-d) opt_dryrun="1" ;; --plugins-path) opt_plugins_dirs=$1 shift ;; -agentlib*) arr_java_props[arr_java_props_ct]=$arg ((++arr_java_props_ct)) ;; -agentpath*) arr_java_props[arr_java_props_ct]=$arg ((++arr_java_props_ct)) ;; -javaagent*) arr_java_props[arr_java_props_ct]=$arg ((++arr_java_props_ct)) ;; -D*) arr_java_props[arr_java_props_ct]=$arg ((++arr_java_props_ct)) ;; -X*) arr_java_props[arr_java_props_ct]=$arg ((++arr_java_props_ct)) ;; *) args="$args $arg" ;; esac done # make opt_conf absolute if [[ -n "$opt_conf" && -d "$opt_conf" ]]; then opt_conf=$(cd $opt_conf; pwd) fi # allow users to override the default env vars via conf/flume-env.sh if [ -z "$opt_conf" ]; then warn "No configuration directory set! Use --conf <dir> to override." elif [ -f "$opt_conf/flume-env.sh" ]; then info "Sourcing environment configuration script $opt_conf/flume-env.sh" source "$opt_conf/flume-env.sh" fi # prepend command-line classpath to env script classpath if [ -n "${opt_classpath}" ]; then if [ -n "${FLUME_CLASSPATH}" ]; then FLUME_CLASSPATH="${opt_classpath}:${FLUME_CLASSPATH}" else FLUME_CLASSPATH="${opt_classpath}" fi fi if [ -z "${FLUME_HOME}" ]; then FLUME_HOME=$(cd $(dirname $0)/..; pwd) fi # prepend $FLUME_HOME/lib jars to the specified classpath (if any) if [ -n "${FLUME_CLASSPATH}" ] ; then FLUME_CLASSPATH="${FLUME_HOME}/lib/*:$FLUME_CLASSPATH" else FLUME_CLASSPATH="${FLUME_HOME}/lib/*" fi # load plugins.d directories PLUGINS_DIRS="" if [ -n "${opt_plugins_dirs}" ]; then PLUGINS_DIRS=$(sed -e 's/:/ /g' <<<${opt_plugins_dirs}) else PLUGINS_DIRS="${FLUME_HOME}/plugins.d" fi unset plugin_lib plugin_libext plugin_native for PLUGINS_DIR in $PLUGINS_DIRS; do if [[ -d ${PLUGINS_DIR} ]]; then for plugin in ${PLUGINS_DIR}/*; do if [[ -d "$plugin/lib" ]]; then plugin_lib="${plugin_lib}${plugin_lib+:}${plugin}/lib/*" fi if [[ -d "$plugin/libext" ]]; then plugin_libext="${plugin_libext}${plugin_libext+:}${plugin}/libext/*" fi if [[ -d "$plugin/native" ]]; then plugin_native="${plugin_native}${plugin_native+:}${plugin}/native" fi done fi done if [[ -n "${plugin_lib}" ]] then FLUME_CLASSPATH="${FLUME_CLASSPATH}:${plugin_lib}" fi if [[ -n "${plugin_libext}" ]] then FLUME_CLASSPATH="${FLUME_CLASSPATH}:${plugin_libext}" fi if [[ -n "${plugin_native}" ]] then if [[ -n "${FLUME_JAVA_LIBRARY_PATH}" ]] then FLUME_JAVA_LIBRARY_PATH="${FLUME_JAVA_LIBRARY_PATH}:${plugin_native}" else FLUME_JAVA_LIBRARY_PATH="${plugin_native}" fi fi # find java if [ -z "${JAVA_HOME}" ] ; then warn "JAVA_HOME is not set!" # Try to use Bigtop to autodetect JAVA_HOME if it's available if [ -e /usr/libexec/bigtop-detect-javahome ] ; then . /usr/libexec/bigtop-detect-javahome elif [ -e /usr/lib/bigtop-utils/bigtop-detect-javahome ] ; then . /usr/lib/bigtop-utils/bigtop-detect-javahome fi # Using java from path if bigtop is not installed or couldn't find it if [ -z "${JAVA_HOME}" ] ; then JAVA_DEFAULT=$(type -p java) [ -n "$JAVA_DEFAULT" ] || error "Unable to find java executable. Is it in your PATH?" 1 JAVA_HOME=$(cd $(dirname $JAVA_DEFAULT)/..; pwd) fi fi # look for hadoop libs add_hadoop_paths add_HBASE_paths add_hive_paths # prepend conf dir to classpath if [ -n "$opt_conf" ]; then FLUME_CLASSPATH="$opt_conf:$FLUME_CLASSPATH" fi set_LD_LIBRARY_PATH # allow dryrun EXEC="exec" if [ -n "${opt_dryrun}" ]; then warn "Dryrun mode enabled (will not actually initiate startup)" EXEC="echo" fi # finally, invoke the appropriate command if [ -n "$opt_agent" ] ; then run_flume $FLUME_AGENT_CLASS $args elif [ -n "$opt_avro_client" ] ; then run_flume $FLUME_AVRO_CLIENT_CLASS $args elif [ -n "${opt_version}" ] ; then run_flume $FLUME_VERSION_CLASS $args elif [ -n "${opt_tool}" ] ; then run_flume $FLUME_TOOLS_CLASS $args else error "This message should never appear" 1 fi exit 0
分析
run_flume() {
local FLUME_APPLICATION_CLASS
if [ "$#" -gt 0 ]; then
FLUME_APPLICATION_CLASS=$1
shift
else
error "Must specify flume application class" 1
fi
if [ ${CLEAN_FLAG} -ne 0 ]; then
set -x
fi
$EXEC $JAVA_HOME/bin/java $JAVA_OPTS $FLUME_JAVA_OPTS "${arr_java_props[@]}" -cp "$FLUME_CLASSPATH"
-Djava.library.path=$FLUME_JAVA_LIBRARY_PATH "$FLUME_APPLICATION_CLASS" $*
}
查启动时导入的jar
[root@d productArtifactId]# tree $FlumeHome/lib -a
/data/UnifiedLog/flume/lib
├── apache-log4j-extras-1.1.jar
├── async-1.4.0.jar
├── asynchbase-1.7.0.jar
├── avro-1.7.4.jar
├── avro-ipc-1.7.4.jar
├── commons-cli-1.2.jar
├── commons-codec-1.8.jar
├── commons-collections-3.2.2.jar
├── commons-compress-1.4.1.jar
├── commons-dbcp-1.4.jar
├── commons-io-2.1.jar
├── commons-jexl-2.1.1.jar
├── commons-lang-2.5.jar
├── commons-logging-1.1.1.jar
├── commons-pool-1.5.4.jar
├── curator-client-2.6.0.jar
├── curator-framework-2.6.0.jar
├── curator-recipes-2.6.0.jar
├── derby-10.11.1.1.jar
├── flume-avro-source-1.8.0.jar
├── flume-dataset-sink-1.8.0.jar
├── flume-file-channel-1.8.0.jar
├── flume-hdfs-sink-1.8.0.jar
├── flume-hive-sink-1.8.0.jar
├── flume-http-sink-1.8.0.jar
├── flume-irc-sink-1.8.0.jar
├── flume-jdbc-channel-1.8.0.jar
├── flume-jms-source-1.8.0.jar
├── flume-kafka-channel-1.8.0.jar
├── flume-kafka-source-1.8.0.jar
├── flume-ng-auth-1.8.0.jar
├── flume-ng-configuration-1.8.0.jar
├── flume-ng-core-1.8.0.jar
├── flume-ng-elasticsearch-sink-1.8.0.jar
├── flume-ng-embedded-agent-1.8.0.jar
├── flume-ng-hbase-sink-1.8.0.jar
├── flume-ng-kafka-sink-1.8.0.jar
├── flume-ng-log4jappender-1.8.0.jar
├── flume-ng-morphline-solr-sink-1.8.0.jar
├── flume-ng-node-1.8.0.jar
├── flume-ng-sdk-1.8.0.jar
├── flume-scribe-source-1.8.0.jar
├── flume-spillable-memory-channel-1.8.0.jar
├── flume-taildir-source-1.8.0.jar
├── flume-thrift-source-1.8.0.jar
├── flume-tools-1.8.0.jar
├── flume-twitter-source-1.8.0.jar
├── geronimo-jms_1.1_spec-1.1.1.jar
├── gson-2.2.2.jar
├── guava-11.0.2.jar
├── httpclient-4.2.1.jar
├── httpcore-4.4.1.jar
├── irclib-1.10.jar
├── jackson-annotations-2.8.9.jar
├── jackson-core-2.8.9.jar
├── jackson-core-asl-1.9.3.jar
├── jackson-databind-2.8.9.jar
├── jackson-mapper-asl-1.9.3.jar
├── jetty-6.1.26.jar
├── jetty-util-6.1.26.jar
├── joda-time-2.9.9.jar
├── jopt-simple-3.2.jar
├── jsr305-1.3.9.jar
├── kafka_2.10-0.9.0.1.jar
├── kafka-clients-0.9.0.1.jar
├── kite-data-core-1.0.0.jar
├── kite-data-hbase-1.0.0.jar
├── kite-data-hive-1.0.0.jar
├── kite-hadoop-compatibility-1.0.0.jar
├── libthrift-0.9.3.jar
├── log4j-1.2.17.jar
├── lz4-1.2.0.jar
├── mapdb-0.9.9.jar
├── metrics-core-2.2.0.jar
├── mina-core-2.0.4.jar
├── netty-3.9.4.Final.jar
├── opencsv-2.3.jar
├── paranamer-2.3.jar
├── parquet-avro-1.4.1.jar
├── parquet-column-1.4.1.jar
├── parquet-common-1.4.1.jar
├── parquet-encoding-1.4.1.jar
├── parquet-format-2.0.0.jar
├── parquet-generator-1.4.1.jar
├── parquet-hadoop-1.4.1.jar
├── parquet-hive-bundle-1.4.1.jar
├── parquet-jackson-1.4.1.jar
├── protobuf-java-2.5.0.jar
├── scala-library-2.10.5.jar
├── serializer-2.7.2.jar
├── servlet-api-2.5-20110124.jar
├── slf4j-api-1.6.1.jar
├── slf4j-log4j12-1.6.1.jar
├── snappy-java-1.1.4.jar
├── twitter4j-core-3.0.3.jar
├── twitter4j-media-support-3.0.3.jar
├── twitter4j-stream-3.0.3.jar
├── velocity-1.7.jar
├── xalan-2.7.2.jar
├── xercesImpl-2.9.1.jar
├── xml-apis-1.3.04.jar
├── xz-1.0.jar
└── zkclient-0.7.jar
0 directories, 103 files
解压 jetty-6.1.26.jar
查源码
jetty-6.1.26orgmortbayjettyMain.class
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.mortbay.jetty;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.handler.ContextHandlerCollection;
import org.mortbay.jetty.servlet.ServletHandler;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.log.Log;
public class Main {
public Main() {
}
public static void main(String[] args) {
if (args.length < 1 || args.length > 3) {
System.err.println("Usage - java org.mortbay.jetty.Main [<addr>:]<port>");
System.err.println("Usage - java org.mortbay.jetty.Main [<addr>:]<port> docroot");
System.err.println("Usage - java org.mortbay.jetty.Main [<addr>:]<port> -webapp myapp.war");
System.err.println("Usage - java org.mortbay.jetty.Main [<addr>:]<port> -webapps webapps");
System.err.println("Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port>");
System.err.println("Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> docroot");
System.err.println("Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> -webapp myapp.war");
System.err.println("Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> -webapps webapps");
System.exit(1);
}
try {
Server server = new Server();
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
SocketConnector connector = new SocketConnector();
String address = args[0];
int colon = address.lastIndexOf(58);
if (colon < 0) {
connector.setPort(Integer.parseInt(address));
} else {
connector.setHost(address.substring(0, colon));
connector.setPort(Integer.parseInt(address.substring(colon + 1)));
}
server.setConnectors(new Connector[]{connector});
if (args.length < 3) {
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setResourceBase(args.length == 1 ? "." : args[1]);
ServletHandler servlet = new ServletHandler();
servlet.addServletWithMapping("org.mortbay.jetty.servlet.DefaultServlet", "/");
context.setHandler(servlet);
contexts.addHandler(context);
} else if ("-webapps".equals(args[1])) {
WebAppContext.addWebApplications(server, args[2], "org/mortbay/jetty/webapp/webdefault.xml", true, true);
} else if ("-webapp".equals(args[1])) {
WebAppContext webapp = new WebAppContext();
webapp.setWar(args[2]);
webapp.setContextPath("/");
contexts.addHandler(webapp);
}
server.start();
} catch (Exception var8) {
Log.warn("EXCEPTION ", var8);
}
}
}
由
org/mortbay/jetty/webapp/webdefault.xml
分析
jetty-6.1.26orgmortbayjettywebappwebdefault.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- ===================================================================== -->
<!-- This file contains the default descriptor for web applications. -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- The intent of this descriptor is to include jetty specific or common -->
<!-- configuration for all webapps. If a context has a webdefault.xml -->
<!-- descriptor, it is applied before the contexts own web.xml file -->
<!-- -->
<!-- A context may be assigned a default descriptor by: -->
<!-- + Calling WebApplicationContext.setDefaultsDescriptor -->
<!-- + Passed an arg to addWebApplications -->
<!-- -->
<!-- This file is used both as the resource within the jetty.jar (which is -->
<!-- used as the default if no explicit defaults descriptor is set) and it -->
<!-- is copied to the etc directory of the Jetty distro and explicitly -->
<!-- by the jetty.xml file. -->
<!-- -->
<!-- ===================================================================== -->
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true"
version="2.5">
<description>
Default web.xml file.
This file is applied to a Web application before it's own WEB_INF/web.xml file
</description>
<!-- ==================================================================== -->
<!-- Context params to control Session Cookies -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- UNCOMMENT TO ACTIVATE
<context-param>
<param-name>org.mortbay.jetty.servlet.SessionDomain</param-name>
<param-value>127.0.0.1</param-value>
</context-param>
<context-param>
<param-name>org.mortbay.jetty.servlet.SessionPath</param-name>
<param-value>/</param-value>
</context-param>
<context-param>
<param-name>org.mortbay.jetty.servlet.MaxAge</param-name>
<param-value>-1</param-value>
</context-param>
-->
<context-param>
<param-name>org.mortbay.jetty.webapp.NoTLDJarPattern</param-name>
<param-value>start.jar|ant-.*.jar|dojo-.*.jar|jetty-.*.jar|jsp-api-.*.jar|junit-.*.jar|servlet-api-.*.jar|dnsns.jar|rt.jar|jsse.jar|tools.jar|sunpkcs11.jar|sunjce_provider.jar|xerces.*.jar</param-value>
</context-param>
<!-- ==================================================================== -->
<!-- The default servlet. -->
<!-- This servlet, normally mapped to /, provides the handling for static -->
<!-- content, OPTIONS and TRACE methods for the context. -->
<!-- The following initParameters are supported: -->
<!-- -->
<!-- acceptRanges If true, range requests and responses are -->
<!-- supported -->
<!-- -->
<!-- dirAllowed If true, directory listings are returned if no -->
<!-- welcome file is found. Else 403 Forbidden. -->
<!-- -->
<!-- welcomeServlets If true, attempt to dispatch to welcome files -->
<!-- that are servlets, if no matching static -->
<!-- resources can be found. -->
<!-- -->
<!-- redirectWelcome If true, redirect welcome file requests -->
<!-- else use request dispatcher forwards -->
<!-- -->
<!-- gzip If set to true, then static content will be served-->
<!-- as gzip content encoded if a matching resource is -->
<!-- found ending with ".gz" -->
<!-- -->
<!-- resoureBase Can be set to replace the context resource base -->
<!-- -->
<!-- relativeResourceBase -->
<!-- Set with a pathname relative to the base of the -->
<!-- servlet context root. Useful for only serving -->
<!-- static content from only specific subdirectories. -->
<!-- -->
<!-- useFileMappedBuffer -->
<!-- If set to true (the default), a memory mapped -->
<!-- file buffer will be used to serve static content -->
<!-- when using an NIO connector. Setting this value -->
<!-- to false means that a direct buffer will be used -->
<!-- instead. If you are having trouble with Windows -->
<!-- file locking, set this to false. -->
<!-- -->
<!-- cacheControl If set, all static content will have this value -->
<!-- set as the cache-control header. -->
<!-- -->
<!-- maxCacheSize Maximum size of the static resource cache -->
<!-- -->
<!-- maxCachedFileSize Maximum size of any single file in the cache -->
<!-- -->
<!-- maxCachedFiles Maximum number of files in the cache -->
<!-- -->
<!-- cacheType "nio", "bio" or "both" to determine the type(s) -->
<!-- of resource cache. A bio cached buffer may be used-->
<!-- by nio but is not as efficient as a nio buffer. -->
<!-- An nio cached buffer may not be used by bio. -->
<!-- -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.mortbay.jetty.servlet.DefaultServlet</servlet-class>
<init-param>
<param-name>acceptRanges</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>dirAllowed</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>welcomeServlets</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>redirectWelcome</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>maxCacheSize</param-name>
<param-value>256000000</param-value>
</init-param>
<init-param>
<param-name>maxCachedFileSize</param-name>
<param-value>10000000</param-value>
</init-param>
<init-param>
<param-name>maxCachedFiles</param-name>
<param-value>1000</param-value>
</init-param>
<init-param>
<param-name>cacheType</param-name>
<param-value>both</param-value>
</init-param>
<init-param>
<param-name>gzip</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>useFileMappedBuffer</param-name>
<param-value>true</param-value>
</init-param>
<!--
<init-param>
<param-name>cacheControl</param-name>
<param-value>max-age=3600,public</param-value>
</init-param>
-->
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
<!-- ==================================================================== -->
<!-- JSP Servlet -->
<!-- This is the jasper JSP servlet from the jakarta project -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- The JSP page compiler and execution servlet, which is the mechanism -->
<!-- used by Glassfish to support JSP pages. Traditionally, this servlet -->
<!-- is mapped to URL patterh "*.jsp". This servlet supports the -->
<!-- following initialization parameters (default values are in square -->
<!-- brackets): -->
<!-- -->
<!-- checkInterval If development is false and reloading is true, -->
<!-- background compiles are enabled. checkInterval -->
<!-- is the time in seconds between checks to see -->
<!-- if a JSP page needs to be recompiled. [300] -->
<!-- -->
<!-- compiler Which compiler Ant should use to compile JSP -->
<!-- pages. See the Ant documenation for more -->
<!-- information. [javac] -->
<!-- -->
<!-- classdebuginfo Should the class file be compiled with -->
<!-- debugging information? [true] -->
<!-- -->
<!-- classpath What class path should I use while compiling -->
<!-- generated servlets? [Created dynamically -->
<!-- based on the current web application] -->
<!-- Set to ? to make the container explicitly set -->
<!-- this parameter. -->
<!-- -->
<!-- development Is Jasper used in development mode (will check -->
<!-- for JSP modification on every access)? [true] -->
<!-- -->
<!-- enablePooling Determines whether tag handler pooling is -->
<!-- enabled [true] -->
<!-- -->
<!-- fork Tell Ant to fork compiles of JSP pages so that -->
<!-- a separate JVM is used for JSP page compiles -->
<!-- from the one Tomcat is running in. [true] -->
<!-- -->
<!-- ieClassId The class-id value to be sent to Internet -->
<!-- Explorer when using <jsp:plugin> tags. -->
<!-- [clsid:8AD9C840-044E-11D1-B3E9-00805F499D93] -->
<!-- -->
<!-- javaEncoding Java file encoding to use for generating java -->
<!-- source files. [UTF-8] -->
<!-- -->
<!-- keepgenerated Should we keep the generated Java source code -->
<!-- for each page instead of deleting it? [true] -->
<!-- -->
<!-- logVerbosityLevel The level of detailed messages to be produced -->
<!-- by this servlet. Increasing levels cause the -->
<!-- generation of more messages. Valid values are -->
<!-- FATAL, ERROR, WARNING, INFORMATION, and DEBUG. -->
<!-- [WARNING] -->
<!-- -->
<!-- mappedfile Should we generate static content with one -->
<!-- print statement per input line, to ease -->
<!-- debugging? [false] -->
<!-- -->
<!-- -->
<!-- reloading Should Jasper check for modified JSPs? [true] -->
<!-- -->
<!-- suppressSmap Should the generation of SMAP info for JSR45 -->
<!-- debugging be suppressed? [false] -->
<!-- -->
<!-- dumpSmap Should the SMAP info for JSR45 debugging be -->
<!-- dumped to a file? [false] -->
<!-- False if suppressSmap is true -->
<!-- -->
<!-- scratchdir What scratch directory should we use when -->
<!-- compiling JSP pages? [default work directory -->
<!-- for the current web application] -->
<!-- -->
<!-- tagpoolMaxSize The maximum tag handler pool size [5] -->
<!-- -->
<!-- xpoweredBy Determines whether X-Powered-By response -->
<!-- header is added by generated servlet [false] -->
<!-- -->
<!-- If you wish to use Jikes to compile JSP pages: -->
<!-- Set the init parameter "compiler" to "jikes". Define -->
<!-- the property "-Dbuild.compiler.emacs=true" when starting Jetty -->
<!-- to cause Jikes to emit error messages in a format compatible with -->
<!-- Jasper. -->
<!-- If you get an error reporting that jikes can't use UTF-8 encoding, -->
<!-- try setting the init parameter "javaEncoding" to "ISO-8859-1". -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<servlet id="jsp">
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>logVerbosityLevel</param-name>
<param-value>DEBUG</param-value>
</init-param>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<!--
<init-param>
<param-name>classpath</param-name>
<param-value>?</param-value>
</init-param>
-->
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.jspf</url-pattern>
<url-pattern>*.jspx</url-pattern>
<url-pattern>*.xsp</url-pattern>
<url-pattern>*.JSP</url-pattern>
<url-pattern>*.JSPF</url-pattern>
<url-pattern>*.JSPX</url-pattern>
<url-pattern>*.XSP</url-pattern>
</servlet-mapping>
<!-- ==================================================================== -->
<!-- Dynamic Servlet Invoker. -->
<!-- This servlet invokes anonymous servlets that have not been defined -->
<!-- in the web.xml or by other means. The first element of the pathInfo -->
<!-- of a request passed to the envoker is treated as a servlet name for -->
<!-- an existing servlet, or as a class name of a new servlet. -->
<!-- This servlet is normally mapped to /servlet/* -->
<!-- This servlet support the following initParams: -->
<!-- -->
<!-- nonContextServlets If false, the invoker can only load -->
<!-- servlets from the contexts classloader. -->
<!-- This is false by default and setting this -->
<!-- to true may have security implications. -->
<!-- -->
<!-- verbose If true, log dynamic loads -->
<!-- -->
<!-- * All other parameters are copied to the -->
<!-- each dynamic servlet as init parameters -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- Uncomment for dynamic invocation
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>org.mortbay.jetty.servlet.Invoker</servlet-class>
<init-param>
<param-name>verbose</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>nonContextServlets</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>dynamicParam</param-name>
<param-value>anyValue</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping> <servlet-name>invoker</servlet-name> <url-pattern>/servlet/*</url-pattern> </servlet-mapping>
-->
<!-- ==================================================================== -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- ==================================================================== -->
<!-- Default MIME mappings -->
<!-- The default MIME mappings are provided by the mime.properties -->
<!-- resource in the org.mortbay.jetty.jar file. Additional or modified -->
<!-- mappings may be specified here -->
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<!-- UNCOMMENT TO ACTIVATE
<mime-mapping>
<extension>mysuffix</extension>
<mime-type>mymime/type</mime-type>
</mime-mapping>
-->
<!-- ==================================================================== -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- ==================================================================== -->
<locale-encoding-mapping-list>
<locale-encoding-mapping><locale>ar</locale><encoding>ISO-8859-6</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>be</locale><encoding>ISO-8859-5</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>bg</locale><encoding>ISO-8859-5</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>ca</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>cs</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>da</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>de</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>el</locale><encoding>ISO-8859-7</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>en</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>es</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>et</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>fi</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>fr</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>hr</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>hu</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>is</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>it</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>iw</locale><encoding>ISO-8859-8</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>ja</locale><encoding>Shift_JIS</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>ko</locale><encoding>EUC-KR</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>lt</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>lv</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>mk</locale><encoding>ISO-8859-5</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>nl</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>no</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>pl</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>pt</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>ro</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>ru</locale><encoding>ISO-8859-5</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>sh</locale><encoding>ISO-8859-5</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>sk</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>sl</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>sq</locale><encoding>ISO-8859-2</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>sr</locale><encoding>ISO-8859-5</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>sv</locale><encoding>ISO-8859-1</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>tr</locale><encoding>ISO-8859-9</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>uk</locale><encoding>ISO-8859-5</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>zh</locale><encoding>GB2312</encoding></locale-encoding-mapping>
<locale-encoding-mapping><locale>zh_TW</locale><encoding>Big5</encoding></locale-encoding-mapping>
</locale-encoding-mapping-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>Disable TRACE</web-resource-name>
<url-pattern>/</url-pattern>
<http-method>TRACE</http-method>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
</web-app>
├── jetty-6.1.26
│ ├── META-INF
│ │ ├── MANIFEST.MF
│ │ └── maven
│ │ └── org.mortbay.jetty
│ │ └── jetty
│ │ ├── pom.properties
│ │ └── pom.xml
│ └── org
│ └── mortbay
│ ├── io
│ │ ├── AbstractBuffer.class
│ │ ├── bio
│ │ │ ├── SocketEndPoint.class
│ │ │ ├── StreamEndPoint.class
│ │ │ └── StringEndPoint.class
│ │ ├── BufferCache$CachedBuffer.class
│ │ ├── BufferCache.class
│ │ ├── Buffer$CaseInsensitve.class
│ │ ├── Buffer.class
│ │ ├── BufferDateCache.class
│ │ ├── Buffers.class
│ │ ├── BufferUtil.class
│ │ ├── ByteArrayBuffer$CaseInsensitive.class
│ │ ├── ByteArrayBuffer.class
│ │ ├── ByteArrayEndPoint.class
│ │ ├── Connection.class
│ │ ├── EndPoint.class
│ │ ├── nio
│ │ │ ├── ChannelEndPoint.class
│ │ │ ├── DirectNIOBuffer.class
│ │ │ ├── IndirectNIOBuffer.class
│ │ │ ├── NIOBuffer.class
│ │ │ ├── SelectChannelEndPoint.class
│ │ │ ├── SelectChannelEndPoint$IdleTask.class
│ │ │ ├── SelectorManager$ChangeSelectableChannel.class
│ │ │ ├── SelectorManager$ChangeTask.class
│ │ │ ├── SelectorManager.class
│ │ │ ├── SelectorManager$SelectSet$1.class
│ │ │ └── SelectorManager$SelectSet.class
│ │ ├── Portable.class
│ │ ├── RuntimeIOException.class
│ │ ├── SimpleBuffers.class
│ │ ├── UncheckedPrintWriter.class
│ │ ├── View$CaseInsensitive.class
│ │ ├── View.class
│ │ └── WriterOutputStream.class
│ ├── jetty
│ │ ├── AbstractBuffers$1.class
│ │ ├── AbstractBuffers.class
│ │ ├── AbstractBuffers$ThreadBuffers.class
│ │ ├── AbstractConnector$Acceptor.class
│ │ ├── AbstractConnector.class
│ │ ├── AbstractGenerator.class
│ │ ├── AbstractGenerator$Output.class
│ │ ├── AbstractGenerator$OutputWriter.class
│ │ ├── bio
│ │ │ ├── SocketConnector.class
│ │ │ └── SocketConnector$Connection.class
│ │ ├── Connector.class
│ │ ├── deployer
│ │ │ ├── ConfigurationManager.class
│ │ │ ├── ContextDeployer$1.class
│ │ │ ├── ContextDeployer.class
│ │ │ ├── ContextDeployer$ScannerListener.class
│ │ │ ├── FileConfigurationManager.class
│ │ │ └── WebAppDeployer.class
│ │ ├── EncodedHttpURI.class
│ │ ├── encoding.properties
│ │ ├── EofException.class
│ │ ├── favicon.ico
│ │ ├── Generator.class
│ │ ├── handler
│ │ │ ├── AbstractHandler.class
│ │ │ ├── AbstractHandlerContainer.class
│ │ │ ├── AbstractStatisticsHandler.class
│ │ │ ├── ContextHandler.class
│ │ │ ├── ContextHandlerCollection.class
│ │ │ ├── ContextHandler$SContext.class
│ │ │ ├── DebugHandler.class
│ │ │ ├── DefaultHandler.class
│ │ │ ├── ErrorHandler.class
│ │ │ ├── HandlerCollection.class
│ │ │ ├── HandlerList.class
│ │ │ ├── HandlerWrapper.class
│ │ │ ├── MovedContextHandler$1.class
│ │ │ ├── MovedContextHandler.class
│ │ │ ├── MovedContextHandler$Redirector.class
│ │ │ ├── RequestLogHandler.class
│ │ │ ├── ResourceHandler.class
│ │ │ ├── RewriteHandler.class
│ │ │ └── StatisticsHandler.class
│ │ ├── Handler.class
│ │ ├── HandlerContainer.class
│ │ ├── HttpConnection$1.class
│ │ ├── HttpConnection.class
│ │ ├── HttpConnection$Output.class
│ │ ├── HttpConnection$OutputWriter.class
│ │ ├── HttpConnection$RequestHandler.class
│ │ ├── HttpContent.class
│ │ ├── HttpException.class
│ │ ├── HttpFields$1.class
│ │ ├── HttpFields$2.class
│ │ ├── HttpFields$3.class
│ │ ├── HttpFields$4.class
│ │ ├── HttpFields$5.class
│ │ ├── HttpFields.class
│ │ ├── HttpFields$Field.class
│ │ ├── HttpGenerator.class
│ │ ├── HttpHeaders.class
│ │ ├── HttpHeaderValues.class
│ │ ├── HttpMethods.class
│ │ ├── HttpOnlyCookie.class
│ │ ├── HttpParser.class
│ │ ├── HttpParser$EventHandler.class
│ │ ├── HttpParser$Input.class
│ │ ├── HttpSchemes.class
│ │ ├── HttpStatus.class
│ │ ├── HttpTokens.class
│ │ ├── HttpURI.class
│ │ ├── HttpVersions.class
│ │ ├── InclusiveByteRange.class
│ │ ├── LocalConnector.class
│ │ ├── Main.class
│ │ ├── mime.properties
│ │ ├── MimeTypes.class
│ │ ├── NCSARequestLog.class
│ │ ├── nio
│ │ │ ├── AbstractNIOConnector.class
│ │ │ ├── BlockingChannelConnector.class
│ │ │ ├── BlockingChannelConnector$Connection.class
│ │ │ ├── InheritedChannelConnector.class
│ │ │ ├── NIOConnector.class
│ │ │ ├── SelectChannelConnector$1.class
│ │ │ ├── SelectChannelConnector.class
│ │ │ ├── SelectChannelConnector$ConnectorEndPoint.class
│ │ │ └── SelectChannelConnector$RetryContinuation.class
│ │ ├── Parser.class
│ │ ├── Request$1.class
│ │ ├── Request.class
│ │ ├── RequestLog.class
│ │ ├── ResourceCache.class
│ │ ├── ResourceCache$Content.class
│ │ ├── Response$1.class
│ │ ├── Response.class
│ │ ├── Response$NullOutput.class
│ │ ├── RetryRequest.class
│ │ ├── security
│ │ │ ├── Authenticator.class
│ │ │ ├── B64Code.class
│ │ │ ├── BasicAuthenticator.class
│ │ │ ├── ClientCertAuthenticator.class
│ │ │ ├── Constraint.class
│ │ │ ├── ConstraintMapping.class
│ │ │ ├── Credential.class
│ │ │ ├── Credential$Crypt.class
│ │ │ ├── Credential$MD5.class
│ │ │ ├── DigestAuthenticator.class
│ │ │ ├── DigestAuthenticator$Digest.class
│ │ │ ├── FormAuthenticator$1.class
│ │ │ ├── FormAuthenticator.class
│ │ │ ├── FormAuthenticator$FormCredential.class
│ │ │ ├── HashSSORealm.class
│ │ │ ├── HashUserRealm$1.class
│ │ │ ├── HashUserRealm$2.class
│ │ │ ├── HashUserRealm.class
│ │ │ ├── HashUserRealm$KnownUser.class
│ │ │ ├── HashUserRealm$User.class
│ │ │ ├── HashUserRealm$WrappedUser.class
│ │ │ ├── HTAccessHandler.class
│ │ │ ├── HTAccessHandler$DummyPrincipal.class
│ │ │ ├── HTAccessHandler$HTAccess.class
│ │ │ ├── JDBCUserRealm.class
│ │ │ ├── Password.class
│ │ │ ├── PKCS12Import.class
│ │ │ ├── SecurityHandler$1.class
│ │ │ ├── SecurityHandler$2.class
│ │ │ ├── SecurityHandler.class
│ │ │ ├── SecurityHandler$NotChecked.class
│ │ │ ├── ServletSSL.class
│ │ │ ├── SslSocketConnector$CachedInfo.class
│ │ │ ├── SslSocketConnector.class
│ │ │ ├── SslSocketConnector$SslConnection$1.class
│ │ │ ├── SslSocketConnector$SslConnection.class
│ │ │ ├── SSORealm.class
│ │ │ ├── UnixCrypt.class
│ │ │ └── UserRealm.class
│ │ ├── Server$1.class
│ │ ├── Server.class
│ │ ├── Server$Graceful.class
│ │ ├── Server$ShutdownHookThread.class
│ │ ├── servlet
│ │ │ ├── AbstractSessionIdManager.class
│ │ │ ├── AbstractSessionManager$1.class
│ │ │ ├── AbstractSessionManager.class
│ │ │ ├── AbstractSessionManager$NullSessionContext.class
│ │ │ ├── AbstractSessionManager$Session.class
│ │ │ ├── AbstractSessionManager$SessionIf.class
│ │ │ ├── Context.class
│ │ │ ├── Context$SContext.class
│ │ │ ├── DefaultServlet.class
│ │ │ ├── DefaultServlet$NIOResourceCache.class
│ │ │ ├── DefaultServlet$UnCachedContent.class
│ │ │ ├── Dispatcher.class
│ │ │ ├── Dispatcher$ForwardAttributes.class
│ │ │ ├── Dispatcher$IncludeAttributes.class
│ │ │ ├── ErrorPageErrorHandler.class
│ │ │ ├── ErrorPageErrorHandler$ErrorCodeRange.class
│ │ │ ├── FilterHolder.class
│ │ │ ├── FilterHolder$Config.class
│ │ │ ├── FilterMapping.class
│ │ │ ├── HashSessionIdManager.class
│ │ │ ├── HashSessionManager$1.class
│ │ │ ├── HashSessionManager$2.class
│ │ │ ├── HashSessionManager.class
│ │ │ ├── HashSessionManager$ClassLoadingObjectInputStream.class
│ │ │ ├── HashSessionManager$Session.class
│ │ │ ├── Holder.class
│ │ │ ├── Invoker.class
│ │ │ ├── Invoker$Request.class
│ │ │ ├── PathMap.class
│ │ │ ├── PathMap$Entry.class
│ │ │ ├── ServletHandler$CachedChain.class
│ │ │ ├── ServletHandler$Chain.class
│ │ │ ├── ServletHandler.class
│ │ │ ├── ServletHandler$MruCache.class
│ │ │ ├── ServletHolder$1.class
│ │ │ ├── ServletHolder.class
│ │ │ ├── ServletHolder$Config.class
│ │ │ ├── ServletHolder$SingleThreadedWrapper.class
│ │ │ ├── ServletMapping.class
│ │ │ └── SessionHandler.class
│ │ ├── SessionIdManager.class
│ │ ├── SessionManager.class
│ │ ├── useragents
│ │ └── webapp
│ │ ├── Configuration.class
│ │ ├── JettyWebXmlConfiguration.class
│ │ ├── TagLibConfiguration.class
│ │ ├── WebAppClassLoader.class
│ │ ├── WebAppContext.class
│ │ ├── webdefault.xml
│ │ ├── WebInfConfiguration.class
│ │ └── WebXmlConfiguration.class
│ ├── resource
│ │ ├── BadResource.class
│ │ ├── FileResource.class
│ │ ├── JarFileResource.class
│ │ ├── JarResource$1.class
│ │ ├── JarResource.class
│ │ ├── Resource.class
│ │ ├── ResourceCollection.class
│ │ ├── ResourceFactory.class
│ │ └── URLResource.class
│ ├── servlet
│ │ └── jetty
│ │ ├── IncludableGzipFilter.class
│ │ ├── IncludableGzipFilter$IncludableGzipStream.class
│ │ └── IncludableGzipFilter$IncludableResponseWrapper.class
│ └── xml
│ ├── configure_6_0.dtd
│ ├── XmlConfiguration.class
│ ├── XmlParser$Attribute.class
│ ├── XmlParser.class
│ ├── XmlParser$Handler.class
│ ├── XmlParser$Node$1.class
│ ├── XmlParser$Node.class
│ └── XmlParser$NoopHandler.class
├── jetty-6.1.26.jar
├── jetty-util-6.1.26
│ ├── META-INF
│ │ ├── MANIFEST.MF
│ │ └── maven
│ │ └── org.mortbay.jetty
│ │ └── jetty-util
│ │ ├── pom.properties
│ │ └── pom.xml
│ └── org
│ └── mortbay
│ ├── component
│ │ ├── AbstractLifeCycle.class
│ │ ├── Container$1.class
│ │ ├── Container.class
│ │ ├── Container$Listener.class
│ │ ├── Container$Relationship.class
│ │ ├── LifeCycle.class
│ │ └── LifeCycle$Listener.class
│ ├── log
│ │ ├── Log$1.class
│ │ ├── Log.class
│ │ ├── Logger.class
│ │ ├── Slf4jLog.class
│ │ └── StdErrLog.class
│ ├── servlet
│ │ ├── CGI$1.class
│ │ ├── CGI.class
│ │ ├── CGI$EnvList.class
│ │ ├── ConcatServlet.class
│ │ ├── GzipFilter.class
│ │ ├── GzipFilter$GZIPResponseWrapper.class
│ │ ├── GzipFilter$GzipStream.class
│ │ ├── MultiPartFilter.class
│ │ ├── MultiPartFilter$Wrapper.class
│ │ ├── NoJspServlet.class
│ │ ├── ProxyServlet.class
│ │ ├── ProxyServlet$Transparent.class
│ │ ├── RestFilter.class
│ │ ├── ThrottlingFilter.class
│ │ ├── UserAgentFilter.class
│ │ └── WelcomeFilter.class
│ ├── thread
│ │ ├── BoundedThreadPool.class
│ │ ├── BoundedThreadPool$PoolThread.class
│ │ ├── QueuedThreadPool$1.class
│ │ ├── QueuedThreadPool.class
│ │ ├── QueuedThreadPool$Lock.class
│ │ ├── QueuedThreadPool$PoolThread.class
│ │ ├── ThreadPool.class
│ │ ├── Timeout.class
│ │ └── Timeout$Task.class
│ └── util
│ ├── ajax
│ │ ├── AjaxFilter$1.class
│ │ ├── AjaxFilter$AjaxResponse.class
│ │ ├── AjaxFilter.class
│ │ ├── Continuation.class
│ │ ├── ContinuationSupport.class
│ │ ├── JSON$1.class
│ │ ├── JSON$2.class
│ │ ├── JSON.class
│ │ ├── JSON$Convertible.class
│ │ ├── JSON$Convertor.class
│ │ ├── JSONDateConvertor.class
│ │ ├── JSONEnumConvertor.class
│ │ ├── JSON$Generator.class
│ │ ├── JSON$Literal.class
│ │ ├── JSONObjectConvertor.class
│ │ ├── JSON$Output.class
│ │ ├── JSONPojoConvertor$1.class
│ │ ├── JSONPojoConvertor$2.class
│ │ ├── JSONPojoConvertor$3.class
│ │ ├── JSONPojoConvertor$4.class
│ │ ├── JSONPojoConvertor$5.class
│ │ ├── JSONPojoConvertor.class
│ │ ├── JSONPojoConvertorFactory.class
│ │ ├── JSONPojoConvertor$NumberType.class
│ │ ├── JSONPojoConvertor$Setter.class
│ │ ├── JSON$ReaderSource.class
│ │ ├── JSON$Source.class
│ │ ├── JSON$StringSource.class
│ │ └── WaitingContinuation.class
│ ├── Attributes.class
│ ├── AttributesMap.class
│ ├── ByteArrayISO8859Writer.class
│ ├── ByteArrayOutputStream2.class
│ ├── DateCache.class
│ ├── IntrospectionUtil.class
│ ├── IO$1.class
│ ├── IO.class
│ ├── IO$ClosedIS.class
│ ├── IO$Job.class
│ ├── IO$NullOS.class
│ ├── IO$NullWrite.class
│ ├── IO$Singleton.class
│ ├── LazyList.class
│ ├── Loader.class
│ ├── MultiException.class
│ ├── MultiMap.class
│ ├── MultiPartOutputStream.class
│ ├── MultiPartWriter.class
│ ├── QuotedStringTokenizer.class
│ ├── RolloverFileOutputStream$1.class
│ ├── RolloverFileOutputStream.class
│ ├── RolloverFileOutputStream$RollTask.class
│ ├── Scanner$1.class
│ ├── Scanner$BulkListener.class
│ ├── Scanner.class
│ ├── Scanner$DiscreteListener.class
│ ├── Scanner$Listener.class
│ ├── SingletonList.class
│ ├── SingletonList$SIterator.class
│ ├── StringMap$1.class
│ ├── StringMap.class
│ ├── StringMap$Node.class
│ ├── StringMap$NullEntry.class
│ ├── StringUtil.class
│ ├── TypeUtil.class
│ ├── URIUtil.class
│ ├── UrlEncoded.class
│ └── Utf8StringBuffer.class
├── jetty-util-6.1.26.jar
├── org-eclipse-jetty-servlets-source-8.1.3
│ ├── about.html
│ ├── META-INF
│ │ ├── eclipse.inf
│ │ ├── ECLIPSE_.RSA
│ │ ├── ECLIPSE_.SF
│ │ └── MANIFEST.MF
│ └── org
│ └── eclipse
│ └── jetty
│ └── servlets
│ ├── CGI.java
│ ├── CloseableDoSFilter.java
│ ├── ConcatServlet.java
│ ├── CrossOriginFilter.java
│ ├── DoSFilter.java
│ ├── GzipFilter.java
│ ├── IncludableGzipFilter.java
│ ├── jmx
│ │ ├── DoSFilter-mbean.properties
│ │ └── QoSFilter-mbean.properties
│ ├── MultiPartFilter.java
│ ├── ProxyServlet.java
│ ├── PutFilter.java
│ ├── QoSFilter.java
│ ├── UserAgentFilter.java
│ └── WelcomeFilter.java
└── org-eclipse-jetty-servlets-source-8.1.3.jar
42 directories, 377 files
java - Jetty Cross Origin Filter - Stack Overflow https://stackoverflow.com/questions/8303162/jetty-cross-origin-filter
Cross Origin Filter http://www.eclipse.org/jetty/documentation/current/cross-origin-filter.html
Contact the core Jetty developers at www.webtide.com
private support for your internal/customer projects ... custom extensions and distributions ... versioned snapshots for indefinite support ... scalability guidance for your apps and Ajax/Comet projects ... development services for sponsored feature development
- Classname:
org.eclipse.jetty.servlets.CrossOriginFilter
- Maven Artifact: org.eclipse.jetty:jetty-servlets
- Javadoc: http://www.eclipse.org/jetty/javadoc/9.4.12.v20180830/org/eclipse/jetty/servlets/CrossOriginFilter.html
HTTP requests made from a script are subject to well known restrictions, the most prominent being the same domain policy.
Firefox 3.5 introduced support for W3C’s Access Control for Cross-Site Requests specification, which requires a compliant client (for example, Firefox 3.5) and a compliant server (via this servlet filter).
This filter implements the required bits to support the server-side contract of the specification, and will allow a compliant client to perform cross-domain requests via the standard XMLHttpRequest object. If the client does not issue a compliant cross-domain request, this filter does nothing, and its overhead is the check of the presence of the cross-domain HTTP header.
This is extremely useful in CometD web applications where it is now possible to perform cross-domain long polling without using script injection (also known as the JSONP transport), and therefore removing all the downsides that the JSONP transport has (it’s chattier, does not react quickly to failures, has a message size limit, uses GET instead of POST, etc.).
You will need to put the jetty-servlets.jar
file onto your classpath. If you are creating a webapp, ensure that this jar is included in your webapp’s WEB-INF/lib
. Or, if you are running Jetty embedded you will need to ensure that jetty-servlets.jar
is on the execution classpath. You can download the jetty-servlets.jar
from the Maven Central Repository at https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-servlets/. It is also available as part of the Jetty distribution in the $JETTY_HOME/lib
directory.
This is a regular servlet filter that must be configured in web.xml
.
It supports the following configuration parameters:
- allowedOrigins
- A comma separated list of origins that are allowed to access the resources. Default value is: * (all origins)
- allowedMethods
- A comma separated list of HTTP methods that are allowed to be used when accessing the resources. Default value is: GET,POST,HEAD
- allowedHeaders
- A comma separated list of HTTP headers that are allowed to be specified when accessing the resources. Default value is: X-Requested-With,Content-Type,Accept,Origin
- allowCredentials
- A boolean indicating if the resource allows requests with credentials. Default value is: true
- preflightMaxAge
- The number of seconds that preflight requests can be cached by the client. Default value is 1800 seconds (30 minutes)
- chainPreflight
- If true preflight requests are chained to their target resource for normal handling (as an OPTION request). Otherwise the filter will response to the preflight. Default is true.
- exposedHeaders
- A comma separated list of HTTP headers that are allowed to be exposed on the client. Default value is the empty list.
A typical configuration could be:
<web-app>
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/cometd/*</url-pattern>
</filter-mapping>
</web-app>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>project</artifactId>
<groupId>org.mortbay.jetty</groupId>
<version>6.1.26</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<name>Jetty Server</name>
<description>Jetty server core</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-deps</id>
<phase>install</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-version}</version>
</artifactItem>
</artifactItems>
<outputDirectory>../../lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>clean</id>
<phase>clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<delete includeemptydirs="true">
<fileset dir="../../lib/" includes="${project.artifactId}-${project.version}.${project.packaging}" />
<fileset dir="../../lib/" includes="servlet-api-${servlet-version}.jar" />
<fileset dir="../../etc/" >
<include name="webdefault.xml"/>
<include name="jetty.xml"/>
<include name="jetty-bio.xml"/>
<include name="jetty-ssl.xml"/>
<include name="keystore"/>
<include name="jetty-stats.xml"/>
<include name="jetty-xinetd.xml"/>
<include name="realm.properties"/>
<include name="jdbcRealm.properties"/>
</fileset>
</delete>
</tasks>
</configuration>
</execution>
<execution>
<id>copyjar</id>
<phase>install</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<copy failonerror="false" file="target/${project.artifactId}-${project.version}.${project.packaging}" tofile="../../lib/${project.artifactId}-${project.version}.${project.packaging}" />
<copy failonerror="false" file="src/main/resources/org/mortbay/jetty/webapp/webdefault.xml" tofile="../../etc/webdefault.xml" />
<copy failonerror="false" includeEmptyDirs="false" todir="../../etc">
<flattenmapper />
<fileset dir="src/main/config/etc">
<include name="jetty.xml"/>
<include name="jetty-bio.xml"/>
<include name="jetty-xinetd.xml"/>
<include name="jetty-ssl.xml"/>
<include name="keystore"/>
<include name="jetty-stats.xml"/>
<include name="realm.properties"/>
<include name="jdbcRealm.properties"/>
</fileset>
</copy>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${maven-bundle-plugin-version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>manifest</goal>
</goals>
<configuration>
<instructions>
<Bundle-SymbolicName>org.mortbay.jetty.server</Bundle-SymbolicName>
<Bundle-RequiredExecutionEnvironment>J2SE-1.4</Bundle-RequiredExecutionEnvironment>
<Bundle-DocURL>http://jetty.mortbay.org</Bundle-DocURL>
<Import-Package>!org.mortbay.jetty.*,!org.mortbay.xml.*,!org.mortbay.resource.*,!org.mortbay.io.*,!org.mortbay.servlet.jetty.*,javax.servlet.resources;resolution:=optional,javax.servlet.jsp;resolution:=optional,org.apache.jasper.servlet;resolution:=optional,org.mortbay.jetty.handler.management;resolution:=optional,*</Import-Package>
</instructions>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<!--
Required for OSGI
-->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<id>artifact-jar</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
<execution>
<id>test-jar</id>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-version}</version>
</dependency>
</dependencies>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>project</artifactId>
<groupId>org.mortbay.jetty</groupId>
<version>6.1.26</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-util</artifactId>
<name>Jetty Utilities</name>
<description>Utility classes for Jetty</description>
<build>
<testResources>
<testResource>
<directory>src/test/java</directory>
<includes>
<include>**/*Test.java</include>
<include>org/mortbay/**/*.xml</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>clean</id>
<phase>clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<delete failonerror="false" file="../../lib/${project.artifactId}-${project.version}.${project.packaging}" />
<delete failonerror="false" file="../../etc/jetty-logging.xml" />
</tasks>
</configuration>
</execution>
<execution>
<id>copyjar</id>
<phase>install</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<copy failonerror="false" file="target/${project.artifactId}-${project.version}.${project.packaging}" todir="../../lib/" />
<copy failonerror="false" file="src/main/config/etc/jetty-logging.xml" todir="../../etc" />
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${maven-bundle-plugin-version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>manifest</goal>
</goals>
<configuration>
<instructions>
<Bundle-SymbolicName>org.mortbay.jetty.util</Bundle-SymbolicName>
<Bundle-RequiredExecutionEnvironment>J2SE-1.4</Bundle-RequiredExecutionEnvironment>
<Import-Package>!org.mortbay.*,org.slf4j;resolution:=optional,*</Import-Package>
<Bundle-DocURL>http://jetty.mortbay.org</Bundle-DocURL>
</instructions>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<!--
Required for OSGI
-->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty.servlets/source -->
<dependency>
<groupId>org.eclipse.jetty.servlets</groupId>
<artifactId>source</artifactId>
<version>8.1.3</version>
</dependency>
org-eclipse-jetty-servlets-source-8.1.3orgeclipsejettyservletsCrossOriginFilter.java
/*
* Copyright (c) 2009-2009 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.servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* <p>Implementation of the
* <a href="http://www.w3.org/TR/cors/">cross-origin resource sharing</a>.</p>
* <p>A typical example is to use this filter to allow cross-domain
* <a href="http://cometd.org">cometd</a> communication using the standard
* long polling transport instead of the JSONP transport (that is less
* efficient and less reactive to failures).</p>
* <p>This filter allows the following configuration parameters:
* <ul>
* <li><b>allowedOrigins</b>, a comma separated list of origins that are
* allowed to access the resources. Default value is <b>*</b>, meaning all
* origins.<br />
* If an allowed origin contains one or more * characters (for example
* http://*.domain.com), then "*" characters are converted to ".*", "."
* characters are escaped to "." and the resulting allowed origin
* interpreted as a regular expression.<br />
* Allowed origins can therefore be more complex expressions such as
* https?://*.domain.[a-z]{3} that matches http or https, multiple subdomains
* and any 3 letter top-level domain (.com, .net, .org, etc.).</li>
* <li><b>allowedMethods</b>, a comma separated list of HTTP methods that
* are allowed to be used when accessing the resources. Default value is
* <b>GET,POST</b></li>
* <li><b>allowedHeaders</b>, a comma separated list of HTTP headers that
* are allowed to be specified when accessing the resources. Default value
* is <b>X-Requested-With</b></li>
* <li><b>preflightMaxAge</b>, the number of seconds that preflight requests
* can be cached by the client. Default value is <b>1800</b> seconds, or 30
* minutes</li>
* <li><b>allowCredentials</b>, a boolean indicating if the resource allows
* requests with credentials. Default value is <b>false</b></li>
* </ul></p>
* <p>A typical configuration could be:
* <pre>
* <web-app ...>
* ...
* <filter>
* <filter-name>cross-origin</filter-name>
* <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
* </filter>
* <filter-mapping>
* <filter-name>cross-origin</filter-name>
* <url-pattern>/cometd/*</url-pattern>
* </filter-mapping>
* ...
* </web-app>
* </pre></p>
*
* @version $Revision$ $Date$
*/
public class CrossOriginFilter implements Filter
{
private static final Logger LOG = Log.getLogger(CrossOriginFilter.class);
// Request headers
private static final String ORIGIN_HEADER = "Origin";
public static final String ACCESS_CONTROL_REQUEST_METHOD_HEADER = "Access-Control-Request-Method";
public static final String ACCESS_CONTROL_REQUEST_HEADERS_HEADER = "Access-Control-Request-Headers";
// Response headers
public static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin";
public static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods";
public static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers";
public static final String ACCESS_CONTROL_MAX_AGE_HEADER = "Access-Control-Max-Age";
public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER = "Access-Control-Allow-Credentials";
// Implementation constants
public static final String ALLOWED_ORIGINS_PARAM = "allowedOrigins";
public static final String ALLOWED_METHODS_PARAM = "allowedMethods";
public static final String ALLOWED_HEADERS_PARAM = "allowedHeaders";
public static final String PREFLIGHT_MAX_AGE_PARAM = "preflightMaxAge";
public static final String ALLOW_CREDENTIALS_PARAM = "allowCredentials";
private static final String ANY_ORIGIN = "*";
private static final List<String> SIMPLE_HTTP_METHODS = Arrays.asList("GET", "POST", "HEAD");
private boolean anyOriginAllowed;
private List<String> allowedOrigins = new ArrayList<String>();
private List<String> allowedMethods = new ArrayList<String>();
private List<String> allowedHeaders = new ArrayList<String>();
private int preflightMaxAge = 0;
private boolean allowCredentials;
public void init(FilterConfig config) throws ServletException
{
String allowedOriginsConfig = config.getInitParameter(ALLOWED_ORIGINS_PARAM);
if (allowedOriginsConfig == null)
allowedOriginsConfig = "*";
String[] allowedOrigins = allowedOriginsConfig.split(",");
for (String allowedOrigin : allowedOrigins)
{
allowedOrigin = allowedOrigin.trim();
if (allowedOrigin.length() > 0)
{
if (ANY_ORIGIN.equals(allowedOrigin))
{
anyOriginAllowed = true;
this.allowedOrigins.clear();
break;
}
else
{
this.allowedOrigins.add(allowedOrigin);
}
}
}
String allowedMethodsConfig = config.getInitParameter(ALLOWED_METHODS_PARAM);
if (allowedMethodsConfig == null)
allowedMethodsConfig = "GET,POST,HEAD";
allowedMethods.addAll(Arrays.asList(allowedMethodsConfig.split(",")));
String allowedHeadersConfig = config.getInitParameter(ALLOWED_HEADERS_PARAM);
if (allowedHeadersConfig == null)
allowedHeadersConfig = "X-Requested-With,Content-Type,Accept,Origin";
allowedHeaders.addAll(Arrays.asList(allowedHeadersConfig.split(",")));
String preflightMaxAgeConfig = config.getInitParameter(PREFLIGHT_MAX_AGE_PARAM);
if (preflightMaxAgeConfig == null)
preflightMaxAgeConfig = "1800"; // Default is 30 minutes
try
{
preflightMaxAge = Integer.parseInt(preflightMaxAgeConfig);
}
catch (NumberFormatException x)
{
LOG.info("Cross-origin filter, could not parse '{}' parameter as integer: {}", PREFLIGHT_MAX_AGE_PARAM, preflightMaxAgeConfig);
}
String allowedCredentialsConfig = config.getInitParameter(ALLOW_CREDENTIALS_PARAM);
if (allowedCredentialsConfig == null)
allowedCredentialsConfig = "true";
allowCredentials = Boolean.parseBoolean(allowedCredentialsConfig);
if (LOG.isDebugEnabled())
{
LOG.debug("Cross-origin filter configuration: " +
ALLOWED_ORIGINS_PARAM + " = " + allowedOriginsConfig + ", " +
ALLOWED_METHODS_PARAM + " = " + allowedMethodsConfig + ", " +
ALLOWED_HEADERS_PARAM + " = " + allowedHeadersConfig + ", " +
PREFLIGHT_MAX_AGE_PARAM + " = " + preflightMaxAgeConfig + ", " +
ALLOW_CREDENTIALS_PARAM + " = " + allowedCredentialsConfig);
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
handle((HttpServletRequest)request, (HttpServletResponse)response, chain);
}
private void handle(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
{
String origin = request.getHeader(ORIGIN_HEADER);
// Is it a cross origin request ?
if (origin != null && isEnabled(request))
{
if (originMatches(origin))
{
if (isSimpleRequest(request))
{
LOG.debug("Cross-origin request to {} is a simple cross-origin request", request.getRequestURI());
handleSimpleResponse(request, response, origin);
}
else if (isPreflightRequest(request))
{
LOG.debug("Cross-origin request to {} is a preflight cross-origin request", request.getRequestURI());
handlePreflightResponse(request, response, origin);
}
else
{
LOG.debug("Cross-origin request to {} is a non-simple cross-origin request", request.getRequestURI());
handleSimpleResponse(request, response, origin);
}
}
else
{
LOG.debug("Cross-origin request to " + request.getRequestURI() + " with origin " + origin + " does not match allowed origins " + allowedOrigins);
}
}
chain.doFilter(request, response);
}
protected boolean isEnabled(HttpServletRequest request)
{
// WebSocket clients such as Chrome 5 implement a version of the WebSocket
// protocol that does not accept extra response headers on the upgrade response
for (Enumeration connections = request.getHeaders("Connection"); connections.hasMoreElements();)
{
String connection = (String)connections.nextElement();
if ("Upgrade".equalsIgnoreCase(connection))
{
for (Enumeration upgrades = request.getHeaders("Upgrade"); upgrades.hasMoreElements();)
{
String upgrade = (String)upgrades.nextElement();
if ("WebSocket".equalsIgnoreCase(upgrade))
return false;
}
}
}
return true;
}
private boolean originMatches(String originList)
{
if (anyOriginAllowed)
return true;
if (originList.trim().length() == 0)
return false;
String[] origins = originList.split(" ");
for (String origin : origins)
{
if (origin.trim().length() == 0)
continue;
for (String allowedOrigin : allowedOrigins)
{
if (allowedOrigin.contains("*"))
{
Matcher matcher = createMatcher(origin,allowedOrigin);
if (matcher.matches())
return true;
}
else if (allowedOrigin.equals(origin))
{
return true;
}
}
}
return false;
}
private Matcher createMatcher(String origin, String allowedOrigin)
{
String regex = parseAllowedWildcardOriginToRegex(allowedOrigin);
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(origin);
}
private String parseAllowedWildcardOriginToRegex(String allowedOrigin)
{
String regex = allowedOrigin.replace(".","\.");
return regex.replace("*",".*"); // we want to be greedy here to match multiple subdomains, thus we use .*
}
private boolean isSimpleRequest(HttpServletRequest request)
{
String method = request.getMethod();
if (SIMPLE_HTTP_METHODS.contains(method))
{
// TODO: implement better detection of simple headers
// The specification says that for a request to be simple, custom request headers must be simple.
// Here for simplicity I just check if there is a Access-Control-Request-Method header,
// which is required for preflight requests
return request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER) == null;
}
return false;
}
private boolean isPreflightRequest(HttpServletRequest request)
{
String method = request.getMethod();
if (!"OPTIONS".equalsIgnoreCase(method))
return false;
if (request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER) == null)
return false;
return true;
}
private void handleSimpleResponse(HttpServletRequest request, HttpServletResponse response, String origin)
{
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, origin);
if (allowCredentials)
response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
}
private void handlePreflightResponse(HttpServletRequest request, HttpServletResponse response, String origin)
{
boolean methodAllowed = isMethodAllowed(request);
if (!methodAllowed)
return;
boolean headersAllowed = areHeadersAllowed(request);
if (!headersAllowed)
return;
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, origin);
if (allowCredentials)
response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
if (preflightMaxAge > 0)
response.setHeader(ACCESS_CONTROL_MAX_AGE_HEADER, String.valueOf(preflightMaxAge));
response.setHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER, commify(allowedMethods));
response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_HEADER, commify(allowedHeaders));
}
private boolean isMethodAllowed(HttpServletRequest request)
{
String accessControlRequestMethod = request.getHeader(ACCESS_CONTROL_REQUEST_METHOD_HEADER);
LOG.debug("{} is {}", ACCESS_CONTROL_REQUEST_METHOD_HEADER, accessControlRequestMethod);
boolean result = false;
if (accessControlRequestMethod != null)
result = allowedMethods.contains(accessControlRequestMethod);
LOG.debug("Method {} is" + (result ? "" : " not") + " among allowed methods {}", accessControlRequestMethod, allowedMethods);
return result;
}
private boolean areHeadersAllowed(HttpServletRequest request)
{
String accessControlRequestHeaders = request.getHeader(ACCESS_CONTROL_REQUEST_HEADERS_HEADER);
LOG.debug("{} is {}", ACCESS_CONTROL_REQUEST_HEADERS_HEADER, accessControlRequestHeaders);
boolean result = true;
if (accessControlRequestHeaders != null)
{
String[] headers = accessControlRequestHeaders.split(",");
for (String header : headers)
{
boolean headerAllowed = false;
for (String allowedHeader : allowedHeaders)
{
if (header.trim().equalsIgnoreCase(allowedHeader.trim()))
{
headerAllowed = true;
break;
}
}
if (!headerAllowed)
{
result = false;
break;
}
}
}
LOG.debug("Headers [{}] are" + (result ? "" : " not") + " among allowed headers {}", accessControlRequestHeaders, allowedHeaders);
return result;
}
private String commify(List<String> strings)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < strings.size(); ++i)
{
if (i > 0) builder.append(",");
String string = strings.get(i);
builder.append(string);
}
return builder.toString();
}
public void destroy()
{
anyOriginAllowed = false;
allowedOrigins.clear();
allowedMethods.clear();
allowedHeaders.clear();
preflightMaxAge = 0;
allowCredentials = false;
}
}